// Vault Showcase shell — chrome + stage + device frames.
// Switches: screen (Home/Pricing/Security/App) · device (Desktop/Mobile) · theme (Light/Dark)
// Reuses every screen + token already built. No new data.

(function () {
  const { VAULT_DARK, VAULT_LIGHT, Icon, mono, sans } = window;
  const { Landing, Pricing, Security } = window;
  const { VaultPhone, WalletHome, SendConfirm, CardDetail, Receipt, TransactionDetail, KYCCapture, Onboarding } = window;

  const STUDIO = {
    dark: { bg: 'oklch(0.12 0.004 250)', grid: 'oklch(1 0 0 / 0.025)' },
    light: { bg: 'oklch(0.92 0.004 80)', grid: 'oklch(0 0 0 / 0.03)' },
  };

  const SCREENS = [
    { id: 'home', label: 'Home', path: '' },
    { id: 'pricing', label: 'Pricing', path: '/pricing' },
    { id: 'security', label: 'Security', path: '/security' },
    { id: 'app', label: 'App', path: '/app' },
  ];

  const APP_SCREENS = [
    { id: 'onboarding', label: 'Onboarding', comp: Onboarding },
    { id: 'kyc', label: 'KYC capture', comp: KYCCapture },
    { id: 'wallet', label: 'Wallet home', comp: WalletHome },
    { id: 'send', label: 'Send · confirm', comp: SendConfirm },
    { id: 'receipt', label: 'Receipt', comp: Receipt },
    { id: 'transaction', label: 'Transaction', comp: TransactionDetail },
    { id: 'card', label: 'Card detail', comp: CardDetail },
  ];

  // fit-to-stage scaler
  function useFit(w, h, deps, maxScale = 1) {
    const ref = React.useRef(null);
    const [scale, setScale] = React.useState(1);
    React.useEffect(() => {
      const el = ref.current;
      if (!el) return;
      const compute = () => {
        const pad = 48;
        const aw = el.clientWidth - pad, ah = el.clientHeight - pad;
        setScale(Math.min(aw / w, ah / h, maxScale));
      };
      compute();
      const ro = new ResizeObserver(compute);
      ro.observe(el);
      return () => ro.disconnect();
    }, deps);
    return [ref, scale];
  }

  // ── themed browser frame ────────────────────────────────────
  function BrowserFrame({ t, url, children }) {
    return (
      <div style={{ width: 1280, height: 800, borderRadius: 16, overflow: 'hidden', background: t.bg,
        border: `1px solid ${t.name === 'dark' ? 'oklch(1 0 0 / 0.10)' : 'oklch(0 0 0 / 0.10)'}`,
        boxShadow: '0 50px 100px oklch(0 0 0 / 0.45), 0 0 0 1px oklch(0 0 0 / 0.2)' }}>
        {/* chrome bar */}
        <div style={{ height: 46, display: 'flex', alignItems: 'center', gap: 14, padding: '0 16px',
          background: t.surface2, borderBottom: `1px solid ${t.hairline}` }}>
          <div style={{ display: 'flex', gap: 8 }}>
            {['#ff5f57', '#febc2e', '#28c840'].map(c => <div key={c} style={{ width: 12, height: 12, borderRadius: 6, background: c, opacity: t.name === 'dark' ? 0.9 : 1 }} />)}
          </div>
          <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 18px', borderRadius: 8, background: t.bg, border: `1px solid ${t.hairline}`, minWidth: 320, justifyContent: 'center' }}>
              <span style={{ color: t.text3 }}>{Icon.lock(11)}</span>
              <span style={{ fontFamily: mono, fontSize: 12.5, color: t.text2 }}>vault.ng{url}</span>
            </div>
          </div>
          <div style={{ width: 54, display: 'flex', justifyContent: 'flex-end', gap: 14, color: t.text3 }}>{Icon.plus(16)}</div>
        </div>
        {/* viewport */}
        <div className="vmk-scroll" style={{ height: 754, overflowY: 'auto', overflowX: 'hidden' }}>{children}</div>
      </div>
    );
  }

  // ── bare phone shell (for marketing-in-mobile, no iOS chrome) ─
  function PhoneShell({ t, children }) {
    return (
      <div style={{ width: 380, height: 800, borderRadius: 46, padding: 10, background: t.name === 'dark' ? '#000' : '#111',
        boxShadow: '0 50px 100px oklch(0 0 0 / 0.5), 0 0 0 1px oklch(0 0 0 / 0.3)' }}>
        <div className="vmk-scroll" style={{ width: '100%', height: '100%', borderRadius: 38, overflow: 'auto', background: t.bg, position: 'relative' }}>
          {children}
        </div>
      </div>
    );
  }

  // ── segmented control ───────────────────────────────────────
  function Segment({ t, items, value, onChange, icons }) {
    return (
      <div style={{ display: 'inline-flex', padding: 3, borderRadius: 11, background: t.name === 'dark' ? 'oklch(1 0 0 / 0.05)' : 'oklch(0 0 0 / 0.04)', border: `1px solid ${t.hairline}` }}>
        {items.map(it => {
          const active = value === it.id;
          return (
            <div key={it.id} className="vmk-btn" onClick={() => onChange(it.id)} style={{
              display: 'inline-flex', alignItems: 'center', gap: 7, padding: icons ? '7px 11px' : '7px 15px',
              borderRadius: 8, fontSize: 13, fontWeight: 500, fontFamily: sans,
              color: active ? t.text1 : t.text3,
              background: active ? (t.name === 'dark' ? 'oklch(1 0 0 / 0.10)' : '#fff') : 'transparent',
              boxShadow: active ? '0 1px 3px oklch(0 0 0 / 0.10)' : 'none',
            }}>{it.icon}{it.label && <span>{it.label}</span>}</div>
          );
        })}
      </div>
    );
  }

  // ── app gallery (desktop rail) ──────────────────────────────
  function AppRail({ t }) {
    const S = 0.74;
    return (
      <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '0 4px 18px', textAlign: 'center', flexShrink: 0 }}>
          <div style={{ fontSize: 12, color: t.accent, letterSpacing: 1.2, textTransform: 'uppercase', fontFamily: mono, fontWeight: 600 }}>The Vault app</div>
          <div style={{ fontSize: 26, fontWeight: 600, color: t.text1, letterSpacing: -0.6, marginTop: 8 }}>Seven screens, one continuous flow</div>
          <div style={{ fontSize: 13, color: t.text3, marginTop: 6, display: 'inline-flex', alignItems: 'center', gap: 7 }}>Scroll horizontally to walk the journey →</div>
        </div>
        <div className="vmk-scroll" style={{ flex: 1, overflowX: 'auto', overflowY: 'hidden', display: 'flex', alignItems: 'center' }}>
          <div style={{ display: 'flex', gap: 18, padding: '0 40px', margin: '0 auto' }}>
            {APP_SCREENS.map((s, i) => {
              const C = s.comp;
              return (
                <div key={s.id} style={{ width: 360 * S, flexShrink: 0, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  <div style={{ width: 360 * S, height: 760 * S, position: 'relative' }}>
                    <div style={{ position: 'absolute', top: 0, left: 0, transform: `scale(${S})`, transformOrigin: 'top left' }}>
                      <VaultPhone t={t}><C t={t} /></VaultPhone>
                    </div>
                  </div>
                  <div style={{ marginTop: 14, fontSize: 12.5, color: t.text2, fontWeight: 500 }}>
                    <span style={{ fontFamily: mono, color: t.text3 }}>{String(i + 1).padStart(2, '0')}</span> · {s.label}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  // ── app single (mobile) ─────────────────────────────────────
  function AppSingle({ t, appScreen, setAppScreen }) {
    const [ref, scale] = useFit(360, 760, [appScreen]);
    const C = (APP_SCREENS.find(s => s.id === appScreen) || APP_SCREENS[2]).comp;
    return (
      <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        {/* pill nav */}
        <div className="vmk-scroll" style={{ flexShrink: 0, maxWidth: '100%', overflowX: 'auto', padding: '0 16px 14px' }}>
          <div style={{ display: 'flex', gap: 8 }}>
            {APP_SCREENS.map(s => {
              const active = s.id === appScreen;
              return (
                <div key={s.id} className="vmk-btn" onClick={() => setAppScreen(s.id)} style={{
                  whiteSpace: 'nowrap', padding: '8px 14px', borderRadius: 999, fontSize: 12.5, fontWeight: 500,
                  color: active ? t.accentInk : t.text2, background: active ? t.accent : t.surface1,
                  border: `1px solid ${active ? 'transparent' : t.hairline}`,
                }}>{s.label}</div>
              );
            })}
          </div>
        </div>
        <div ref={ref} style={{ flex: 1, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 0 }}>
          <div style={{ transform: `scale(${scale})`, transformOrigin: 'center' }}>
            <VaultPhone t={t}><C t={t} /></VaultPhone>
          </div>
        </div>
      </div>
    );
  }

  // ── marketing frame (scaled) ────────────────────────────────
  function MarketingStage({ t, device, screen, onNav }) {
    const isDesk = device === 'desktop';
    const [ref, scale] = useFit(isDesk ? 1280 : 380, isDesk ? 800 : 800, [device, screen]);
    const Comp = screen === 'pricing' ? Pricing : screen === 'security' ? Security : Landing;
    const url = (SCREENS.find(s => s.id === screen) || {}).path || '';
    const content = <Comp t={t} device={isDesk ? 'desktop' : 'mobile'} onNav={onNav} />;
    return (
      <div ref={ref} style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ transform: `scale(${scale})`, transformOrigin: 'center' }}>
          {isDesk ? <BrowserFrame t={t} url={url}>{content}</BrowserFrame> : <PhoneShell t={t}>{content}</PhoneShell>}
        </div>
      </div>
    );
  }

  // ── shell ───────────────────────────────────────────────────
  function Showcase() {
    const saved = (() => { try { return JSON.parse(localStorage.getItem('vault_showcase') || '{}'); } catch { return {}; } })();
    const [screen, setScreen] = React.useState(saved.screen || 'home');
    const [device, setDevice] = React.useState(saved.device || 'desktop');
    const [theme, setTheme] = React.useState(saved.theme || 'dark');
    const [appScreen, setAppScreen] = React.useState(saved.appScreen || 'wallet');

    React.useEffect(() => {
      localStorage.setItem('vault_showcase', JSON.stringify({ screen, device, theme, appScreen }));
    }, [screen, device, theme, appScreen]);

    const t = theme === 'dark' ? VAULT_DARK : VAULT_LIGHT;
    const studio = STUDIO[theme];
    const onNav = (id) => setScreen(id);

    const monitorIcon = <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><rect x="3" y="4" width="18" height="13" rx="2" stroke="currentColor" strokeWidth="1.7"/><path d="M9 20h6M12 17v3" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/></svg>;
    const phoneIcon = <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><rect x="7" y="3" width="10" height="18" rx="2.5" stroke="currentColor" strokeWidth="1.7"/><path d="M11 18h2" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/></svg>;
    const sunIcon = <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="1.7"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.5 1.5M17.5 17.5L19 19M19 5l-1.5 1.5M6.5 17.5L5 19" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/></svg>;
    const moonIcon = <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M21 12.8A8 8 0 1111.2 3a6.5 6.5 0 009.8 9.8z" stroke="currentColor" strokeWidth="1.7" strokeLinejoin="round"/></svg>;

    return (
      <div style={{ position: 'fixed', inset: 0, display: 'flex', flexDirection: 'column', background: studio.bg, fontFamily: sans, transition: 'background .3s' }}>
        {/* CHROME */}
        <div style={{ flexShrink: 0, height: 62, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 18px',
          background: t.surface1, borderBottom: `1px solid ${t.hairline}`, color: t.text1, zIndex: 5 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11, width: 280 }}>
            <div style={{ width: 30, height: 30, borderRadius: 8, background: t.accent, color: t.accentInk, display: 'grid', placeItems: 'center', fontFamily: mono, fontWeight: 700, fontSize: 16 }}>V</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 9 }}>
              <span style={{ fontSize: 17, fontWeight: 600, letterSpacing: -0.3 }}>Vault</span>
              <span style={{ fontSize: 11, color: t.text3, fontFamily: mono, letterSpacing: 0.5, textTransform: 'uppercase' }}>Showcase</span>
            </div>
          </div>

          {/* screen switch */}
          <Segment t={t} value={screen} onChange={setScreen} items={SCREENS.map(s => ({ id: s.id, label: s.label }))} />

          {/* device + theme */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, width: 280, justifyContent: 'flex-end' }}>
            <Segment t={t} icons value={device} onChange={setDevice} items={[
              { id: 'desktop', icon: monitorIcon }, { id: 'mobile', icon: phoneIcon },
            ]} />
            <Segment t={t} icons value={theme} onChange={setTheme} items={[
              { id: 'light', icon: sunIcon }, { id: 'dark', icon: moonIcon },
            ]} />
          </div>
        </div>

        {/* STAGE */}
        <div style={{ flex: 1, minHeight: 0, position: 'relative',
          backgroundImage: `linear-gradient(${studio.grid} 1px, transparent 1px), linear-gradient(90deg, ${studio.grid} 1px, transparent 1px)`,
          backgroundSize: '40px 40px' }}>
          <div style={{ position: 'absolute', inset: 0, padding: 8 }}>
            {screen === 'app'
              ? (device === 'desktop'
                ? <div style={{ width: '100%', height: '100%', padding: '28px 12px' }}><AppRail t={t} /></div>
                : <AppSingle t={t} appScreen={appScreen} setAppScreen={setAppScreen} />)
              : <MarketingStage t={t} device={device} screen={screen} onNav={onNav} />}
          </div>

          {/* corner caption */}
          <div style={{ position: 'absolute', left: 16, bottom: 14, fontSize: 11.5, color: t.text3, fontFamily: mono, display: 'flex', alignItems: 'center', gap: 8, pointerEvents: 'none' }}>
            <span style={{ width: 7, height: 7, borderRadius: 4, background: t.accent }} />
            {screen.toUpperCase()} · {device.toUpperCase()} · {theme.toUpperCase()}
          </div>
        </div>
      </div>
    );
  }

  window.VaultShowcase = Showcase;
})();
