const { useState, useEffect, useRef, useCallback } = React;

const FONT_PAIRS = {
  "Bricolage + DM Sans": ['"Bricolage Grotesque", system-ui, sans-serif', '"DM Sans", system-ui, sans-serif'],
  "Poppins + Nunito": ['"Poppins", system-ui, sans-serif', '"Nunito Sans", system-ui, sans-serif'],
  "Space Grotesk + DM Sans": ['"Space Grotesk", system-ui, sans-serif', '"DM Sans", system-ui, sans-serif'],
};
const ACCENTS = {
  Plum: "oklch(0.46 0.17 318)",
  Cardinal: "oklch(0.46 0.16 24)",
  Teal: "oklch(0.52 0.11 215)",
  Forest: "oklch(0.52 0.12 150)",
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "Plum",
  "fontPair": "Bricolage + DM Sans",
  "videoLayout": "Stepper",
  "heroStyle": "Cream"
}/*EDITMODE-END*/;

/* ---------- small helpers ---------- */
function PlayIcon() {
  return <svg width="26" height="26" viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>;
}
function Check() {
  return <svg width="13" height="13" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12" /></svg>;
}
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".fade-up");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

function ytId(url) {
  if (!url) return null;
  const m = url.match(/(?:embed\/|v=|youtu\.be\/)([\w-]{11})/);
  return m ? m[1] : null;
}

function Video({ step }) {
  const [playing, setPlaying] = useState(false);
  const id = ytId(step.embed);
  const watchUrl = id ? "https://youtu.be/" + id : step.embed;
  if (step.embed && playing) {
    const origin = (typeof window !== "undefined" && window.location && window.location.origin && window.location.origin !== "null")
      ? "&origin=" + encodeURIComponent(window.location.origin) : "";
    const src = "https://www.youtube-nocookie.com/embed/" + id + "?autoplay=1&rel=0&playsinline=1" + origin;
    return (
      <div className="video">
        <iframe src={src} allow="autoplay; encrypted-media; fullscreen; picture-in-picture" allowFullScreen title={step.title}></iframe>
        {id && <a className="yt-fallback" href={watchUrl} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()}>Open on YouTube ↗</a>}
      </div>
    );
  }
  const poster = id ? "https://img.youtube.com/vi/" + id + "/maxresdefault.jpg" : null;
  return (
    <div className={"video" + (poster ? " has-poster" : "")} onClick={() => step.embed && setPlaying(true)} role="button" aria-label={"Play " + step.title}
      style={poster ? { backgroundImage: "url(" + poster + ")" } : undefined}>
      <div className="play"><PlayIcon /></div>
      <div className="tag mono">{step.embed ? "WATCH" : "VIDEO " + String(step.n).padStart(2, "0")}</div>
      {id && <a className="yt-fallback" href={watchUrl} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()}>Open on YouTube ↗</a>}
    </div>
  );
}

/* ---------- checklist ---------- */
function CheckList({ items, stepN, done, toggle }) {
  return (
    <ul className="check-list">
      {items.map((it, i) => {
        const key = stepN + ":" + i;
        const on = !!done[key];
        return (
          <li key={key} className={on ? "on" : ""} onClick={() => toggle(key)}>
            <span className="check-box"><Check /></span>
            <span>{it}</span>
          </li>
        );
      })}
    </ul>
  );
}

/* ---------- layouts ---------- */
function Stepper({ steps, done, toggle, stepComplete }) {
  return (
    <div className="stepper">
      {steps.map((s) => (
        <div className={"step-row fade-up" + (stepComplete(s) ? " done" : "") + (s.highlight ? " highlight" : "")} key={s.n}>
          <div className="step-rail">
            <div className="step-num">{stepComplete(s) ? <Check /> : s.n}</div>
            <div className="step-line"></div>
          </div>
          <div className="step-body" style={s.noVideo ? { gridTemplateColumns: "1fr" } : undefined}>
            <div className="step-meta">
              <div className="phase-chip">{s.phase}</div>
              <div className="kicker" style={{ marginTop: 12 }}>{s.kicker}</div>
              <h3>{s.title}</h3>
              <p className="desc">{s.desc}</p>
              {!s.noVideo && <div className="step-mins mono">◷ {s.mins} watch</div>}
              <CheckList items={s.checklist} stepN={s.n} done={done} toggle={toggle} />
              {s.callout && (
                <div className="callout">
                  <div className="callout-label">{s.callout.label}</div>
                  <h4>{s.callout.title}</h4>
                  <div className="callout-code mono">{s.callout.code}</div>
                  <p>{s.callout.body}</p>
                </div>
              )}
            </div>
            {!s.noVideo && <Video step={s} />}
          </div>
        </div>
      ))}
    </div>
  );
}

function GridCards({ steps, stepComplete }) {
  return (
    <div className="grid-cards">
      {steps.map((s) => (
        <div className="gcard fade-up" key={s.n}>
          {!s.noVideo && <Video step={s} />}
          <div className="gbody">
            <div className="gnum">STEP {String(s.n).padStart(2, "0")} · {s.phase.toUpperCase()}</div>
            <h3>{s.title}</h3>
            <p className="desc">{s.desc}</p>
            <div className="gfoot">
              <span className="mono">◷ {s.mins}</span>
              <span>{stepComplete(s) ? "✓ Complete" : s.checklist.length + " to-dos"}</span>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function ListRows({ steps }) {
  return (
    <div className="list-rows">
      {steps.map((s) => (
        <div className="lrow fade-up" key={s.n} style={s.noVideo ? { gridTemplateColumns: "1fr" } : undefined}>
          {!s.noVideo && <Video step={s} />}
          <div>
            <div className="lnum">STEP {String(s.n).padStart(2, "0")} · {s.phase.toUpperCase()} · {s.mins}</div>
            <h3>{s.title}</h3>
            <p className="desc">{s.desc}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------- FAQ ---------- */
function Faq({ faqs }) {
  const [open, setOpen] = useState(null);
  return (
    <div className="faq-list">
      {faqs.map((f, i) => (
        <div className={"faq-item" + (open === i ? " open" : "")} key={i}>
          <button className="faq-q" onClick={() => setOpen(open === i ? null : i)}>
            {f.q}<span className="pm"></span>
          </button>
          <div className="faq-a" style={{ maxHeight: open === i ? "320px" : "0" }}>
            <p>{f.a}</p>
            {f.link && <a className="faq-link" href={f.link.href} target="_blank" rel="noopener">{f.link.label} ↗</a>}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------- App ---------- */
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const G = window.GUIDE;
  useReveal();

  const [done, setDone] = useState(() => {
    try { return JSON.parse(localStorage.getItem("tm_nourish_checklist") || "{}"); } catch (e) { return {}; }
  });
  const toggle = useCallback((key) => {
    setDone((d) => {
      const next = { ...d, [key]: !d[key] };
      localStorage.setItem("tm_nourish_checklist", JSON.stringify(next));
      return next;
    });
  }, []);

  // apply tweaks to :root
  useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty("--accent", ACCENTS[t.accent] || ACCENTS.Plum);
    const hue = { Plum: 318, Cardinal: 24, Teal: 215, Forest: 150 }[t.accent] || 318;
    r.setProperty("--accent-ink", `oklch(0.34 0.13 ${hue})`);
    const [h, b] = FONT_PAIRS[t.fontPair] || FONT_PAIRS["Bricolage + DM Sans"];
    r.setProperty("--font-head", h);
    r.setProperty("--font-body", b);
  }, [t.accent, t.fontPair]);

  const totalItems = G.steps.reduce((a, s) => a + s.checklist.length, 0);
  const doneCount = Object.values(done).filter(Boolean).length;
  const pct = totalItems ? Math.round((doneCount / totalItems) * 100) : 0;
  const stepComplete = (s) => s.checklist.every((_, i) => done[s.n + ":" + i]);

  const layouts = {
    Stepper: <Stepper steps={G.steps} done={done} toggle={toggle} stepComplete={stepComplete} />,
    Grid: <GridCards steps={G.steps} stepComplete={stepComplete} />,
    List: <ListRows steps={G.steps} />,
  };

  const heroPlum = t.heroStyle === "Plum";

  return (
    <React.Fragment>
      {/* announcement */}
      <div className="announce">Stanford Nourish Project × Tastermonial — your continuous glucose experiment, step by step</div>

      {/* header */}
      <header className="site">
        <div className="wrap nav">
          <img className="logo" src={window.ASSETS.logo} alt="Tastermonial" />
          <nav className="links">
            <a href="#guide">The guide</a>
            <a href="#need">What you need</a>
            <a href="#faq">FAQ</a>
          </nav>
          <a className="support" href="https://help.tastermonial.com/en-US" target="_blank" rel="noopener">Support</a>
        </div>
      </header>

      {/* hero */}
      <div className={"hero" + (heroPlum ? " plum" : "")}>
        <div className="wrap hero-inner">
          <div>
            <div className="eyebrow"><span className="dot"></span> CGM Experiment Guide</div>
            <h1>Run your first food experiment with a CGM</h1>
            <p className="sub">Welcome, Nourish participant. This is your step-by-step walkthrough — from applying your sensor to submitting results to the Stanford study. Watch, follow along, and tick each step off as you go.</p>
            <div className="cta">
              <a className="btn btn-primary" href="#guide">Start the guide ↓</a>
              <button className="btn btn-ghost" onClick={() => window.print()}>Download PDF quick-start</button>
            </div>
            <div className="cobrand">
              <span>Created in support of the <b>Stanford Medical School</b> NOURISH Meal Experiment</span>
            </div>
          </div>
          <div className="hero-art">
            <div className="blob"></div>
            <img src={heroPlum ? window.ASSETS.kiwiCap : window.ASSETS.kiwiLearn} alt="Tastermonial kiwi mascot" />
          </div>
        </div>
      </div>

      {/* progress strip */}
      <div className="progress-strip">
        <div className="wrap progress-inner">
          <span className="progress-label"><b>{doneCount}</b>/{totalItems} steps done</span>
          <div className="progress-track"><div className="progress-fill" style={{ width: pct + "%" }}></div></div>
          <span className="progress-label">{pct}%</span>
          <button className="btn btn-ghost pdf-btn" onClick={() => window.print()}>Save PDF</button>
        </div>
      </div>

      {/* what you need */}
      <section className="need" id="need">
        <div className="wrap">
          <div className="section-head">
            <div className="eyebrow" style={{ color: "var(--accent-ink)" }}><span className="dot"></span> Before you begin</div>
            <h2>What you'll need</h2>
          </div>
          <div className="need-grid">
            {[
              ["01", "Your Nourish kit", "The box mailed to you with your FreeStyle Libre 3 Plus sensor and experiment cards."],
              ["02", "A smartphone", "iOS or Android, to run the Tastermonial app and scan your kit."],
              ["03", "Your study QR Code", "Found on the Nourish card inside your kit — you'll scan it during sign-up."],
              ["04", "~20 minutes", "To set up. Then you'll wear the sensor and test foods over your study window."],
            ].map(([k, h, p]) => (
              <div className="need-item" key={k}>
                <span className="nk mono">{k}</span>
                <h4>{h}</h4>
                <p>{p}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* orientation */}
      <section id="orientation">
        <div className="wrap">
          <div className="orient">
            <div>
              <div className="eyebrow" style={{ color: "var(--accent-ink)" }}><span className="dot"></span> Start here</div>
              <h2>Watch the Stanford NOURISH orientation first</h2>
              <p className="desc" style={{ color: "var(--ink-soft)", marginTop: 14 }}>Before jumping into the steps, watch this orientation from the Stanford NOURISH team — it explains the study, what's expected of you, and how the pieces fit together.</p>
            </div>
            <Video step={{ n: 0, title: "Stanford NOURISH orientation", embed: "https://www.youtube.com/embed/eMK45UjgHgM" }} />
          </div>
        </div>
      </section>

      {/* guide */}
      <section id="guide" style={{ paddingTop: 0 }}>
        <div className="wrap">
          <div className="section-head">
            <div className="eyebrow" style={{ color: "var(--accent-ink)" }}><span className="dot"></span> Set up → Test → Learn</div>
            <h2>The step-by-step guide</h2>
            <p>Seven short steps take you from sensor to results. Check off each task as you finish — your progress is saved on this device.</p>
          </div>
          {layouts[t.videoLayout] || layouts.Stepper}
        </div>
      </section>

      {/* faq */}
      <section id="faq" style={{ paddingTop: 0 }}>
        <div className="wrap">
          <div className="section-head">
            <div className="eyebrow" style={{ color: "var(--accent-ink)" }}><span className="dot"></span> Good to know</div>
            <h2>Frequently asked</h2>
          </div>
          <Faq faqs={G.faqs} />
        </div>
      </section>

      {/* support */}
      <section style={{ paddingTop: 0 }}>
        <div className="wrap">
          <div className="support">
            <div>
              <h2>Study Team Office Hours</h2>
              <p>Questions about study procedures — applying your CGM sensor, syncing the app, logging meals, or any step in the protocol? The study team is here to help.</p>
              <dl className="support-info">
                <div><dt>Office hours</dt><dd>Tuesdays &amp; Thursdays, 9:00–11:00 AM Pacific Time</dd></div>
                <div><dt>Phone</dt><dd><a href="tel:+18664815142">+1 (866) 481-5142</a></dd></div>
                <div><dt>Email</dt><dd><a href="mailto:support@tastermonial.com?subject=NOURISH%20study%20question">support@tastermonial.com</a></dd></div>
              </dl>
              <ul className="support-tips">
                <li>Start your email subject with “NOURISH”</li>
                <li>Write from the email you used when signing up to the Tastermonial app</li>
                <li>Please don’t include personal health information beyond what’s necessary</li>
              </ul>
              <p className="support-note">Messages received outside office hours are answered within 24 hours.</p>
            </div>
            <div className="actions">
              <a className="btn btn-primary" href="https://help.tastermonial.com/en-US" target="_blank" rel="noopener">Visit support</a>
              <a className="btn btn-ghost" href="mailto:support@tastermonial.com?subject=NOURISH%20study%20question">Email us</a>
            </div>
          </div>
        </div>
      </section>

      {/* footer */}
      <footer className="site">
        <div className="wrap">
          <div className="fgrid">
            <div>
              <img className="logo" src={window.ASSETS.logo} alt="Tastermonial" />
              <p>Take control of your health through real-time, personalized nutrition insights — using continuous glucose monitors and experiments to uncover how your body responds to the foods you eat.</p>
            </div>
            <div>
              <h5>Guide</h5>
              <ul>
                <li><a href="#need">What you need</a></li>
                <li><a href="#guide">The steps</a></li>
                <li><a href="#faq">FAQ</a></li>
              </ul>
            </div>
            <div>
              <h5>Help</h5>
              <ul>
                <li><a href="https://help.tastermonial.com/en-US" target="_blank" rel="noopener">Support center</a></li>
                <li><a href="mailto:support@tastermonial.com">Email support</a></li>
                <li><a href="https://tastermonial.com" target="_blank" rel="noopener">tastermonial.com</a></li>
              </ul>
            </div>
          </div>
          <p className="disc">Disclaimer: Tastermonial uses FDA-approved continuous glucose monitors (CGMs). Our experiment kits, app insights, and educational materials are not medical devices and are not intended to diagnose, treat, cure, or prevent any disease. All content is for personal insight, wellness, and research use only. © 2026 Tastermonial.</p>
        </div>
      </footer>

      {/* tweaks */}
      <TweaksPanel>
        <TweakSection label="Theme" />
        <TweakColor label="Accent" value={ACCENTS[t.accent]}
          options={Object.values(ACCENTS)}
          onChange={(v) => setTweak("accent", Object.keys(ACCENTS).find((k) => ACCENTS[k] === v) || "Plum")} />
        <TweakSelect label="Fonts" value={t.fontPair} options={Object.keys(FONT_PAIRS)} onChange={(v) => setTweak("fontPair", v)} />
        <TweakSection label="Layout" />
        <TweakRadio label="Hero style" value={t.heroStyle} options={["Cream", "Plum"]} onChange={(v) => setTweak("heroStyle", v)} />
        <TweakRadio label="Video layout" value={t.videoLayout} options={["Stepper", "Grid", "List"]} onChange={(v) => setTweak("videoLayout", v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

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