/* global React, ReactDOM */

// =====================================================================
// PAGE MOUNT — wraps a page body in the APIO shell (GlobalNav + Sidebar +
// TopBar) and renders it. Each per-page HTML file calls this once.
//
// Usage:
//   <script>window.APIO_PAGE = { id: 'payee360', body: () => <Payee360/> };</script>
//
// Then loaded after all scripts: mountAPIOPage(window.APIO_PAGE)
// =====================================================================

const { Sidebar: ShellSidebar, TopBar: ShellTopBar, GlobalNav: ShellGlobalNav,
        Button: ShellButton, Icon: ShellIcon,
        TweaksPanel: ShellTweaksPanel, useTweaks: useShellTweaks,
        TweakSection: ShellTweakSection, TweakRadio: ShellTweakRadio,
        TweakToggle: ShellTweakToggle, HEADERS: ShellHEADERS } = window;
const { useState: useStateMount } = React;

function PageRoot({ pageId, renderBody, bare = false, actions }) {
  const t = window.APIO_TWEAKS || {};

  const [dept, setDept] = useStateMount(() => {
    try {
      const u = new URLSearchParams(location.search);
      const fromUrl = u.get('dept');
      if (fromUrl) return fromUrl;
      // SCREENSHOT MODE — ignore sessionStorage, always use default
      if (window.__APIO_FORCE_DEFAULT__) return window.__APIO_FORCE_DEFAULT__;
      return sessionStorage.getItem('apio-dept') || (window.__APIO_DEFAULT_DEPT__ || 'hhs');
    } catch { return 'hhs'; }
  });
  React.useEffect(() => {
    try { sessionStorage.setItem('apio-dept', dept); } catch {}
    window.__dept = dept;
  }, [dept]);

  // Apply runtime tweak overrides (font, paper, density) — same effect as
  // the old App.jsx TweaksRoot. Lives here so it runs on every page.
  React.useEffect(() => {
    const root = document.documentElement;
    if (t.paperTone === 'cool') {
      root.style.setProperty('--paper', '#f3f4f7');
      root.style.setProperty('--paper-dim', '#fafbfd');
      document.body.style.backgroundImage = '';
    } else if (t.paperTone === 'gridpaper') {
      root.style.setProperty('--paper', '#f5f4f1');
      root.style.setProperty('--paper-dim', '#fafaf7');
      document.body.style.backgroundImage = 'linear-gradient(var(--line) 1px, transparent 1px) 0 0 / 24px 24px, linear-gradient(90deg, var(--line) 1px, transparent 1px) 0 0 / 24px 24px';
    } else {
      // Redwood default
      root.style.setProperty('--paper', '#f5f4f1');
      root.style.setProperty('--paper-dim', '#fafaf7');
      document.body.style.backgroundImage = '';
    }
    if (t.fidelity === 'tidy') {
      // Redwood — Inter / Inter Tight everywhere (no Caveat for display)
      root.style.setProperty('--font-sketch', '"Inter", "Oracle Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif');
      root.style.setProperty('--font-display', '"Inter Tight", "Inter", "Oracle Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif');
    } else {
      // Legacy sketch fidelity (Comic Neue + Caveat) — still toggleable from tweaks panel
      root.style.setProperty('--font-sketch', '"Comic Sans MS", "Comic Neue", "Chalkboard SE", system-ui, sans-serif');
      root.style.setProperty('--font-display', '"Caveat", "Comic Sans MS", "Comic Neue", cursive');
    }
    const dens = t.density === 'compact' ? 0.85 : t.density === 'comfy' ? 1.15 : 1;
    root.style.setProperty('--space-3', (12 * dens) + 'px');
    root.style.setProperty('--space-4', (16 * dens) + 'px');
    root.style.setProperty('--space-5', (24 * dens) + 'px');
    let s = document.getElementById('twk-overrides');
    if (!s) { s = document.createElement('style'); s.id = 'twk-overrides'; document.head.appendChild(s); }
    const hideAnn = t.annotations === 'none';
    const lightAnn = t.annotations === 'light';
    s.textContent = `
      ${hideAnn ? '.margin-note, [data-redline], [data-todo] { display: none !important; }' : ''}
      ${lightAnn ? '.margin-note:nth-of-type(n+2) { display: none !important; }' : ''}
      ${!t.showRedlines ? '[data-redline] { display: none !important; }' : ''}
      ${!t.showTodos ? '[data-todo] { display: none !important; }' : ''}
    `;
    window.__tweakPaymentLayout = t.paymentLayout;
  }, []);

  const navigate = (id) => { window.goTo(id); };
  const goPayee = (id) => { try { sessionStorage.setItem('apio-picked-payee', id); } catch {} ; window.goTo('payee360'); };
  const goBatch = (id) => { try { sessionStorage.setItem('apio-picked-batch', id); } catch {} ; window.goTo('batch360'); };
  const goPmt   = ()   => { window.goTo('payment360'); };

  const body = renderBody({ dept, navigate, goPayee, goBatch, goPmt });

  if (bare) {
    return (
      <div style={{ minHeight: '100vh', background: 'var(--paper)' }} data-screen-label={pageId}>
        <main style={{ minHeight: '100vh', overflow: 'auto' }}>{body}</main>
      </div>
    );
  }

  if (pageId === 'springboard') {
    // Springboard is bare too — it IS the home, no chrome on top of it.
    return body;
  }

  const headerProps = (ShellHEADERS && ShellHEADERS[pageId]) || { title: pageId, breadcrumb: ['home'] };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', minHeight: '100vh', background: 'var(--paper)' }}>
      <ShellGlobalNav onHome={() => navigate('springboard')} page={pageId}/>
      <div style={{ display: 'flex', flex: 1, minHeight: 0 }}>
        <ShellSidebar active={pageId} dept={dept} onDept={setDept}/>
        <main style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }} data-screen-label={pageId}>
          <ShellTopBar {...headerProps} actions={actions}/>
          <div style={{ flex: 1, overflow: 'auto' }}>{body}</div>
        </main>
      </div>
    </div>
  );
}

// =====================================================================
// TweaksRoot — same panel that used to live in App.jsx. Mounted alongside
// the page so it appears on every screen. Persists via the host's EDITMODE
// block (each HTML has one of those).
// =====================================================================
function TweaksRoot() {
  const TWEAK_DEFAULTS = window.APIO_TWEAK_DEFAULTS;
  const [t, setTweak] = useShellTweaks(TWEAK_DEFAULTS);

  // mirror into a global so PageRoot's useEffect can read it
  React.useEffect(() => { window.APIO_TWEAKS = t; }, [t]);

  React.useEffect(() => {
    const root = document.documentElement;
    if (t.paperTone === 'cool') {
      root.style.setProperty('--paper', '#f3f4f7');
      root.style.setProperty('--paper-dim', '#fafbfd');
      document.body.style.backgroundImage = '';
    } else if (t.paperTone === 'gridpaper') {
      root.style.setProperty('--paper', '#f5f4f1');
      root.style.setProperty('--paper-dim', '#fafaf7');
      document.body.style.backgroundImage = 'linear-gradient(var(--line) 1px, transparent 1px) 0 0 / 24px 24px, linear-gradient(90deg, var(--line) 1px, transparent 1px) 0 0 / 24px 24px';
    } else {
      // Redwood default
      root.style.setProperty('--paper', '#f5f4f1');
      root.style.setProperty('--paper-dim', '#fafaf7');
      document.body.style.backgroundImage = '';
    }
    if (t.fidelity === 'tidy') {
      // Redwood — Inter / Inter Tight everywhere
      root.style.setProperty('--font-sketch', '"Inter", "Oracle Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif');
      root.style.setProperty('--font-display', '"Inter Tight", "Inter", "Oracle Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif');
    } else {
      // Legacy sketch fidelity
      root.style.setProperty('--font-sketch', '"Comic Sans MS", "Comic Neue", "Chalkboard SE", system-ui, sans-serif');
      root.style.setProperty('--font-display', '"Caveat", "Comic Sans MS", "Comic Neue", cursive');
    }
    const dens = t.density === 'compact' ? 0.85 : t.density === 'comfy' ? 1.15 : 1;
    root.style.setProperty('--space-3', (12 * dens) + 'px');
    root.style.setProperty('--space-4', (16 * dens) + 'px');
    root.style.setProperty('--space-5', (24 * dens) + 'px');
    let s = document.getElementById('twk-overrides');
    if (!s) { s = document.createElement('style'); s.id = 'twk-overrides'; document.head.appendChild(s); }
    const hideAnn = t.annotations === 'none';
    const lightAnn = t.annotations === 'light';
    s.textContent = `
      ${hideAnn ? '.margin-note, [data-redline], [data-todo] { display: none !important; }' : ''}
      ${lightAnn ? '.margin-note:nth-of-type(n+2) { display: none !important; }' : ''}
      ${!t.showRedlines ? '[data-redline] { display: none !important; }' : ''}
      ${!t.showTodos ? '[data-todo] { display: none !important; }' : ''}
    `;
    window.__tweakPaymentLayout = t.paymentLayout;
  }, [t]);

  return (
    <ShellTweaksPanel title="Tweaks">
      <ShellTweakSection label="Fidelity"/>
      <ShellTweakRadio label="Hand"    value={t.fidelity}    options={['sketch','tidy']}                onChange={(v) => setTweak('fidelity', v)}/>
      <ShellTweakRadio label="Paper"   value={t.paperTone}   options={['warm','cool','gridpaper']}      onChange={(v) => setTweak('paperTone', v)}/>
      <ShellTweakRadio label="Density" value={t.density}     options={['compact','regular','comfy']}    onChange={(v) => setTweak('density', v)}/>

      <ShellTweakSection label="Annotations"/>
      <ShellTweakRadio label="Volume"  value={t.annotations} options={['heavy','light','none']}         onChange={(v) => setTweak('annotations', v)}/>
      <ShellTweakToggle label="Show redlines" value={t.showRedlines} onChange={(v) => setTweak('showRedlines', v)}/>
      <ShellTweakToggle label="Show TODOs"    value={t.showTodos}    onChange={(v) => setTweak('showTodos', v)}/>

      <ShellTweakSection label="Payment Req 360"/>
      <ShellTweakRadio label="Layout"  value={t.paymentLayout} options={['left','right','stacked','tabs']} onChange={(v) => setTweak('paymentLayout', v)}/>
    </ShellTweaksPanel>
  );
}

// =====================================================================
// mountAPIOPage — single entry point each page HTML calls.
// =====================================================================
function mountAPIOPage(opts) {
  const root = document.getElementById('root');
  if (!root) { console.error('[apio] no #root'); return; }
  const tree = (
    <>
      <PageRoot pageId={opts.id} renderBody={opts.body} bare={!!opts.bare} actions={opts.actions}/>
      <TweaksRoot/>
    </>
  );
  ReactDOM.createRoot(root).render(tree);
}

window.mountAPIOPage = mountAPIOPage;
