/* Rolo Marketing — Wireframes
 * Main shell: title strip, floating nav, section stacks, tweaks panel.
 * Variant components live in variants-top.jsx + variants-bot.jsx (exported to window).
 */

const { useEffect, useRef, useState } = React;

/* ---------- Floating pill nav ---------- */
function FloatNav({ mode }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const isFlow = mode === 'flow';
  return (
    <nav className={"wf-floatnav" + (scrolled ? " scrolled" : "") + (isFlow ? " in-flow" : "")} aria-label="Primary">
      <a href="#sec-hero" className="brand">
        <img src={window.A("logoBlack")} alt="Rolo Robotics" className="logo logo-black" />
        <img src={window.A("logoWhite")} alt="Rolo Robotics" className="logo logo-white" />
      </a>
      <div className="links">
        <a href="#sec-platform">Platform</a>
        <a href="#sec-modules">Modules</a>
        <a href="#sec-deploy">Deployment</a>
      </div>
      <a className="cta" href="#sec-cta">Book a Demo</a>
    </nav>
  );
}

/* ---------- Picks context (persistent variant selections) ---------- */
const PicksContext = React.createContext({
  num: null, total: 0, mode: 'lab', picks: {}, setPick: () => {}, sectionTitle: '',
});
window.PicksContext = PicksContext;

/* ---------- Variant block ---------- */
function Variant({ letter, title, desc, notes, children, dark }) {
  const ctx = React.useContext(PicksContext);
  const picked = ctx.picks[ctx.num] === letter;
  // In flow mode: only render the chosen variant; strip the meta column.
  if (ctx.mode === 'flow') {
    if (!picked) return null;
    return (
      <div className="wf-flow-block" data-section={ctx.num}>
        <div className={"wf-canvas wf-canvas--flow" + (dark ? " dark" : "")}>
          {children}
        </div>
      </div>
    );
  }
  return (
    <div className={"wf-variant" + (picked ? " picked" : "")}>
      <div className="wf-variant-meta">
        <span className="wf-variant-tag">Variant {letter}</span>
        <span className="wf-variant-letter">{letter}</span>
        <div className="wf-variant-title">{title}</div>
        <div className="wf-variant-desc">{desc}</div>
        {notes && notes.length > 0 && (
          <ul className="wf-variant-list">
            {notes.map((n, i) => <li key={i}>{n}</li>)}
          </ul>
        )}
        <button
          type="button"
          className={"wf-pick-btn" + (picked ? " on" : "")}
          onClick={() => ctx.setPick(ctx.num, picked ? null : letter)}
          aria-pressed={picked}
          title={picked ? "Remove from flow" : "Use this variant in the flow"}
        >
          <span className="dot" aria-hidden="true"></span>
          {picked ? "Picked for flow" : "Pick for flow"}
        </button>
      </div>
      <div className={"wf-canvas" + (dark ? " dark" : "")}>
        <span className="corner">VAR · {letter}</span>
        {children}
      </div>
    </div>
  );
}
window.Variant = Variant;

/* ---------- Section stack ---------- */
function Section({ num, total, title, anchor, note, children, picksValue }) {
  return (
    <PicksContext.Provider value={{ ...picksValue, num, total, sectionTitle: title }}>
      <section className={"wf-section wf-section-" + picksValue.mode} id={anchor}>
        {picksValue.mode === 'lab' && (
          <header className="wf-section-head">
            <span className="wf-section-num">{String(num).padStart(2,'0')} / {String(total).padStart(2,'0')}</span>
            <h2 className="wf-section-title">{title}</h2>
            <span className="wf-section-count">
              {picksValue.picks[num] ? <span className="wf-section-picked">Picked · {picksValue.picks[num]}</span> : "3 variants"}
            </span>
          </header>
        )}
        {picksValue.mode === 'lab' && note && <div className="wf-section-note">{note}</div>}
        {children}
      </section>
    </PicksContext.Provider>
  );
}

/* ---------- Tweaks ---------- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "showGrid": false,
  "showAnnotations": true,
  "density": "comfortable",
  "showLetters": true,
  "highlight": "all"
}/*EDITMODE-END*/;

function applyBodyClasses(t) {
  document.body.classList.toggle('hide-anno', !t.showAnnotations);
  document.body.classList.toggle('compact', t.density === 'compact');
  document.body.classList.toggle('hide-letters', !t.showLetters);
  document.body.dataset.highlight = t.highlight;
}

function TweaksUI() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  useEffect(() => { applyBodyClasses(t); }, [t]);
  useEffect(() => {
    // Apply grid overlay to every canvas live
    document.querySelectorAll('.wf-canvas').forEach(el => {
      el.classList.toggle('show-grid', !!t.showGrid);
    });
  }, [t.showGrid]);
  // Apply highlight focus styling
  useEffect(() => {
    const hi = t.highlight;
    document.querySelectorAll('.wf-variant').forEach(v => {
      const letter = v.querySelector('.wf-variant-letter')?.textContent?.trim();
      const focused = hi === 'all' || hi === letter;
      v.style.opacity = focused ? '1' : '0.28';
      v.style.filter = focused ? 'none' : 'grayscale(0.4)';
      v.style.transition = 'opacity 250ms, filter 250ms';
    });
  }, [t.highlight]);

  return (
    <window.TweaksPanel title="Tweaks">
      <window.TweakSection label="Review mode">
        <window.TweakRadio
          label="Focus variant"
          value={t.highlight}
          options={[
            { value: 'all', label: 'All' },
            { value: 'A', label: 'A' },
            { value: 'B', label: 'B' },
            { value: 'C', label: 'C' },
          ]}
          onChange={v => setTweak('highlight', v)}
        />
        <window.TweakRadio
          label="Density"
          value={t.density}
          options={[
            { value: 'comfortable', label: 'Roomy' },
            { value: 'compact', label: 'Compact' },
          ]}
          onChange={v => setTweak('density', v)}
        />
      </window.TweakSection>
      <window.TweakSection label="Wireframe chrome">
        <window.TweakToggle label="Show 12-col grid" value={t.showGrid} onChange={v => setTweak('showGrid', v)} />
        <window.TweakToggle label="Show annotations" value={t.showAnnotations} onChange={v => setTweak('showAnnotations', v)} />
        <window.TweakToggle label="Big variant letters" value={t.showLetters} onChange={v => setTweak('showLetters', v)} />
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

/* ---------- App ---------- */
const PICKS_KEY = 'rolo-wf-picks';
const MODE_KEY  = 'rolo-wf-mode';

/* Standalone export mode — set by the offline HTML head before scripts load.
   When on: force flow mode + embedded picks, hide lab chrome + tweaks panel. */
const EXPORT_MODE = !!(window.__rolo_export);
const EXPORT_PICKS = window.__rolo_export_picks || null;

function loadPicks() {
  if (EXPORT_MODE && EXPORT_PICKS) return { ...EXPORT_PICKS };
  try { return JSON.parse(localStorage.getItem(PICKS_KEY) || '{}') || {}; } catch { return {}; }
}
function loadMode() {
  if (EXPORT_MODE) return 'flow';
  return localStorage.getItem(MODE_KEY) === 'flow' ? 'flow' : 'lab';
}

function App() {
  const [picks, setPicks] = useState(loadPicks);
  const [mode, setMode]   = useState(loadMode);

  useEffect(() => { localStorage.setItem(PICKS_KEY, JSON.stringify(picks)); }, [picks]);
  useEffect(() => {
    localStorage.setItem(MODE_KEY, mode);
    document.body.classList.toggle('mode-flow', mode === 'flow');
    document.body.classList.toggle('mode-lab',  mode === 'lab');
  }, [mode]);

  const setPick = (num, letter) => setPicks(p => {
    const next = { ...p };
    if (letter == null) delete next[num]; else next[num] = letter;
    return next;
  });
  const clearPicks = () => setPicks({});
  const fillDefaults = (letter) => setPicks(() => {
    const o = {};
    for (let i = 1; i <= 10; i++) o[i] = letter;
    return o;
  });

  // Reveal-on-scroll for variant canvases
  useEffect(() => {
    const els = document.querySelectorAll('.wf-reveal:not(.visible)');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('visible');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, [mode, picks]);

  const sections = [
    { n: 1,  title: 'Hero',                 anchor: 'sec-hero',     comp: window.HeroVariants,
      note: 'Full-viewport video bg with dark overlay · centered headline + sub · single gold CTA · subtle scroll indicator. Wireframes substitute an animated diagonal-line treatment for the video.' },
    { n:  2,  title: 'MicroKitchens Platform', anchor: 'sec-platform', comp: window.PlatformVariants,
      note: 'White surface · two-column copy + product photo · horizontal stat strip in Brand Gold · compliance badge floating over imagery · compliance bar (CE/UL/UVC/AI/Pest) anchors the bottom of the section.' },
    { n: 3,  title: 'The 4 Modules',        anchor: 'sec-modules',  comp: window.ModulesVariants,
      note: 'Dark surface · cinematic full-viewport scroll · each module bleeds its accent in dramatically; module name in League Spartan 900 at enormous scale; speed stat + 4 capability lines; signature dishes per module shown as circle-cropped bowls (brand brochure style).' },
    { n: 4,  title: 'Rolo OS',              anchor: 'sec-os',       comp: window.OSVariants,
      note: 'Dark surface · AI intelligence layer · four capability rows with line icons · gold orbit/ring graphic.' },
    { n: 5,  title: 'Deployment',           anchor: 'sec-deploy',   comp: window.DeployVariants,
      note: 'White surface · live Singapore sites + upcoming international pilots · "Built for" environment strip recalls the contexts Rolo runs in.' },
    { n: 6,  title: 'Social Proof Videos',  anchor: 'sec-social',   comp: window.SocialVariants,
      note: 'Dark surface · three portrait 9:16 video cards · centered play, bottom quote overlay · subtle hover lift.' },
    { n: 7,  title: 'Press & Media',        anchor: 'sec-press',    comp: window.PressVariants,
      note: 'White surface · muted "As Seen In" eyebrow · publication pills with light grey borders.' },
    { n: 8,  title: 'About & Investors',    anchor: 'sec-about',    comp: window.AboutVariants,
      note: 'White surface · founder portrait + story copy · partnership pills · $3.45M funding block in Brand Gold with backer pills.' },
    { n: 9,  title: 'Why Now',              anchor: 'sec-whynow',   comp: window.WhyNowVariants,
      note: 'Dark surface · three insight cards with gold left border · each with a small source line.' },
    { n: 10, title: 'CTA + Footer',         anchor: 'sec-cta',      comp: window.CTAVariants,
      note: 'White CTA: bold centered headline + ink-filled + gold-outline buttons · contact email · social icons. Footer: black with white logo, copyright, address, muted nav links.' },
  ];

  const pickedCount = Object.values(picks).filter(Boolean).length;
  const picksValue = { mode, picks, setPick };

  return (
    <React.Fragment>
            <FloatNav mode={mode} />

      {mode === 'lab' && (
        <header className="wf-title-strip">
          <div className="meta">Wireframes · v1 · Mid-fidelity · Grayscale</div>
          <h1>Rolo Robotics<br/>Marketing Site.</h1>
          <p className="lede">
            Section-by-section exploration of the single-page brief. Each section below shows three layout
            directions stacked top-to-bottom — real Neue Montreal, real spacing, photography replaced by
            hatched placeholders. Tap <b>Pick for flow</b> on any variant, then toggle <b>Preview flow</b>
            in the bar at the top right to stitch your selections into a single end-to-end page.
          </p>
          <nav className="wf-toc" aria-label="Sections">
            {sections.map(s => (
              <a key={s.anchor} href={"#" + s.anchor}>{String(s.n).padStart(2,'0')} · {s.title}</a>
            ))}
          </nav>
        </header>
      )}

      {!EXPORT_MODE && (
      <FlowBar
        sections={sections}
        picks={picks}
        mode={mode}
        setMode={setMode}
        setPick={setPick}
        clearPicks={clearPicks}
        fillDefaults={fillDefaults}
        pickedCount={pickedCount}
      />
      )}

      {sections.map(s => {
        const Comp = s.comp;
        // In flow mode: skip whole section if nothing is picked there.
        if (mode === 'flow' && !picks[s.n]) return null;
        return (
          <React.Fragment key={s.anchor}>
            <Section num={s.n} total={sections.length} title={s.title} anchor={s.anchor} note={s.note} picksValue={picksValue}>
              {Comp ? <Comp /> : <div style={{padding:24,color:'#999'}}>Variants for "{s.title}" not yet wired.</div>}
            </Section>
            {/* Partners marquee sits between Press (7) and Why Now (9). Flow mode only. */}
            {mode === 'flow' && s.n === 7 && window.PartnersBanner && <window.PartnersBanner />}
          </React.Fragment>
        );
      })}

      {mode === 'lab' && (
        <footer style={{
          padding: '40px clamp(28px,5vw,72px) 80px',
          fontFamily: 'var(--rr-font-mono)',
          fontSize: 11,
          letterSpacing: '0.18em',
          textTransform: 'uppercase',
          color: '#8B8779',
          borderTop: '1px solid #D9D5CB'
        }}>
          End of wireframes · Rolo Robotics marketing site · {sections.length} sections · {sections.length * 3} variants
        </footer>
      )}

      {mode === 'lab' && <TweaksUI />}
      {mode === 'lab' && <div className="wf-stamp">Wireframes · v1 · Rolo Robotics</div>}
    </React.Fragment>
  );
}

/* ---------- Flow bar (picks dashboard) ---------- */
function FlowBar({ sections, picks, mode, setMode, setPick, clearPicks, fillDefaults, pickedCount }) {
  const [open, setOpen] = useState(false);
  return (
    <div className={"wf-flowbar" + (mode === 'flow' ? " in-flow" : "") + (open ? " open" : "")}>
      <button
        type="button"
        className="wf-flowbar-toggle"
        onClick={() => setMode(mode === 'flow' ? 'lab' : 'flow')}
        disabled={pickedCount === 0 && mode === 'lab'}
        title={pickedCount === 0 ? "Pick at least one variant first" : ""}
      >
        <span className="dot"></span>
        {mode === 'flow' ? 'Back to wireframe lab' : 'Preview flow'}
        {mode === 'lab' && <span className="ct">{pickedCount}/10</span>}
      </button>
      <button type="button" className="wf-flowbar-trigger" onClick={() => setOpen(o => !o)}>
        Picks {open ? '▴' : '▾'}
      </button>
      {open && (
        <div className="wf-flowbar-panel">
          <div className="wf-flowbar-panel-head">
            <span>Your selection</span>
            <div className="flex gap-2">
              <button type="button" className="wf-pill" onClick={() => fillDefaults('A')}>Pick all A</button>
              <button type="button" className="wf-pill" onClick={() => fillDefaults('B')}>All B</button>
              <button type="button" className="wf-pill" onClick={() => fillDefaults('C')}>All C</button>
              <button type="button" className="wf-pill danger" onClick={clearPicks}>Clear</button>
            </div>
          </div>
          <ol className="wf-flowbar-list">
            {sections.map(s => {
              const cur = picks[s.n];
              return (
                <li key={s.n}>
                  <span className="num">{String(s.n).padStart(2,'0')}</span>
                  <span className="ttl">{s.title}</span>
                  <span className="opts">
                    {['A','B','C'].map(L => (
                      <button
                        key={L}
                        type="button"
                        className={"opt" + (cur === L ? " on" : "")}
                        onClick={() => setPick(s.n, cur === L ? null : L)}
                      >{L}</button>
                    ))}
                  </span>
                </li>
              );
            })}
          </ol>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
