/* global React, ReactDOM */
const { useState, useEffect, useRef, useMemo } = React;

// ===== Recipe data =====
const RECIPE = {
  title: "Butter Chicken",
  subtitle: "Murgh Makhani",
  tagline:
    "An easy, deeply spiced butter chicken with a creamy tomato sauce. Tastes like takeout — made in your own kitchen, even if you've never cooked Indian food before.",
  meta: {
    active: "35 min",
    total: "1 hr 20 min",
    serves: 4,
    difficulty: "Easy",
  },
  story: [
    "Butter chicken is what got me into Indian cooking. I'd order it every time it appeared on a menu, then spent years trying to replicate that velvety, slightly-smoky, faintly-sweet sauce at home.",
    "The trick, it turns out, isn't a secret ingredient. It's three things: marinating the chicken in yogurt and aromatics so it stays tender, blooming the spices in butter until they smell like a restaurant kitchen, and finishing with a generous splash of cream and a pinch of crushed kasuri methi — dried fenugreek leaves — which is the single most important thing you can add and the one ingredient most home recipes leave out.",
    "This version is the result of about forty attempts. It is not authentic to any particular region; it is authentic to my kitchen, and to people who have never cooked Indian food before. Read through once, then start.",
  ],
  ingredients: [
    {
      section: "For the marinade",
      items: [
        { qty: 1.5, unit: "lb", name: "boneless, skinless chicken thighs", note: "cut into 1½-inch pieces" },
        { qty: 0.5, unit: "cup", name: "full-fat plain yogurt" },
        { qty: 1, unit: "tbsp", name: "lemon juice" },
        { qty: 2, unit: "tsp", name: "garam masala" },
        { qty: 1, unit: "tsp", name: "ground turmeric" },
        { qty: 1, unit: "tsp", name: "ground cumin" },
        { qty: 1, unit: "tsp", name: "Kashmiri chili powder", note: "or ½ tsp cayenne + ½ tsp paprika" },
        { qty: 1, unit: "tbsp", name: "fresh ginger", note: "grated" },
        { qty: 4, unit: "cloves", name: "garlic", note: "grated" },
        { qty: 1, unit: "tsp", name: "kosher salt" },
      ],
    },
    {
      section: "For the sauce",
      items: [
        { qty: 4, unit: "tbsp", name: "unsalted butter", note: "divided" },
        { qty: 1, unit: "tbsp", name: "neutral oil" },
        { qty: 1, unit: "", name: "yellow onion", note: "finely diced" },
        { qty: 1, unit: "tbsp", name: "fresh ginger", note: "grated" },
        { qty: 4, unit: "cloves", name: "garlic", note: "grated" },
        { qty: 1, unit: "", name: "small green chili", note: "split, optional" },
        { qty: 2, unit: "tsp", name: "garam masala" },
        { qty: 1, unit: "tsp", name: "ground coriander" },
        { qty: 1, unit: "tsp", name: "Kashmiri chili powder" },
        { qty: 1, unit: "tsp", name: "ground cumin" },
        { qty: 1, unit: "can", name: "whole peeled tomatoes (28 oz)", note: "puréed smooth" },
        { qty: 1, unit: "tbsp", name: "tomato paste" },
        { qty: 1, unit: "tsp", name: "sugar" },
        { qty: 0.75, unit: "cup", name: "heavy cream" },
        { qty: 1, unit: "tbsp", name: "kasuri methi", note: "crushed between your palms" },
        { qty: 1, unit: "tsp", name: "kosher salt", note: "plus more to taste" },
      ],
    },
    {
      section: "To finish",
      items: [
        { qty: 0.25, unit: "cup", name: "cilantro", note: "roughly chopped" },
        { qty: 2, unit: "tbsp", name: "heavy cream", note: "for swirling" },
        { qty: 1, unit: "", name: "basmati rice or naan", note: "for serving" },
      ],
    },
  ],
  steps: [
    {
      title: "Marinate the chicken",
      time: 30,
      timeLabel: "30 min, up to overnight",
      body:
        "In a medium bowl, whisk the yogurt with lemon juice, garam masala, turmeric, cumin, chili powder, ginger, garlic, and salt. Add the chicken, turn to coat every piece, and refrigerate for at least 30 minutes. Overnight is better — the yogurt's acid tenderizes the meat and lets the spices penetrate.",
      tip: "Don't skip the salt in the marinade. It's the only thing seasoning the chicken from the inside.",
    },
    {
      title: "Sear the chicken",
      time: 8,
      timeLabel: "about 8 min",
      body:
        "Heat 1 tablespoon of the butter and the oil in a wide, heavy pot over medium-high heat until shimmering. Working in two batches so you don't crowd the pan, add the chicken in a single layer and sear for 2–3 minutes per side, just until deeply browned but not cooked through. Transfer to a plate and set aside. The browned bits in the pan are flavor — leave them.",
      tip: "The chicken will finish cooking in the sauce. You're after color here, not doneness.",
    },
    {
      title: "Build the base",
      time: 10,
      timeLabel: "about 10 min",
      body:
        "Lower the heat to medium and add the remaining 3 tablespoons of butter to the same pot. When it foams, add the onion with a pinch of salt and cook, stirring often, until deeply golden — about 8 minutes. Add the ginger, garlic, and chili (if using) and cook 1 minute more until very fragrant.",
    },
    {
      title: "Bloom the spices",
      time: 1,
      timeLabel: "60 seconds",
      body:
        "Add the garam masala, coriander, chili powder, and cumin. Stir constantly for 30–60 seconds until the spices smell toasty and the oil turns brick-red. This is the single step that separates a flat sauce from a deeply flavored one. Don't let them burn.",
      tip: "If your pan is too hot, pull it off the heat and stir for the full minute off the burner.",
    },
    {
      title: "Simmer the sauce",
      time: 15,
      timeLabel: "15 min",
      body:
        "Stir in the tomato paste and cook 1 minute, then add the puréed tomatoes, sugar, and salt. Bring to a low simmer and cook uncovered for 12–15 minutes, stirring every few minutes, until the sauce darkens to a deep rust color and a wooden spoon dragged across the bottom leaves a trail that holds for a second.",
    },
    {
      title: "Finish",
      time: 8,
      timeLabel: "about 8 min",
      body:
        "Return the chicken and any juices to the pot and simmer 5 minutes, until the chicken is just cooked through. Lower the heat, stir in the cream, and crumble the kasuri methi between your palms directly into the pot — this releases its oils. Taste; it will want more salt than you expect. Cover and let sit off the heat for 5 minutes.",
      tip: "Off-heat resting is real. The sauce thickens and the spices round out.",
    },
    {
      title: "Serve",
      time: 0,
      timeLabel: "now",
      body:
        "Swirl a thread of cream on top, scatter cilantro, and serve over basmati rice with warm naan for tearing and dragging through the sauce. Make a small audible noise of appreciation. You earned it.",
    },
  ],
  tips: [
    {
      h: "The kasuri methi is non-negotiable",
      p: "It's the dried-fenugreek-leaf smell you've been chasing. Indian grocers, most spice shops, Amazon. A bag lasts a year.",
    },
    {
      h: "Thighs over breasts, always",
      p: "Breasts dry out in the time it takes the sauce to develop. Thighs stay juicy and forgiving.",
    },
    {
      h: "Make it ahead",
      p: "The sauce is better the next day. Cook through Step 5, refrigerate, then reheat gently with the chicken and cream the night you're serving.",
    },
    {
      h: "Heat level",
      p: "Kashmiri chili is mild and adds color, not fire. For more heat, add a second split green chili in step 3 or a pinch of cayenne with the bloomed spices.",
    },
  ],
};

// ===== Helpers =====
function scaleQty(qty, factor) {
  if (qty == null || qty === "") return "";
  const v = qty * factor;
  if (v === Math.floor(v)) return String(v);
  // Friendly fractions
  const fractions = [
    [0.125, "⅛"],
    [0.25, "¼"],
    [0.333, "⅓"],
    [0.5, "½"],
    [0.666, "⅔"],
    [0.75, "¾"],
  ];
  const whole = Math.floor(v);
  const frac = v - whole;
  let best = null;
  let bestDiff = 1;
  for (const [f, s] of fractions) {
    const d = Math.abs(frac - f);
    if (d < bestDiff && d < 0.06) {
      bestDiff = d;
      best = s;
    }
  }
  if (best) return whole === 0 ? best : `${whole}${best}`;
  return v.toFixed(2).replace(/\.?0+$/, "");
}

// ===== Unsplash photo component =====
// Real photos via Unsplash. We pass focal-point + size params for quality.
function Photo({ src, alt, aspect = "4/3", focal = "center" }) {
  const [loaded, setLoaded] = useState(false);
  return (
    <div className="ph" style={{ aspectRatio: aspect }}>
      <img
        src={src}
        alt={alt}
        loading="lazy"
        onLoad={() => setLoaded(true)}
        style={{
          width: "100%",
          height: "100%",
          objectFit: "cover",
          objectPosition: focal,
          opacity: loaded ? 1 : 0,
          transition: "opacity 0.5s ease",
        }}
      />
      {!loaded && <span className="ph-label">loading photo…</span>}
    </div>
  );
}

// ===== Components =====
function Header({ onJump }) {
  return (
    <header className="site-header">
      <div className="brand">
        <span className="brand-mark" aria-hidden="true">
          <svg viewBox="0 0 32 32" width="22" height="22">
            <circle cx="16" cy="16" r="13" fill="currentColor" opacity="0.18" />
            <circle cx="16" cy="16" r="8" fill="currentColor" />
          </svg>
        </span>
        <span className="brand-name">Make Butter Chicken At Home</span>
      </div>
      <nav className="site-nav">
        <button className="nav-home" onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })} aria-label="Home">
          <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
            <path d="M3 11.5 12 4l9 7.5V20a1 1 0 0 1-1 1h-5v-6h-6v6H4a1 1 0 0 1-1-1v-8.5Z" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" />
          </svg>
          Home
        </button>
        <button onClick={() => onJump("video")}>Video</button>
        <button onClick={() => onJump("ingredients")}>Ingredients</button>
        <button onClick={() => onJump("method")}>Method</button>
        <button onClick={() => onJump("tips")}>Tips</button>
        <button onClick={() => onJump("about")}>About</button>
      </nav>
    </header>
  );
}

function Hero() {
  return (
    <section className="hero">
      <div className="hero-text">
        <div className="kicker">A recipe · Indian · Weeknight</div>
        <h1 className="display">
          The Best <em>Butter Chicken</em><br />You'll Make at Home.
        </h1>
        <p className="lede">{RECIPE.tagline}</p>
        <div className="meta-row">
          <Meta label="Active" value={RECIPE.meta.active} />
          <Meta label="Total" value={RECIPE.meta.total} />
          <Meta label="Serves" value={RECIPE.meta.serves} />
          <Meta label="Level" value={RECIPE.meta.difficulty} />
        </div>
        <div className="hero-cta">
          <a className="btn primary" href="#ingredients">Start cooking</a>
          <a className="btn ghost" href="#about">Read the story</a>
        </div>
      </div>
      <div className="hero-image">
        <Photo
          src="images/hero-butter-chicken.png"
          alt="A copper karahi of butter chicken finished with cream swirls and cilantro, served with basmati rice and garlic naan"
          aspect="5/6"
          focal="center"
        />
        <div className="hero-tag">
          <span className="dot" />
          made 12,400+ times this month
        </div>
      </div>
    </section>
  );
}

function Meta({ label, value }) {
  return (
    <div className="meta">
      <div className="meta-label">{label}</div>
      <div className="meta-value">{value}</div>
    </div>
  );
}

function StorySection() {
  return (
    <section className="story" id="about">
      <div className="rule"><span>The story</span></div>
      <div className="story-grid">
        <h2 className="h2">Forty tries to taste like takeout.</h2>
        <div className="story-body">
          {RECIPE.story.map((p, i) => (
            <p key={i}>{p}</p>
          ))}
          <div className="pullquote">
            "Read through once, then start."
          </div>
        </div>
      </div>
    </section>
  );
}

function Ingredients() {
  const [scale, setScale] = useState(1);
  const [unit, setUnit] = useState("us"); // us | metric
  const [checked, setChecked] = useState(() => {
    try {
      return JSON.parse(localStorage.getItem("bc:checked") || "{}");
    } catch (e) {
      return {};
    }
  });

  useEffect(() => {
    localStorage.setItem("bc:checked", JSON.stringify(checked));
  }, [checked]);

  const toggle = (key) => setChecked((c) => ({ ...c, [key]: !c[key] }));
  const clear = () => setChecked({});

  const serves = Math.round(RECIPE.meta.serves * scale * 10) / 10;

  return (
    <section className="ingredients" id="ingredients">
      <div className="rule"><span>Ingredients</span></div>

      <div className="ing-controls">
        <div className="serves-block">
          <div className="serves-label">Serves</div>
          <div className="serves-stepper">
            <button
              aria-label="Fewer"
              onClick={() => setScale((s) => Math.max(0.25, +(s - 0.25).toFixed(2)))}
            >
              −
            </button>
            <div className="serves-count">
              <span className="num">{serves}</span>
              <span className="x">{scale === 1 ? "original" : `${scale}× scale`}</span>
            </div>
            <button
              aria-label="More"
              onClick={() => setScale((s) => Math.min(6, +(s + 0.25).toFixed(2)))}
            >
              +
            </button>
          </div>
        </div>

        <div className="unit-toggle" role="tablist" aria-label="Units">
          <button
            role="tab"
            aria-selected={unit === "us"}
            className={unit === "us" ? "on" : ""}
            onClick={() => setUnit("us")}
          >
            US
          </button>
          <button
            role="tab"
            aria-selected={unit === "metric"}
            className={unit === "metric" ? "on" : ""}
            onClick={() => setUnit("metric")}
          >
            Metric
          </button>
        </div>

        <button className="link-btn" onClick={clear}>Reset checklist</button>
      </div>

      <div className="ing-grid">
        {RECIPE.ingredients.map((group, gi) => (
          <div key={gi} className="ing-group">
            <h3 className="ing-section">{group.section}</h3>
            <ul className="ing-list">
              {group.items.map((it, i) => {
                const key = `${gi}-${i}`;
                const isChecked = !!checked[key];
                return (
                  <li
                    key={key}
                    className={"ing-item" + (isChecked ? " checked" : "")}
                    onClick={() => toggle(key)}
                  >
                    <span className="check" aria-hidden="true">
                      {isChecked ? "✓" : ""}
                    </span>
                    <span className="qty">
                      {scaleQty(it.qty, scale)} {it.unit}
                    </span>
                    <span className="ing-name">
                      {it.name}
                      {it.note && <span className="ing-note">, {it.note}</span>}
                    </span>
                  </li>
                );
              })}
            </ul>
          </div>
        ))}
      </div>
    </section>
  );
}

function Timer({ minutes }) {
  const [remaining, setRemaining] = useState(minutes * 60);
  const [running, setRunning] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    if (running) {
      ref.current = setInterval(() => {
        setRemaining((r) => {
          if (r <= 1) {
            clearInterval(ref.current);
            setRunning(false);
            try {
              // gentle ping
              const ctx = new (window.AudioContext || window.webkitAudioContext)();
              const o = ctx.createOscillator();
              const g = ctx.createGain();
              o.connect(g);
              g.connect(ctx.destination);
              o.frequency.value = 660;
              g.gain.value = 0.08;
              o.start();
              setTimeout(() => {
                o.stop();
                ctx.close();
              }, 400);
            } catch (e) {}
            return 0;
          }
          return r - 1;
        });
      }, 1000);
    }
    return () => clearInterval(ref.current);
  }, [running]);

  const m = Math.floor(remaining / 60);
  const s = remaining % 60;
  const total = minutes * 60;
  const pct = total > 0 ? ((total - remaining) / total) * 100 : 0;
  const done = remaining === 0;

  return (
    <div className={"timer" + (running ? " running" : "") + (done ? " done" : "")}>
      <button
        className="timer-btn"
        onClick={() => {
          if (done) {
            setRemaining(minutes * 60);
            setRunning(true);
          } else {
            setRunning((r) => !r);
          }
        }}
        aria-label={running ? "Pause timer" : "Start timer"}
      >
        {done ? "↻" : running ? "❚❚" : "▶"}
      </button>
      <div className="timer-readout">
        <div className="timer-time">
          {String(m).padStart(2, "0")}:{String(s).padStart(2, "0")}
        </div>
        <div className="timer-bar">
          <div className="timer-fill" style={{ width: pct + "%" }} />
        </div>
      </div>
    </div>
  );
}

function Method() {
  const [done, setDone] = useState(() => {
    try {
      return JSON.parse(localStorage.getItem("bc:steps") || "{}");
    } catch (e) {
      return {};
    }
  });
  const [activeTimer, setActiveTimer] = useState(null);

  useEffect(() => {
    localStorage.setItem("bc:steps", JSON.stringify(done));
  }, [done]);

  const completed = Object.values(done).filter(Boolean).length;
  const pct = (completed / RECIPE.steps.length) * 100;

  return (
    <section className="method" id="method">
      <div className="rule"><span>Method</span></div>

      <div className="progress-block">
        <div className="progress-label">
          <span>Your progress</span>
          <span className="progress-count">
            {completed} of {RECIPE.steps.length} steps
          </span>
        </div>
        <div className="progress-bar">
          <div className="progress-fill" style={{ width: pct + "%" }} />
        </div>
      </div>

      <ol className="steps">
        {RECIPE.steps.map((step, i) => {
          const isDone = !!done[i];
          return (
            <li key={i} className={"step" + (isDone ? " done" : "")}>
              <div className="step-num">
                <button
                  className="step-check"
                  onClick={() => setDone((d) => ({ ...d, [i]: !d[i] }))}
                  aria-label={isDone ? "Mark step incomplete" : "Mark step complete"}
                >
                  {isDone ? "✓" : String(i + 1).padStart(2, "0")}
                </button>
              </div>
              <div className="step-body">
                <div className="step-head">
                  <h3 className="step-title">{step.title}</h3>
                  {step.timeLabel && (
                    <div className="step-time">{step.timeLabel}</div>
                  )}
                </div>
                <p className="step-text">{step.body}</p>
                {step.tip && (
                  <div className="step-tip">
                    <span className="tip-label">Note</span>
                    {step.tip}
                  </div>
                )}
                {step.time > 0 && (
                  <div className="step-timer">
                    {activeTimer === i ? (
                      <Timer minutes={step.time} key={i} />
                    ) : (
                      <button
                        className="btn ghost small"
                        onClick={() => setActiveTimer(i)}
                      >
                        Set a {step.time}-min timer
                      </button>
                    )}
                  </div>
                )}
              </div>
            </li>
          );
        })}
      </ol>
    </section>
  );
}

function Tips() {
  return (
    <section className="tips" id="tips">
      <div className="rule"><span>Notes from the kitchen</span></div>
      <div className="tip-grid">
        {RECIPE.tips.map((t, i) => (
          <div key={i} className="tip-card">
            <div className="tip-index">{String(i + 1).padStart(2, "0")}</div>
            <h3 className="tip-h">{t.h}</h3>
            <p>{t.p}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function Gallery() {
  const u = (id, w = 1200) =>
    `https://images.unsplash.com/photo-${id}?w=${w}&q=80&auto=format&fit=crop`;
  return (
    <section className="gallery">
      <div className="rule"><span>What it should look like</span></div>
      <div className="gal-grid">
        <div className="gal-cell tall">
          <Photo
            src={u("1565557623262-b51c2513a641", 900)}
            alt="Indian spices in small bowls, ground for cooking"
            aspect="auto"
          />
        </div>
        <div className="gal-cell">
          <Photo
            src={u("1588166524941-3bf61a9c41db", 900)}
            alt="A deep rust-red butter chicken sauce in a pan"
            aspect="auto"
          />
        </div>
        <div className="gal-cell">
          <Photo
            src={u("1601050690597-df0568f70950", 900)}
            alt="Cream swirled into a curry, garnished with cilantro"
            aspect="auto"
          />
        </div>
        <div className="gal-cell wide">
          <Photo
            src={u("1631452180519-c014fe946bc7", 1600)}
            alt="Butter chicken served with naan and basmati rice on a table"
            aspect="auto"
            focal="center 60%"
          />
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="site-footer">
      <div className="foot-inner">
        <div className="foot-brand">
          <div className="display-sm">Make Butter Chicken At Home<span className="dot-period">.</span></div>
          <p>One recipe, made better forty times. Cook it, change it, make it yours.</p>
        </div>
        <div className="foot-cols">
          <div>
            <div className="foot-h">Recipe</div>
            <a href="#ingredients">Ingredients</a>
            <a href="#method">Method</a>
            <a href="#tips">Tips</a>
          </div>
          <div>
            <div className="foot-h">Index</div>
            <a href="#">All recipes</a>
            <a href="#">Pantry</a>
            <a href="#">Newsletter</a>
          </div>
          <div>
            <div className="foot-h">Elsewhere</div>
            <a href="#">Instagram</a>
            <a href="#">YouTube</a>
            <a href="#">RSS</a>
          </div>
        </div>
      </div>
      <div className="foot-base">
        <span>© 2026 Make Butter Chicken At Home</span>
        <span className="foot-links">
          <a href="privacy.html">Privacy Policy</a>
          <span className="sep">·</span>
          <a href="#">Terms</a>
          <span className="sep">·</span>
          <span>Photos via Unsplash</span>
        </span>
      </div>
    </footer>
  );
}

// ===== Tweaks =====
const PALETTES = {
  ember:    { bg: "#F6EFE4", ink: "#1F1612", accent: "#D14D24", accent2: "#E2A52B", muted: "#7A6A5C", card: "#FFFAF1", line: "rgba(31,22,18,0.12)" },
  saffron:  { bg: "#FBF4E3", ink: "#1A1206", accent: "#C68417", accent2: "#8E2B14", muted: "#7A6A4A", card: "#FFFCEC", line: "rgba(26,18,6,0.12)" },
  charcoal: { bg: "#1C1814", ink: "#F4ECDF", accent: "#E66A3A", accent2: "#F2BD53", muted: "#A89A86", card: "#272118", line: "rgba(244,236,223,0.14)" },
  herb:     { bg: "#F1EFE5", ink: "#13211A", accent: "#7E5A2A", accent2: "#4D6A3C", muted: "#6E6A5C", card: "#F9F7EE", line: "rgba(19,33,26,0.12)" },
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "ember",
  "displayFont": "Instrument Serif",
  "heatLevel": "medium",
  "showGallery": true,
  "wideLayout": false
}/*EDITMODE-END*/;

function applyPalette(name) {
  const p = PALETTES[name] || PALETTES.ember;
  const r = document.documentElement;
  Object.entries(p).forEach(([k, v]) => r.style.setProperty(`--${k}`, v));
  r.dataset.palette = name;
}

function applyFont(name) {
  document.documentElement.style.setProperty("--display-font", `"${name}", Georgia, serif`);
}

function Tweaks() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const { TweaksPanel, TweakSection, TweakRadio, TweakToggle, TweakSelect } = window;

  useEffect(() => { applyPalette(t.palette); }, [t.palette]);
  useEffect(() => { applyFont(t.displayFont); }, [t.displayFont]);
  useEffect(() => {
    document.documentElement.classList.toggle("wide", !!t.wideLayout);
    document.documentElement.classList.toggle("show-gallery", !!t.showGallery);
  }, [t.wideLayout, t.showGallery]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Palette">
        <TweakSelect
          label="Theme"
          value={t.palette}
          onChange={(v) => setTweak("palette", v)}
          options={[
            { value: "ember", label: "Ember (default)" },
            { value: "saffron", label: "Saffron" },
            { value: "charcoal", label: "Charcoal" },
            { value: "herb", label: "Herb garden" },
          ]}
        />
      </TweakSection>
      <TweakSection title="Type">
        <TweakSelect
          label="Display font"
          value={t.displayFont}
          onChange={(v) => setTweak("displayFont", v)}
          options={["Instrument Serif", "DM Serif Display", "Cormorant Garamond", "EB Garamond"]}
        />
      </TweakSection>
      <TweakSection title="Layout">
        <TweakToggle
          label="Show photo gallery"
          value={t.showGallery}
          onChange={(v) => setTweak("showGallery", v)}
        />
        <TweakToggle
          label="Wide layout"
          value={t.wideLayout}
          onChange={(v) => setTweak("wideLayout", v)}
        />
      </TweakSection>
      <TweakSection title="Recipe">
        <TweakRadio
          label="Heat"
          value={t.heatLevel}
          onChange={(v) => setTweak("heatLevel", v)}
          options={[
            { value: "mild", label: "Mild" },
            { value: "medium", label: "Medium" },
            { value: "hot", label: "Hot" },
          ]}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

function VideoSection() {
  const [playing, setPlaying] = useState(false);
  const videoId = "nHj09xU40bM";
  const thumb = `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`;
  const embed = `https://www.youtube-nocookie.com/embed/${videoId}?autoplay=1&rel=0&modestbranding=1&playsinline=1`;
  const watchOnYT = `https://youtu.be/${videoId}`;
  return (
    <section className="video" id="video">
      <div className="rule"><span>Watch · 22 min</span></div>
      <div className="video-grid">
        <div className="video-text">
          <h2 className="h2">Everything I learned, in one sitting.</h2>
          <p className="video-lede">
            A walkthrough of the whole recipe — picking the right chili powder, why kasuri methi matters, the spoon-trail test for the sauce, and how the finished dish should look and smell. Watch it once before you cook; it'll save you an attempt or two.
          </p>
          <ul className="video-chapters">
            <li><span className="ts">00:00</span> Intro &amp; what makes butter chicken butter chicken</li>
            <li><span className="ts">02:18</span> The marinade — yogurt, acid, and time</li>
            <li><span className="ts">06:40</span> Searing without crowding the pan</li>
            <li><span className="ts">09:15</span> Blooming the spices (the brick-red moment)</li>
            <li><span className="ts">12:50</span> Building the tomato base</li>
            <li><span className="ts">16:30</span> Cream, methi, and the off-heat rest</li>
            <li><span className="ts">19:42</span> Plating, naan, and what to do with leftovers</li>
          </ul>
          <a className="btn ghost small video-yt-link" href={watchOnYT} target="_blank" rel="noopener noreferrer">
            <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
              <path d="M14 3h7v7M21 3l-9 9M10 5H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            Open on YouTube
          </a>
        </div>
        <div className="video-frame">
          {playing ? (
            <iframe
              src={embed}
              title="Butter Chicken — full walkthrough"
              frameBorder="0"
              referrerPolicy="strict-origin-when-cross-origin"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
              allowFullScreen
            />
          ) : (
            <button
              className="video-poster"
              onClick={() => setPlaying(true)}
              aria-label="Play video"
            >
              <img
                src={thumb}
                alt=""
                loading="lazy"
                onError={(e) => {
                  e.currentTarget.src = `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`;
                }}
              />
              <span className="video-play">
                <svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true">
                  <path d="M8 5v14l11-7z" fill="currentColor" />
                </svg>
              </span>
              <span className="video-meta">
                <span className="video-tag">YouTube · 22:08</span>
                <span className="video-title">The complete butter chicken guide</span>
              </span>
            </button>
          )}
        </div>
      </div>
    </section>
  );
}

// ===== App =====
function App() {
  const onJump = (id) => {
    const el = document.getElementById(id);
    if (el) {
      window.scrollTo({ top: el.offsetTop - 60, behavior: "smooth" });
    }
  };

  return (
    <div className="page">
      <Header onJump={onJump} />
      <main>
        <Hero />
        <VideoSection />
        <StorySection />
        <Ingredients />
        <Method />
        <Gallery />
        <Tips />
      </main>
      <Footer />
      <Tweaks />
    </div>
  );
}

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