/* eslint-disable */
/* Artifex Heritage — Tweaks
   Cross-page tweaks persisted in localStorage. Applied as CSS custom
   properties on :root via an injected <style id="ah-tweaks"> tag so
   the design-system fonts pick them up. */

const AH_TWEAK_DEFAULTS = {
  display: 'Tid Display',
  body: 'Inter',
  heroSize: 108,
  gridCols: 4,
};

const AH_DISPLAY_FONTS = {
  'Tid Display':        "'Tid Display', 'Times New Roman', serif",
  'EB Garamond':        "'EB Garamond', 'Adobe Garamond Pro', serif",
  'Libre Caslon Text':  "'Libre Caslon Text', 'Big Caslon', serif",
  'Lora':               "'Lora', 'Charter', serif",
};

const AH_BODY_FONTS = {
  'Inter':        "'Inter', 'Suisse Int\\'l', system-ui, sans-serif",
  'Manrope':      "'Manrope', 'Söhne', system-ui, sans-serif",
  'IBM Plex Sans':"'IBM Plex Sans', 'Neue Haas Grotesk', system-ui, sans-serif",
};

function ahLoadTweaks() {
  try {
    const raw = localStorage.getItem('ah-tweaks');
    return raw ? { ...AH_TWEAK_DEFAULTS, ...JSON.parse(raw) } : { ...AH_TWEAK_DEFAULTS };
  } catch (e) { return { ...AH_TWEAK_DEFAULTS }; }
}
function ahSaveTweaks(t) {
  try { localStorage.setItem('ah-tweaks', JSON.stringify(t)); } catch (e) {}
}
function ahApplyTweaks(t) {
  let style = document.getElementById('ah-tweaks');
  if (!style) {
    style = document.createElement('style');
    style.id = 'ah-tweaks';
    document.head.appendChild(style);
  }
  const disp = AH_DISPLAY_FONTS[t.display] || AH_DISPLAY_FONTS['Tid Display'];
  const body = AH_BODY_FONTS[t.body] || AH_BODY_FONTS['Inter'];
  style.textContent = `
    :root {
      --tw-display: ${disp};
      --tw-body: ${body};
      --tw-hero-size: ${t.heroSize}px;
      --tw-grid-cols: ${t.gridCols};
    }
  `;
}

// Apply immediately so pages paint with the user's settings.
(function () {
  const t = ahLoadTweaks();
  ahApplyTweaks(t);
})();

/* React-level hook + panel */
function useAHTweaks() {
  const [tweaks, setTweaks] = React.useState(ahLoadTweaks());
  const update = (patch) => {
    setTweaks(t => {
      const next = { ...t, ...patch };
      ahSaveTweaks(next);
      ahApplyTweaks(next);
      return next;
    });
  };
  return [tweaks, update];
}

function TweaksPanel() {
  const [tweaks, update] = useAHTweaks();
  const [active, setActive] = React.useState(false);
  const [dragging, setDragging] = React.useState(false);
  const panelRef = React.useRef(null);
  const [pos, setPos] = React.useState(null);

  React.useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setActive(true);
      else if (d.type === '__deactivate_edit_mode') setActive(false);
    };
    window.addEventListener('message', onMsg);
    // Only announce after listener is registered
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const dismiss = () => {
    setActive(false);
    window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
  };

  // drag
  const onMouseDown = (e) => {
    const rect = panelRef.current.getBoundingClientRect();
    const offX = e.clientX - rect.left, offY = e.clientY - rect.top;
    setDragging(true);
    const onMove = (ev) => {
      setPos({ left: ev.clientX - offX, top: ev.clientY - offY });
    };
    const onUp = () => {
      setDragging(false);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  };

  if (!active) return null;

  const pStyle = pos
    ? { left: pos.left, top: pos.top, right: 'auto', bottom: 'auto' }
    : { right: 24, bottom: 24 };

  const panelStyle = {
    position: 'fixed', width: 290, zIndex: 999999,
    background: '#fff', color: '#000',
    border: '1px solid rgba(0,0,0,0.14)',
    boxShadow: '0 20px 60px rgba(0,0,0,0.12)',
    fontFamily: "'Inter', system-ui, sans-serif",
    ...pStyle,
  };

  const headStyle = {
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '14px 16px', borderBottom: '1px solid rgba(0,0,0,0.1)',
    cursor: 'move', userSelect: 'none',
    fontSize: 11, letterSpacing: 1.4, textTransform: 'uppercase', color: '#000',
  };

  const bodyStyle = { padding: '18px 16px 22px', display: 'flex', flexDirection: 'column', gap: 18 };
  const rowStyle = { display: 'flex', flexDirection: 'column', gap: 8 };
  const lblStyle = { fontSize: 10, letterSpacing: 1.2, textTransform: 'uppercase', color: '#000101' };
  const radioWrap = { display: 'grid', gap: 2 };

  const radioBtn = (active) => ({
    padding: '7px 10px',
    border: '1px solid ' + (active ? '#000' : 'rgba(0,0,0,0.14)'),
    background: active ? '#000' : '#fff',
    color: active ? '#fff' : '#000',
    fontFamily: 'inherit', fontSize: 12, letterSpacing: 0.2,
    cursor: 'pointer', textAlign: 'left',
    borderRadius: 0, marginBottom: -1,
  });

  return (
    <div ref={panelRef} style={panelStyle}>
      <div style={headStyle} onMouseDown={onMouseDown}>
        <span>Tweaks</span>
        <button
          style={{ border: 0, background: 'transparent', cursor: 'pointer', fontSize: 18, lineHeight: 1, padding: 0, color: '#000' }}
          onClick={dismiss}
          aria-label="Close tweaks"
        >×</button>
      </div>
      <div style={bodyStyle}>
        <div style={rowStyle}>
          <div style={lblStyle}>Display font</div>
          <div style={radioWrap}>
            {Object.keys(AH_DISPLAY_FONTS).map(f => (
              <button key={f} style={{ ...radioBtn(tweaks.display === f), fontFamily: AH_DISPLAY_FONTS[f], fontSize: 16 }}
                      onClick={() => update({ display: f })}>{f}</button>
            ))}
          </div>
        </div>

        <div style={rowStyle}>
          <div style={lblStyle}>Body font</div>
          <div style={radioWrap}>
            {Object.keys(AH_BODY_FONTS).map(f => (
              <button key={f} style={{ ...radioBtn(tweaks.body === f), fontFamily: AH_BODY_FONTS[f] }}
                      onClick={() => update({ body: f })}>{f}</button>
            ))}
          </div>
        </div>

        <div style={rowStyle}>
          <div style={{ ...lblStyle, display: 'flex', justifyContent: 'space-between' }}>
            <span>Hero display size</span>
            <span style={{ color: '#000' }}>{tweaks.heroSize}px</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0 }}>
            {[80, 108, 140].map(v => (
              <button key={v} style={radioBtn(tweaks.heroSize === v)} onClick={() => update({ heroSize: v })}>{v}px</button>
            ))}
          </div>
        </div>

        <div style={rowStyle}>
          <div style={lblStyle}>Work grid density</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0 }}>
            {[{ n: 4, l: '4-col' }, { n: 3, l: '3-col' }, { n: 2, l: '2-col' }].map(o => (
              <button key={o.n} style={radioBtn(tweaks.gridCols === o.n)} onClick={() => update({ gridCols: o.n })}>{o.l}</button>
            ))}
          </div>
        </div>

        <div style={{ fontSize: 10.5, lineHeight: 1.5, color: '#000101', letterSpacing: 0.2, fontStyle: 'italic', borderTop: '1px solid rgba(0,0,0,0.08)', paddingTop: 12 }}>
          Changes persist across pages. Body font and Hero size preview typographic variations without leaving the Artifex chassis.
        </div>
      </div>
    </div>
  );
}

window.TweaksPanel = TweaksPanel;
