// Tabbed shell + Live Demo controller.
// Replaces the design-canvas pan/zoom view with sectioned tabs.
// Adds `?demo` route that renders a full-bleed mobile flow (for real phones).

const SHELL_CSS = `
  .sh-root{min-height:100vh;background:#f4f1ec;color:#0a0a0a;
    font-family:'Inter',system-ui,sans-serif;display:flex;flex-direction:column}
  .sh-top{position:sticky;top:0;z-index:30;background:rgba(250,249,247,.92);
    backdrop-filter:blur(14px) saturate(160%);-webkit-backdrop-filter:blur(14px) saturate(160%);
    border-bottom:1px solid #e5e2dc}
  .sh-top-inner{max-width:1320px;margin:0 auto;padding:10px 20px 0;
    display:flex;flex-direction:column;gap:10px}
  .sh-brand{display:flex;align-items:center;justify-content:space-between;gap:12px}
  .sh-brand-title{font-family:'Inter Tight',system-ui,sans-serif;font-weight:800;
    font-size:15px;letter-spacing:-.01em;display:flex;align-items:center;gap:8px}
  .sh-brand-dot{width:9px;height:9px;border-radius:2px;background:var(--tp-cta)}
  .sh-brand-meta{font-family:'JetBrains Mono',ui-monospace,monospace;font-size:10px;
    color:#8a8a8a;letter-spacing:.04em}
  .sh-tabs{display:flex;gap:2px;overflow-x:auto;scrollbar-width:none;
    margin:0 -20px;padding:0 20px}
  .sh-tabs::-webkit-scrollbar{display:none}
  .sh-tab{appearance:none;border:0;background:transparent;cursor:pointer;
    padding:10px 14px;border-radius:8px 8px 0 0;font:inherit;font-size:13px;
    font-weight:500;color:#4a4a4a;white-space:nowrap;line-height:1;
    display:flex;align-items:center;gap:6px;border-bottom:2px solid transparent;
    margin-bottom:-1px;transition:color .12s,border-color .12s,background .12s}
  .sh-tab:hover{color:#0a0a0a;background:rgba(0,0,0,.03)}
  .sh-tab[data-active="1"]{color:#0a0a0a;border-bottom-color:var(--tp-cta);font-weight:600}
  .sh-tab-idx{font-family:'JetBrains Mono',ui-monospace,monospace;font-size:10px;
    color:#8a8a8a;letter-spacing:.04em}
  .sh-tab[data-active="1"] .sh-tab-idx{color:var(--tp-cta)}
  .sh-tab-demo{background:#0a0a0a;color:#fff;margin-left:6px;border-radius:8px;
    padding:8px 14px;border-bottom:0;margin-bottom:0;align-self:center}
  .sh-tab-demo:hover{background:#222;color:#fff}
  .sh-tab-demo[data-active="1"]{background:var(--tp-cta);color:#fff;
    border-bottom:0}

  .sh-stage{max-width:1320px;width:100%;margin:0 auto;padding:28px 20px 80px;
    display:flex;flex-direction:column;gap:8px}
  .sh-stage-head{display:flex;align-items:baseline;gap:14px;flex-wrap:wrap;
    margin-bottom:14px}
  .sh-stage-title{font-family:'Inter Tight',system-ui,sans-serif;font-weight:700;
    font-size:28px;letter-spacing:-.02em}
  .sh-stage-sub{font-size:14px;color:#4a4a4a}

  .sh-row{display:flex;flex-wrap:wrap;gap:32px;justify-content:center;
    align-items:flex-start}
  .sh-card{display:flex;flex-direction:column;gap:10px}
  .sh-card-lbl{font-family:'JetBrains Mono',ui-monospace,monospace;font-size:11px;
    color:#6a6a6a;letter-spacing:.04em;padding:0 4px}
  .sh-scaler{position:relative;overflow:hidden;background:#fbfaf7;
    border-radius:4px;box-shadow:0 1px 3px rgba(0,0,0,.06),0 6px 24px rgba(0,0,0,.06)}
  .sh-scaler-inner{transform-origin:top left}

  .sh-demo-wrap{display:flex;flex-direction:column;align-items:center;gap:14px;
    padding-top:8px}
  .sh-demo-toolbar{display:flex;gap:10px;align-items:center;background:#0a0a0a;
    color:#fff;border-radius:999px;padding:6px 6px 6px 14px;
    box-shadow:0 6px 24px rgba(0,0,0,.18);font-size:13px}
  .sh-demo-toolbar .sh-pos{font-family:'JetBrains Mono',ui-monospace,monospace;
    font-size:11px;color:#bbb;letter-spacing:.04em;min-width:88px;text-align:center}
  .sh-demo-btn{appearance:none;border:0;background:#fff;color:#0a0a0a;
    cursor:pointer;font:inherit;font-weight:600;font-size:12px;
    padding:8px 14px;border-radius:999px;display:flex;align-items:center;gap:6px}
  .sh-demo-btn:disabled{opacity:.4;cursor:not-allowed}
  .sh-demo-btn.ghost{background:transparent;color:#fff;border:1px solid rgba(255,255,255,.25)}
  .sh-demo-link{font-size:12px;color:#4a4a4a;text-decoration:none;
    border:1px solid #d4d0c8;padding:6px 10px;border-radius:999px;
    display:inline-flex;align-items:center;gap:6px;background:#fff}
  .sh-demo-link:hover{color:#0a0a0a;border-color:#0a0a0a}

  @media (max-width:720px){
    .sh-stage{padding:20px 12px 80px}
    .sh-stage-title{font-size:22px}
    .sh-row{gap:20px}
  }
`;

if (typeof document !== 'undefined' && !document.getElementById('sh-styles')) {
  const s = document.createElement('style');
  s.id = 'sh-styles';
  s.textContent = SHELL_CSS;
  document.head.appendChild(s);
}

// ─── ScaledFrame ─────────────────────────────────────────────
// Renders a fixed-pixel artboard, scaled to fit the available width.
// Handles both mobile (IOS frame, 402x874) and desktop (Chrome window) sizes.
// `autoHeight`: measure the inner content's natural height and size the frame
// to it (× scale) instead of locking to the declared `height`. Use it when the
// artboard's content can overflow/grow (e.g. the Brief). The declared `height`
// becomes the initial/min height. Non-autoHeight frames keep the fixed box so
// phone shells render at exact pixel dimensions.
function ScaledFrame({ width, height, maxScale = 1, autoHeight = false, children }) {
  const ref = React.useRef(null);
  const innerRef = React.useRef(null);
  const [scale, setScale] = React.useState(1);
  const [measuredH, setMeasuredH] = React.useState(height);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const fit = () => {
      const cw = el.clientWidth;
      if (!cw) return;
      const s = Math.min(maxScale, cw / width);
      setScale(s);
      if (autoHeight && innerRef.current) {
        setMeasuredH(innerRef.current.offsetHeight);
      }
    };
    fit();
    const ro = new ResizeObserver(fit);
    ro.observe(el);
    if (autoHeight && innerRef.current) ro.observe(innerRef.current);
    window.addEventListener('resize', fit);
    return () => { ro.disconnect(); window.removeEventListener('resize', fit); };
  }, [width, height, maxScale, autoHeight]);

  const h = autoHeight ? measuredH : height;
  return (
    <div ref={ref} className="sh-scaler"
         style={{ width: '100%', maxWidth: width, height: h * scale }}>
      <div ref={innerRef} className="sh-scaler-inner" style={{
        width, transform: `scale(${scale})`,
        ...(autoHeight ? {} : { height }),
      }}>{children}</div>
    </div>
  );
}

// ─── Phone artboard wrapper ──────────────────────────────────
// Components render their own status bar / phone chrome, so we skip
// IOSDevice and use a plain phone-shaped card to avoid duplication.
function PhoneShell({ width = 420, height = 900, children }) {
  return (
    <div style={{
      width, height, background: '#fbfaf7', overflow: 'hidden',
      borderRadius: 36, border: '1px solid #d4d0c8',
      boxShadow: '0 1px 3px rgba(0,0,0,.06),0 16px 40px rgba(0,0,0,.10)',
    }}>{children}</div>
  );
}

function PhoneCard({ label, children, height = 900 }) {
  return (
    <div className="sh-card" style={{ width: 420, maxWidth: '100%' }}>
      {label && <div className="sh-card-lbl">{label}</div>}
      <ScaledFrame width={420} height={height}>
        <PhoneShell width={420} height={height}>{children}</PhoneShell>
      </ScaledFrame>
    </div>
  );
}

// ─── Wide artboard wrapper (desktop / canvas) ────────────────
function WideCard({ label, width, height, children, browserChrome, url, autoHeight }) {
  return (
    <div className="sh-card" style={{ width: '100%', maxWidth: 1280 }}>
      {label && <div className="sh-card-lbl">{label}</div>}
      <ScaledFrame width={width} height={height} autoHeight={autoHeight}>
        {browserChrome
          ? <ChromeWindow width={width} height={height}
                          tabs={[{ title: url || 'tested-peptides.com' }]}
                          url={url || 'tested-peptides.com'}>{children}</ChromeWindow>
          : <div style={{ width, ...(autoHeight ? { minHeight: height } : { height }), background: '#fbfaf7' }}>{children}</div>}
      </ScaledFrame>
    </div>
  );
}

// ─── Stage definitions ───────────────────────────────────────
function buildStages(t) {
  return [
    {
      id: 'brief', idx: '00', title: 'Brief & Strategy', sub: 'Read this first',
      render: () => <div className="sh-row">
        <WideCard label="00 · Design brief" width={1080} height={920} autoHeight>
          <Brief />
        </WideCard>
      </div>,
    },
    {
      id: 'ads', idx: '01', title: 'TikTok Ad Creative',
      sub: '8 hook variants · cold traffic · sub-$1 CPM target',
      // Rendered directly (no ScaledFrame downscale): the 8 hooks lay out as a
      // responsive grid of native-size phone cards so they stay readable.
      render: () => <Ads />,
    },
    {
      id: 'quiz', idx: '02', title: 'Quiz Landing Page',
      sub: 'Mobile · post-click from TikTok',
      render: () => <div className="sh-row">
        <PhoneCard label="Quiz · step 1"><Landing step={1} t={t} /></PhoneCard>
        <PhoneCard label="Quiz · step 2"><Landing step={2} t={t} /></PhoneCard>
        <PhoneCard label="Quiz · step 3"><Landing step={3} t={t} /></PhoneCard>
        <PhoneCard label="Quiz · result + email gate"><Landing step={4} t={t} /></PhoneCard>
      </div>,
    },
    {
      id: 'vsl', idx: '03', title: 'VSL / Long-form Sales Page',
      sub: 'Mobile · post-quiz · 5 sections',
      render: () => <div className="sh-row">
        <PhoneCard label="VSL · above the fold"><VSL section="hero" t={t} /></PhoneCard>
        <PhoneCard label="VSL · the mechanism"><VSL section="mech" t={t} /></PhoneCard>
        <PhoneCard label="VSL · social proof wall"><VSL section="proof" t={t} /></PhoneCard>
        <PhoneCard label="VSL · the stacked offer"><VSL section="offer" t={t} /></PhoneCard>
        <PhoneCard label="VSL · objections + FAQ"><VSL section="faq" t={t} /></PhoneCard>
      </div>,
    },
    {
      id: 'checkout', idx: '04', title: 'Offer + Checkout',
      sub: 'Mobile · cart with order bump',
      render: () => <div className="sh-row">
        <PhoneCard label="Checkout · with order bump" height={1080}>
          <Checkout view="main" t={t} />
        </PhoneCard>
        <PhoneCard label="Checkout · payment expanded" height={1080}>
          <Checkout view="pay" t={t} />
        </PhoneCard>
      </div>,
    },
    {
      id: 'upsell', idx: '05', title: 'Upsell + Downsell',
      sub: '1-click post-purchase',
      render: () => <div className="sh-row">
        <PhoneCard label="OTO · 90-day subscribe & save" height={1000}>
          <Upsell view="main" t={t} />
        </PhoneCard>
        <PhoneCard label="Downsell · if they decline" height={1000}>
          <Upsell view="down" t={t} />
        </PhoneCard>
      </div>,
    },
    {
      id: 'thankyou', idx: '06', title: 'Confirmation',
      sub: 'Reduce remorse · drive referral',
      render: () => <div className="sh-row">
        <PhoneCard label="Thank-you page" height={1000}><ThankYou t={t} /></PhoneCard>
      </div>,
    },
    {
      id: 'email', idx: '07', title: 'Email + SMS Follow-up',
      sub: 'Cart rescue + post-purchase · 4-touch sequence',
      // Rendered directly (no ScaledFrame downscale): the 4 touches wrap as
      // native-size email/SMS cards so the copy stays readable.
      render: () => <EmailSequence t={t} />,
    },
  ];
}

// ─── Demo flow (sequenced phone screens) ─────────────────────
// One iPhone frame, toolbar navigates stages. VSL is one tall scroll.
const DEMO_STEPS = [
  { id: 'quiz1',    label: 'Quiz · step 1' },
  { id: 'quiz2',    label: 'Quiz · step 2' },
  { id: 'quiz3',    label: 'Quiz · step 3' },
  { id: 'quizres',  label: 'Quiz · result + email' },
  { id: 'vsl',      label: 'VSL · long-form (scroll)' },
  { id: 'checkout', label: 'Checkout · cart + bump' },
  { id: 'pay',      label: 'Checkout · payment' },
  { id: 'upsell',   label: 'Upsell · 90-day' },
  { id: 'downsell', label: 'Downsell · 1 vial' },
  { id: 'thankyou', label: 'Thank-you' },
];

function DemoScreen({ stepId, t }) {
  if (stepId === 'quiz1')    return <Landing step={1} t={t} />;
  if (stepId === 'quiz2')    return <Landing step={2} t={t} />;
  if (stepId === 'quiz3')    return <Landing step={3} t={t} />;
  if (stepId === 'quizres')  return <Landing step={4} t={t} />;
  if (stepId === 'vsl')      return (
    <div>
      <VSL section="hero" t={t} />
      <VSL section="mech" t={t} />
      <VSL section="proof" t={t} />
      <VSL section="offer" t={t} />
      <VSL section="faq" t={t} />
    </div>
  );
  if (stepId === 'checkout') return <Checkout view="main" t={t} />;
  if (stepId === 'pay')      return <Checkout view="pay" t={t} />;
  if (stepId === 'upsell')   return <Upsell view="main" t={t} />;
  if (stepId === 'downsell') return <Upsell view="down" t={t} />;
  if (stepId === 'thankyou') return <ThankYou t={t} />;
  return null;
}

function DemoFlow({ t, fullBleed = false }) {
  const [i, setI] = React.useState(0);
  const step = DEMO_STEPS[i];
  const phoneW = fullBleed ? Math.min(window.innerWidth, 480) : 420;
  const phoneH = fullBleed ? window.innerHeight : 900;

  const next  = () => setI((x) => Math.min(DEMO_STEPS.length - 1, x + 1));
  const prev  = () => setI((x) => Math.max(0, x - 1));
  const reset = () => setI(0);

  if (fullBleed) {
    return (
      <div style={{
        minHeight: '100vh', background: '#000', display: 'flex',
        flexDirection: 'column', alignItems: 'center',
        paddingBottom: 72,
      }}>
        <div style={{ width: '100%', maxWidth: phoneW, background: '#fbfaf7', minHeight: '100vh' }}>
          <DemoScreen stepId={step.id} t={t} />
        </div>
        <div style={{
          position: 'fixed', left: 0, right: 0, bottom: 0,
          background: 'rgba(10,10,10,.94)', backdropFilter: 'blur(14px)',
          padding: '10px 14px max(10px, env(safe-area-inset-bottom))',
          display: 'flex', gap: 10, alignItems: 'center', justifyContent: 'center',
          zIndex: 100, color: '#fff',
        }}>
          <button className="sh-demo-btn ghost" onClick={prev} disabled={i === 0}>← Back</button>
          <span className="sh-pos">{i + 1} / {DEMO_STEPS.length}</span>
          <button className="sh-demo-btn" onClick={next} disabled={i === DEMO_STEPS.length - 1}>Next →</button>
          <button className="sh-demo-btn ghost" onClick={reset} title="Restart">↺</button>
        </div>
      </div>
    );
  }

  const demoUrl = location.pathname + '?demo';
  return (
    <div className="sh-demo-wrap">
      <div className="sh-demo-toolbar">
        <button className="sh-demo-btn ghost" onClick={prev} disabled={i === 0}>← Back</button>
        <span className="sh-pos">{i + 1} / {DEMO_STEPS.length}</span>
        <button className="sh-demo-btn" onClick={next} disabled={i === DEMO_STEPS.length - 1}>Next →</button>
        <button className="sh-demo-btn ghost" onClick={reset} title="Restart">↺</button>
      </div>
      <div className="sh-card-lbl" style={{ textAlign: 'center' }}>
        {step.label}
      </div>
      <ScaledFrame width={phoneW} height={phoneH} maxScale={1}>
        <PhoneShell width={phoneW} height={phoneH}>
          <div style={{ height: '100%', overflow: 'auto' }}>
            <DemoScreen stepId={step.id} t={t} />
          </div>
        </PhoneShell>
      </ScaledFrame>
      <a className="sh-demo-link" href={demoUrl} target="_blank" rel="noreferrer">
        ↗ Open on phone (full-bleed)
      </a>
      <div style={{ fontSize: 11, color: '#8a8a8a', textAlign: 'center', maxWidth: 360 }}>
        Scan the URL on your phone to walk the flow at full width.
      </div>
    </div>
  );
}

// ─── TabShell ────────────────────────────────────────────────
function TabShell({ t }) {
  const stages = buildStages(t);
  const tabs = [...stages, { id: 'demo', idx: '▶', title: 'Live Demo', sub: 'Click through the full funnel' }];

  const validId = (h) => tabs.find((x) => x.id === h)?.id;

  const [activeId, setActiveId] = React.useState(
    () => validId((location.hash || '').replace('#', '')) || 'brief');

  // The URL hash is the source of truth. Tab clicks set location.hash (which
  // pushes a history entry and fires hashchange); back/forward and manual hash
  // edits also fire hashchange. This single listener maps hash → active tab, so
  // navigation stays in sync both ways (deep links, history buttons, URL edits).
  React.useEffect(() => {
    const onHash = () => {
      const id = validId((location.hash || '').replace('#', ''));
      if (id) setActiveId(id);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // On first load, normalize the URL to the active tab without adding a history
  // entry (so the Back button leaves the funnel rather than cycling a no-op).
  React.useEffect(() => {
    if ((location.hash || '').replace('#', '') !== activeId) {
      history.replaceState(null, '', '#' + activeId);
    }
  }, []);

  const select = (id) => {
    if (id === activeId) return;
    location.hash = id; // pushes history + fires hashchange → setActiveId
  };

  const active = tabs.find((x) => x.id === activeId) || tabs[0];

  return (
    <div className="sh-root">
      <div className="sh-top">
        <div className="sh-top-inner">
          <div className="sh-brand">
            <div className="sh-brand-title">
              <span className="sh-brand-dot" /> TESTED / PEPTIDES
              <span className="sh-brand-meta" style={{ marginLeft: 10 }}>· FUNNEL-1 · TIKTOK</span>
            </div>
          </div>
          <div className="sh-tabs">
            {tabs.map((tab) => (
              <button key={tab.id}
                      className={tab.id === 'demo' ? 'sh-tab sh-tab-demo' : 'sh-tab'}
                      data-active={tab.id === activeId ? '1' : '0'}
                      onClick={() => select(tab.id)}>
                <span className="sh-tab-idx">{tab.idx}</span>
                {tab.title}
              </button>
            ))}
          </div>
        </div>
      </div>

      <div className="sh-stage">
        <div className="sh-stage-head">
          <span className="sh-stage-title">{active.title}</span>
          {active.sub && <span className="sh-stage-sub">{active.sub}</span>}
        </div>
        {active.id === 'demo'
          ? <DemoFlow t={t} />
          : active.render()}
      </div>
    </div>
  );
}

Object.assign(window, { TabShell, DemoFlow, ScaledFrame });
