// AdminApp — responsive root shell.
//   ≥ 900px: sidebar + topbar + desktop pages
//   < 900px: sticky header + bottom tab bar + card-list mobile pages
// Single source of truth. Same data, same tokens. Switches live on resize.

function useViewportWidth() {
  const [w, setW] = React.useState(typeof window !== 'undefined' ? window.innerWidth : 1440);
  React.useEffect(() => {
    const onResize = () => setW(window.innerWidth);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return w;
}

function AdminApp() {
  const [page, setPage] = React.useState('overview');
  const [role, setRole] = React.useState('all');
  const density = 'compact';
  const w = useViewportWidth();
  const isMobile = w < 900;

  const pageTitles = {
    overview:    { t: 'Overview',    s: 'Print & Send ops at a glance' },
    signups:     { t: 'Signups',     s: 'Waitlist inbox from printandsend.com' },
    customers:   { t: 'Customers',   s: '12 active shops on monthly budgets' },
    campaigns:   { t: 'Campaigns',   s: 'Postcard drops — schedule & status' },
    production:  { t: 'Production',  s: "Kent facility · Chad's floor" },
    attribution: { t: 'Attribution', s: 'Twilio call tracking per campaign' },
    finance:     { t: 'Finance',     s: 'MRR, invoices & margin' },
  };

  if (isMobile) {
    return <MobileShell page={page} setPage={setPage} pageTitles={pageTitles} />;
  }

  const PageComp = {
    overview: Overview, signups: Signups, customers: Customers,
    campaigns: Campaigns, production: Production,
    attribution: Attribution, finance: Finance,
  }[page];

  return (
    <div style={{
      display: 'flex', background: '#0a0a0a', color: '#f5f3ef',
      fontFamily: 'Inter, -apple-system, sans-serif',
      width: '100%', height: '100vh', overflow: 'hidden',
    }}>
      <Sidebar page={page} setPage={setPage} role={role} setRole={setRole} />
      <main style={{ flex: 1, minWidth: 0, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
        <Topbar
          title={pageTitles[page].t}
          subtitle={pageTitles[page].s}
          density={density}
          right={
            <div style={{ display: 'flex', gap: 8 }}>
              <button style={btnSecondary}>Last 30d ▾</button>
              <button style={btnPrimary}><Icon.plus /> New campaign</button>
            </div>
          }
        />
        <div style={{ flex: 1 }}>
          <PageComp density={density} />
        </div>
      </main>
    </div>
  );
}

// ── Mobile shell ──────────────────────────────────────────────────────
// Sticky header with logo + search + overflow menu. 5-tab bottom nav for
// Home / Signups / Drops / Press / Shops. Attribution + Finance live behind
// the overflow (☰) menu. Safe-area insets respected for notched devices.
function MobileShell({ page, setPage, pageTitles }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const tabs = [
    { id: 'overview',   label: 'Home',    icon: Icon.dash },
    { id: 'signups',    label: 'Signups', icon: Icon.inbox, badge: 18 },
    { id: 'campaigns',  label: 'Drops',   icon: Icon.mail },
    { id: 'production', label: 'Press',   icon: Icon.press, badge: 6 },
    { id: 'customers',  label: 'Shops',   icon: Icon.users },
  ];
  const extraLinks = [
    { id: 'attribution', label: 'Attribution', icon: Icon.phone },
    { id: 'finance',     label: 'Finance',     icon: Icon.finance },
  ];
  const PageComp = {
    overview:    MPage_Overview,
    signups:     MPage_Signups,
    campaigns:   MPage_Campaigns,
    production:  MPage_Production,
    customers:   MPage_Customers,
    attribution: MPage_Attribution,
    finance:     MPage_Finance,
  }[page];

  return (
    <div style={{
      minHeight: '100dvh', width: '100%',
      background: '#0a0a0a', color: '#f5f3ef',
      fontFamily: 'Inter, -apple-system, sans-serif',
      display: 'flex', flexDirection: 'column',
      paddingBottom: 'calc(72px + env(safe-area-inset-bottom, 0px))',
    }}>
      <header style={{
        padding: 'calc(14px + env(safe-area-inset-top, 0px)) 16px 14px',
        display: 'flex', alignItems: 'center', gap: 10,
        borderBottom: '1px solid rgba(255,255,255,0.08)',
        position: 'sticky', top: 0, zIndex: 10,
        background: 'rgba(10,10,10,0.92)', backdropFilter: 'blur(12px)',
        WebkitBackdropFilter: 'blur(12px)',
      }}>
        <div style={{
          width: 28, height: 28, background: '#ff5a1f', borderRadius: 4,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#000', fontWeight: 900, fontSize: 14,
          transform: 'rotate(-3deg)', fontFamily: 'Archivo, sans-serif',
          flexShrink: 0,
        }}>P</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'Archivo, sans-serif', fontWeight: 900, fontSize: 17, letterSpacing: '-0.02em', lineHeight: 1, color: '#f5f3ef' }}>
            {pageTitles[page].t}
          </div>
          <div style={{ fontSize: 10, color: '#ff5a1f', fontFamily: 'JetBrains Mono, monospace', fontWeight: 700, letterSpacing: '0.14em', marginTop: 3 }}>
            PRINT &amp; SEND · ADMIN
          </div>
        </div>
        <button aria-label="Search" style={{
          width: 36, height: 36, borderRadius: 999,
          background: '#141414', border: '1px solid rgba(255,255,255,0.1)',
          color: '#f5f3ef', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          flexShrink: 0,
        }}><Icon.search /></button>
        <button aria-label="Menu" onClick={() => setMenuOpen(!menuOpen)} style={{
          width: 36, height: 36, borderRadius: 999,
          background: menuOpen ? '#ff5a1f' : '#141414',
          border: '1px solid rgba(255,255,255,0.1)',
          color: menuOpen ? '#0a0a0a' : '#f5f3ef',
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          flexShrink: 0,
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><line x1="4" y1="7" x2="20" y2="7"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="17" x2="20" y2="17"/></svg>
        </button>
      </header>

      {menuOpen && (
        <div style={{
          position: 'sticky', top: 64, zIndex: 9,
          background: '#141414', borderBottom: '1px solid rgba(255,255,255,0.08)',
          padding: 8,
        }}>
          {extraLinks.map(l => {
            const IconC = l.icon;
            return (
              <button key={l.id} onClick={() => { setPage(l.id); setMenuOpen(false); }} style={{
                width: '100%', display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 12px', background: 'transparent', border: 'none',
                color: page === l.id ? '#ff5a1f' : 'rgba(245,243,239,0.85)',
                fontSize: 13, fontWeight: 600, cursor: 'pointer', borderRadius: 8,
                textAlign: 'left',
              }}>
                <IconC />
                <span>{l.label}</span>
              </button>
            );
          })}
        </div>
      )}

      <main style={{ flex: 1, minWidth: 0 }}>
        <PageComp />
      </main>

      <nav style={{
        position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 20,
        background: 'rgba(10,10,10,0.92)', backdropFilter: 'blur(16px)',
        WebkitBackdropFilter: 'blur(16px)',
        borderTop: '1px solid rgba(255,255,255,0.08)',
        display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)',
        padding: '8px 4px calc(10px + env(safe-area-inset-bottom, 0px))',
      }}>
        {tabs.map(t => {
          const active = page === t.id;
          const IconC = t.icon;
          return (
            <button key={t.id} onClick={() => setPage(t.id)} style={{
              border: 'none', background: 'transparent',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              padding: '6px 0', cursor: 'pointer', position: 'relative',
              color: active ? '#ff5a1f' : 'rgba(245,243,239,0.55)',
            }}>
              <div style={{ position: 'relative' }}>
                <IconC />
                {t.badge && (
                  <span style={{
                    position: 'absolute', top: -4, right: -8,
                    background: '#ff5a1f', color: '#0a0a0a',
                    fontSize: 9, fontWeight: 800, fontFamily: 'JetBrains Mono, monospace',
                    padding: '1px 4px', borderRadius: 999, minWidth: 14, textAlign: 'center',
                    lineHeight: 1.3,
                  }}>{t.badge}</span>
                )}
              </div>
              <span style={{
                fontSize: 10, fontWeight: active ? 700 : 500,
                fontFamily: 'Inter, sans-serif',
              }}>{t.label}</span>
            </button>
          );
        })}
      </nav>
    </div>
  );
}

window.AdminApp = AdminApp;
