// SPELLBOOK — landing page main app
const { useState, useEffect, useRef } = React;

/* ---------- shared UI bits ---------- */

// Auto-cycling animated glyph for the hero
function HeroGlyph() {
  const liveSpells = (window.SPELLS || []).filter(s => !s.coming);
  const [idx, setIdx] = useState(0);
  const pathRef = useRef(null);
  const [len, setLen] = useState(0);

  useEffect(() => {
    if (pathRef.current) {
      const l = pathRef.current.getTotalLength();
      setLen(l);
    }
  }, [idx]);

  useEffect(() => {
    const t = setTimeout(() => setIdx(i => (i + 1) % liveSpells.length), 3800);
    return () => clearTimeout(t);
  }, [idx, liveSpells.length]);

  const cur = liveSpells[idx];
  if (!cur) return null;

  return (
    <div className="hero-glyph">
      <div className="hero-glyph-top">
        <span>✦ Casting</span>
        <span className="hero-glyph-status">
          <span className="hero-glyph-dot" /> Watch detecting
        </span>
      </div>

      <div className="hero-glyph-stage">
        {/* Concentric runic rings */}
        <svg className="hero-glyph-rings" viewBox="-100 -100 200 200">
          <circle cx="0" cy="0" r="80" fill="none" stroke="rgba(255,212,58,0.08)" strokeWidth="0.5" />
          <circle cx="0" cy="0" r="88" fill="none" stroke="rgba(255,212,58,0.06)" strokeWidth="0.5" strokeDasharray="2 4" />
          <circle cx="0" cy="0" r="70" fill="none" stroke="rgba(157,108,255,0.16)" strokeWidth="0.7" />
          {/* runic ticks */}
          {Array.from({length: 24}).map((_, i) => {
            const a = (i / 24) * Math.PI * 2;
            const x1 = Math.cos(a) * 90, y1 = Math.sin(a) * 90;
            const x2 = Math.cos(a) * 95, y2 = Math.sin(a) * 95;
            return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="rgba(255,212,58,0.25)" strokeWidth="0.6" />;
          })}
        </svg>

        {/* The glyph itself, drawn with stroke-dashoffset animation */}
        <svg className="hero-glyph-svg" viewBox="0 0 100 100" key={idx}>
          <defs>
            <filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
              <feGaussianBlur stdDeviation="2" result="blur" />
              <feMerge>
                <feMergeNode in="blur" />
                <feMergeNode in="SourceGraphic" />
              </feMerge>
            </filter>
          </defs>
          <path
            ref={pathRef}
            d={cur.glyph}
            fill="none"
            stroke="var(--gold)"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            filter="url(#glow)"
            style={{
              strokeDasharray: len,
              strokeDashoffset: len,
              animation: 'drawGlyph 1.4s ease-out forwards, fadeGlyph 1.2s ease-in 2.4s forwards',
            }}
          />
        </svg>
      </div>

      <div className="hero-glyph-info" key={`info-${idx}`}>
        <div className="hero-glyph-name">{cur.name}</div>
        <div className="hero-glyph-pron">{cur.pron} · {cur.shape}</div>
        <div className="hero-glyph-purpose">{cur.purpose}</div>
      </div>

      <div className="hero-glyph-progress">
        {liveSpells.map((_, i) => (
          <span key={i} className={"hero-glyph-tick " + (i === idx ? "active" : "")} />
        ))}
      </div>
    </div>
  );
}

function SpellGlyph({ d, size = 84, className = "" }) {
  return (
    <svg className={"spell-glyph " + className} viewBox="0 0 100 100" width={size} height={size}>
      <path d={d} />
    </svg>
  );
}

function AppStoreBadge() {
  return (
    <a href="https://apps.apple.com/us/app/spellbook-real-wand-gestures/id6759551250" className="app-store-badge" aria-label="Download on the App Store">
      <svg viewBox="0 0 24 24" fill="currentColor">
        <path d="M17.05 12.04c-.03-2.78 2.27-4.12 2.37-4.18-1.29-1.89-3.3-2.15-4.02-2.18-1.71-.17-3.34 1.01-4.21 1.01-.87 0-2.21-.99-3.64-.96C5.71 5.76 4.02 6.81 3.1 8.43c-1.95 3.38-.5 8.38 1.39 11.12.93 1.34 2.04 2.85 3.49 2.8 1.41-.06 1.94-.91 3.64-.91 1.7 0 2.18.91 3.66.88 1.51-.03 2.47-1.37 3.39-2.71 1.07-1.55 1.51-3.06 1.53-3.14-.03-.02-2.93-1.12-2.96-4.43zM14.49 4.04c.77-.94 1.29-2.23 1.15-3.52-1.11.05-2.46.74-3.26 1.67-.71.82-1.34 2.15-1.17 3.41 1.24.1 2.51-.63 3.28-1.56z"/>
      </svg>
      <span>
        <small>Download on the</small>
        <strong>App Store</strong>
      </span>
    </a>
  );
}

function PhoneFrame({ src, alt }) {
  return (
    <div className="phone">
      <div className="phone-notch" />
      <div className="phone-screen">
        <img src={src} alt={alt} />
      </div>
    </div>
  );
}

/* ---------- nav ---------- */
function Nav() {
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a className="brand" href="#top">
          <svg className="brand-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M14 4l-1.2 4-4 1.2 4 1.2L14 14.6l1.2-4.2 4-1.2-4-1.2zM6 14l-.6 2-2 .6 2 .6.6 2 .6-2 2-.6-2-.6zM18.5 17l-.4 1.3-1.3.4 1.3.4.4 1.3.4-1.3 1.3-.4-1.3-.4z"/>
          </svg>
          SPELLBOOK
        </a>
        <div className="nav-links">
          <a href="#spells">Spells</a>
          <a href="#features">Features</a>
          <a href="#duel">Duelling</a>
          <a href="#pricing">Pricing</a>
          <a href="#faq">FAQ</a>
        </div>
        <a href="https://apps.apple.com/us/app/spellbook-real-wand-gestures/id6759551250" className="btn btn-primary" style={{padding: '10px 18px', fontSize: 13, whiteSpace: 'nowrap'}}>
          Get the App
        </a>
      </div>
    </nav>
  );
}

/* ---------- hero ---------- */
function Hero() {
  return (
    <section className="hero" id="top">
      <div className="wrap">
        <div className="hero-grid">
          <div>
            <div className="hero-eyebrow">
              <span className="eyebrow">✦ Apple Watch · Standalone</span>
            </div>
            <h1 className="display">
              Your wrist<br/>is a <span className="serif">wand</span>.<br/>
              <span className="accent">Cast spells.</span>
            </h1>
            <p className="lede">
              Spellbook turns your Apple Watch into a wand. Trace one of <em>10 spells</em> with
              your wrist — light up rooms, dim the scene, unlock doors,
              even duel a friend. Entirely on-device. No accounts.
            </p>
            <div className="hero-cta">
              <AppStoreBadge />
              <a href="#spells" className="btn btn-ghost">See the spells →</a>
            </div>
            <div className="hero-meta">
              <span>● 10 spells</span>
              <span>● HomeKit ready</span>
              <span>● watchOS 9+</span>
            </div>
          </div>
          <div>
            <HeroGlyph />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- spells gallery ---------- */
function SpellsGallery() {
  return (
    <section className="block" id="spells">
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow">The Grimoire</span>
          <h2 className="section-title">Ten spells.<br/>Eight ready now.</h2>
          <p className="lede">
            Each one is a distinct wrist motion — recorded once, recognized forever.
            Don't like the latin? <em>Rename any spell</em> to whatever feels right.
          </p>
        </div>
        <div className="spells">
          {window.SPELLS.map(s => (
            <div key={s.id} className={"spell-card " + (s.coming ? "coming" : "")}>
              {s.coming && <span className="badge badge-soon">Soon</span>}
              <SpellGlyph d={s.glyph} />
              <span className="spell-name">{s.name}</span>
              <div className="pron">{s.pron}</div>
              <div className="shape-label">{s.shape}</div>
              <div className="purpose">{s.purpose}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- features (cast / learn / actions / homekit / fine tune) ---------- */
function Features() {
  return (
    <section className="block" id="features">
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow">How it works</span>
          <h2 className="section-title">Wrist motion in.<br/>Magic out.</h2>
        </div>

        <div className="features">
          {/* Cast — wide */}
          <div className="feature span-7">
            <div className="feature-eyebrow">
              <span className="eyebrow" style={{color: 'var(--violet)'}}>① Cast</span>
            </div>
            <h3>Cast Spells</h3>
            <p>
              Your Apple Watch reads wrist motion and matches one of the 10 patterns in real time.
              A glowing glyph confirms the cast on iPhone — cinematic, dramatic, and instant.
            </p>
            <div className="feature-shot">
              <PhoneFrame src="assets/screen-cast.jpg" alt="Cast Spells screen" />
            </div>
          </div>

          {/* Learn — narrow */}
          <div className="feature span-5">
            <div className="feature-eyebrow">
              <span className="eyebrow" style={{color: 'var(--violet)'}}>② Learn</span>
            </div>
            <h3>Learn the<br/>Movements</h3>
            <p>
              Step-by-step animations show you exactly how to trace each spell — and you can rename
              every one. Prefer <span className="spell-name">Lumos</span> over <span className="spell-name">Lucernas</span>?
              Yours to choose.
            </p>
            <div className="feature-shot">
              <PhoneFrame src="assets/screen-learn.jpg" alt="Learn Spells screen" />
            </div>
          </div>

          {/* Actions — wide */}
          <div className="feature span-5">
            <div className="feature-eyebrow">
              <span className="eyebrow" style={{color: 'var(--violet)'}}>③ Actions</span>
              <span className="badge badge-premium">Premium</span>
            </div>
            <h3>Bind any Action</h3>
            <p>
              Tie a spell to anything: toggle lights, run a scene, play media, adjust brightness.
              Layer in custom sounds and haptics for that real-magic feel.
            </p>
            <div className="feature-shot">
              <PhoneFrame src="assets/screen-actions.jpg" alt="Actions screen" />
            </div>
          </div>

          {/* HomeKit — wide */}
          <div className="feature span-7">
            <div className="feature-eyebrow">
              <span className="eyebrow" style={{color: 'var(--violet)'}}>④ HomeKit</span>
              <span className="badge badge-premium">Premium</span>
            </div>
            <h3>Control the Room</h3>
            <p>
              Every HomeKit accessory is targetable — by room, by scene, or individually.
              Cast <span className="spell-name">Lucernas</span> in the bedroom, the bedroom lights come on.
              Rotate your wrist after casting to use <em>attunement mode</em> — dial in brightness or hue with a twist.
            </p>
            <div className="feature-shot">
              <PhoneFrame src="assets/screen-homekit.jpg" alt="HomeKit configuration" />
            </div>
          </div>

          {/* Fine Tune — full */}
          <div className="feature span-12" style={{flexDirection: 'row', alignItems: 'center', gap: 40}}>
            <div style={{flex: 1.2, minWidth: 0}}>
              <div className="feature-eyebrow">
                <span className="eyebrow" style={{color: 'var(--violet)'}}>⑤ Fine Tune</span>
              </div>
              <h3>Tune it<br/>to your wrist</h3>
              <p>
                Everyone casts a little differently. Four sliders — motion sensitivity, gesture speed,
                settle time, and confidence threshold — adapt the model to your style. Settings sync
                instantly over WatchConnectivity.
              </p>
              <ul style={{listStyle: 'none', padding: 0, color: 'var(--ink-dim)', fontSize: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 16, maxWidth: 460}}>
                <li>✦ Motion sensitivity</li>
                <li>✦ Gesture speed</li>
                <li>✦ Settle time</li>
                <li>✦ Confidence threshold</li>
                <li>✦ Cooldown timing</li>
                <li>✦ Reset to defaults</li>
              </ul>
            </div>
            <div className="feature-shot" style={{flex: 1, padding: 0}}>
              <PhoneFrame src="assets/screen-finetune.jpg" alt="Fine Tune settings" />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- duelling demo ---------- */
function DuelDemo() {
  const [you, setYou] = useState(100);
  const [opp, setOpp] = useState(100);
  const [log, setLog] = useState([]);
  const [winner, setWinner] = useState(null);
  const intervalRef = useRef(null);

  const spellsForDuel = (window.SPELLS || []).filter(s => !s.coming);

  const cast = (who) => {
    const s = spellsForDuel[Math.floor(Math.random() * spellsForDuel.length)];
    const dmg = 8 + Math.floor(Math.random() * 14);
    setLog(l => [{ who, spell: s, dmg, t: Date.now() + Math.random() }, ...l].slice(0, 6));
    if (who === "you") setOpp(v => Math.max(0, v - dmg));
    else setYou(v => Math.max(0, v - dmg));
  };

  useEffect(() => {
    if (winner) return;
    if (you <= 0) { setWinner("Tenebris"); return; }
    if (opp <= 0) { setWinner("You"); return; }
  }, [you, opp, winner]);

  const reset = () => {
    setYou(100); setOpp(100); setLog([]); setWinner(null);
    if (intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; }
  };

  // Opponent auto-casts every 2-3.5s while alive
  useEffect(() => {
    if (winner) return;
    const tick = () => {
      if (!winner && opp > 0 && you > 0) cast("opp");
    };
    intervalRef.current = setTimeout(tick, 1800 + Math.random() * 1800);
    return () => clearTimeout(intervalRef.current);
  }, [log, winner]);

  return (
    <>
      <div className="duel-arena">
        <div className="wizard">
          <div className="wizard-portrait">✦</div>
          <div className="wizard-name">You</div>
          <div className="wizard-hp">HP {you}/100</div>
          <div className="hp-bar"><span style={{width: you + "%"}} /></div>
        </div>
        <div className="vs">VS</div>
        <div className="wizard opp">
          <div className="wizard-portrait">☾</div>
          <div className="wizard-name">Tenebris</div>
          <div className="wizard-hp">HP {opp}/100</div>
          <div className="hp-bar"><span style={{width: opp + "%"}} /></div>
        </div>
      </div>

      <div className="duel-cta">
        {!winner ? (
          <>
            <button className="btn btn-primary" onClick={() => cast("you")}>
              ✦ Cast a Spell
            </button>
            <button className="btn btn-ghost" onClick={reset}>Reset</button>
          </>
        ) : (
          <>
            <button className="btn btn-primary" onClick={reset}>
              {winner === "You" ? "🏆 Victory — duel again" : "💀 Defeated — duel again"}
            </button>
          </>
        )}
      </div>

      {log.length > 0 && (
        <div className="spell-log">
          {log.map(l => (
            <div key={l.t} className={"log-row " + l.who}>
              <span style={{color: l.who === 'you' ? 'var(--gold)' : 'var(--violet)', fontSize: 11, letterSpacing: '0.2em', fontFamily: 'var(--font-display)', textTransform: 'uppercase'}}>
                {l.who === 'you' ? 'You' : 'Tenebris'}
              </span>
              <span style={{color: 'var(--ink-faint)'}}>cast</span>
              <span className="log-spell">{l.spell.name}</span>
              <span className="log-dmg">−{l.dmg} HP</span>
            </div>
          ))}
        </div>
      )}
    </>
  );
}

function Duelling() {
  return (
    <section className="block duel" id="duel">
      <div className="wrap">
        <div className="duel-head">
          <span className="badge badge-new" style={{marginBottom: 18}}>✦ New in v2</span>
          <h2 className="section-title">Duel a friend.<br/><span style={{fontFamily: 'var(--font-serif)', fontStyle: 'italic', textTransform: 'none', color: 'var(--violet)'}}>wand to wand.</span></h2>
          <p className="lede" style={{margin: '24px auto 0'}}>
            Connect over multipeer — no servers, no accounts, no Wi-Fi needed.
            Cast spells against each other in real time. Last wizard standing wins.
          </p>
        </div>

        <DuelDemo />

        <div style={{textAlign: 'center', marginTop: 40, color: 'var(--ink-faint)', fontSize: 13}}>
          ↑ Mock duel — in the real app, every cast comes from your wrist motion.
        </div>
      </div>
    </section>
  );
}

/* ---------- watch standalone ---------- */
function WatchStandalone() {
  return (
    <section className="block" id="watch">
      <div className="wrap">
        <div className="watch-row">
          <div>
            <span className="eyebrow">⌚ Watch-first</span>
            <h2 className="section-title" style={{marginTop: 14}}>iPhone<br/>optional.</h2>
            <p className="lede" style={{marginTop: 20}}>
              Spellbook runs entirely on the Apple Watch. Leave your phone behind —
              cast, detect, and trigger HomeKit straight from your wrist.
            </p>
            <ul style={{listStyle: 'none', padding: 0, marginTop: 24, display: 'flex', flexDirection: 'column', gap: 12, color: 'var(--ink-dim)'}}>
              <li>● Standalone watchOS app — no phone required</li>
              <li>● On-device ML — your motion never leaves the watch</li>
              <li>● Optional haptics + custom sounds per spell</li>
              <li>● Compatible with Apple Watch Series 4 and later</li>
            </ul>
            <div style={{
              marginTop: 28,
              padding: '14px 18px',
              border: '1px solid rgba(255,77,87,0.3)',
              background: 'rgba(255,77,87,0.06)',
              borderRadius: 12,
              color: 'var(--ink-dim)',
              fontSize: 13,
              maxWidth: 440,
            }}>
              <strong style={{color: '#ff8a8a'}}>One caveat:</strong> training is currently left-hand only.
              Right-hand support is in progress.
            </div>
          </div>
          <div className="watch-frame">
            <img src="assets/screen-watch.jpg" alt="Apple Watch running Spellbook" />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- pricing ---------- */
function Pricing() {
  return (
    <section className="block" id="pricing">
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow">Pricing</span>
          <h2 className="section-title">All ten spells.<br/>Free, forever.</h2>
          <p className="lede">
            Cast, learn, and rename every spell at no cost. Unlock <em>Actions</em>, <em>Sounds</em>,
            and <em>Duelling</em> with Premium — pick the tier that fits.
          </p>
        </div>

        <div className="pricing pricing-3">
          {/* Free */}
          <div className="price-card">
            <div className="price-tier">Free</div>
            <div className="price-cost">$0</div>
            <div className="price-tagline">All 10 spells. Forever. No account.</div>
            <ul className="price-list">
              <li><span className="check">✓</span> Cast all 10 spells from your wrist</li>
              <li><span className="check">✓</span> Rename any spell to your liking</li>
              <li><span className="check">✓</span> Motion tutorials in the spell book</li>
              <li><span className="check">✓</span> Cinematic on-screen reveals</li>
              <li><span className="check">✓</span> Fine-tune detection sensitivity</li>
              <li className="faded"><span className="check">○</span> HomeKit & device actions</li>
              <li className="faded"><span className="check">○</span> Custom spell sounds</li>
              <li className="faded"><span className="check">○</span> Duelling mode</li>
            </ul>
            <AppStoreBadge />
          </div>

          {/* Monthly */}
          <div className="price-card">
            <div className="price-tier">Premium · Monthly</div>
            <div className="price-cost"><span className="price-billing">Monthly<small>billed each month</small></span></div>
            <div className="price-tagline">Dip your toe in. Cancel anytime.</div>
            <ul className="price-list">
              <li><span className="check">✓</span> Everything in Free</li>
              <li><span className="check">✓</span> HomeKit actions — lights, scenes, accessories</li>
              <li><span className="check">✓</span> Custom sounds per spell</li>
              <li><span className="check">✓</span> Duelling mode over multipeer</li>
              <li><span className="check">✓</span> Attunement — twist to dim & color-shift</li>
              <li><span className="check">✓</span> Haptic feedback</li>
            </ul>
            <a href="#" className="btn btn-ghost" style={{width: '100%', justifyContent: 'center'}}>
              Subscribe in the App
            </a>
            <div className="price-fineprint">Renews monthly. Cancel anytime.</div>
          </div>

          {/* Yearly */}
          <div className="price-card premium">
            <span className="price-flag">Best value</span>
            <div className="price-tier">✦ Premium · Yearly</div>
            <div className="price-cost"><span className="price-billing">Yearly<small>cheaper over time</small></span></div>
            <div className="price-tagline">Cheaper than monthly over the long run.</div>
            <ul className="price-list">
              <li><span className="check">✓</span> Everything in monthly</li>
              <li><span className="check">✓</span> Save vs. paying monthly</li>
              <li><span className="check">✓</span> All future spells included</li>
              <li><span className="check">✓</span> Priority support</li>
            </ul>
            <a href="#" className="btn btn-primary" style={{width: '100%', justifyContent: 'center'}}>
              Subscribe Yearly
            </a>
            <div className="price-fineprint">Renews yearly. Cancel anytime.</div>
          </div>

          {/* Lifetime */}
          <div className="price-card lifetime">
            <span className="price-flag flag-violet">Pay once</span>
            <div className="price-tier">Premium · Lifetime</div>
            <div className="price-cost"><span className="price-billing">Lifetime<small>one payment, forever</small></span></div>
            <div className="price-tagline">Unlock forever. No subscription, ever.</div>
            <ul className="price-list">
              <li><span className="check">✓</span> Everything in Premium</li>
              <li><span className="check">✓</span> One payment — unlocked forever</li>
              <li><span className="check">✓</span> All future spells & integrations included</li>
              <li><span className="check">✓</span> No renewals, no auto-billing</li>
            </ul>
            <a href="#" className="btn btn-ghost" style={{width: '100%', justifyContent: 'center'}}>
              Unlock Lifetime
            </a>
            <div className="price-fineprint">One-time purchase. Restore on any device.</div>
          </div>
        </div>

        <p style={{textAlign: 'center', color: 'var(--ink-faint)', fontSize: 13, marginTop: 32, maxWidth: 580, marginLeft: 'auto', marginRight: 'auto'}}>
          Prices set by Apple in your local currency and shown at checkout in the App Store. All three tiers unlock the same set of Premium features.
        </p>
      </div>
    </section>
  );
}

/* ---------- FAQ ---------- */
function FAQ() {
  const items = [
    { q: "Do I really need an Apple Watch?",
      a: "Yes — spell recognition is built on wrist motion. Without a Watch there is nothing to detect. iPhone is optional; the Watch runs as a standalone app." },
    { q: "Which watches are supported?",
      a: "Apple Watch Series 4 and later, running watchOS 9 or newer. If you're using iPhone alongside, iOS 16+." },
    { q: "Does my motion data leave the device?",
      a: "Never. Detection runs entirely on-device, with no cloud processing and no account. We don't see your spells." },
    { q: "What if I wear my watch on my right hand?",
      a: "The current model is trained on left-hand motion. Right-hand support is in active development and will ship as a free update." },
    { q: "Can I rename the spells?",
      a: "Yes. Every spell can be renamed in the spell book. Many users replace the latin names with their favourites from a certain wizarding world." },
    { q: "How does Duelling work?",
      a: "Two devices connect over Apple's MultipeerConnectivity framework — no Wi-Fi, no internet, no accounts needed. You cast in real time; the winner is whoever lasts longest. Requires Premium on both devices." },
    { q: "Is Premium a subscription?",
      a: "No. Premium is a single one-time unlock. All future spells and integrations are included." },
    { q: "What spells are coming next?",
      a: "Exanima (a final-strike spell) and Mineura (a shrink spell, opposite of Amplora) are next. Beyond that: more spells, more integrations, and right-hand support." },
  ];
  const [open, setOpen] = useState(0);
  return (
    <section className="block" id="faq">
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow">Questions</span>
          <h2 className="section-title">Frequently<br/>asked.</h2>
        </div>
        <div className="faq">
          {items.map((it, i) => (
            <div key={i} className={"faq-item " + (open === i ? "open" : "")}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{it.q}</span>
                <svg className="faq-toggle" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                  <line x1="12" y1="5" x2="12" y2="19" />
                  <line x1="5" y1="12" x2="19" y2="12" />
                </svg>
              </button>
              <div className="faq-a">{it.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Testimonials ---------- */
function Testimonials() {
  const quotes = [
    { text: "I keep flicking my wrist to turn the lamp on. My kids think I'm a wizard. I haven't corrected them.",
      name: "Maeve K.", meta: "App Store · 5★", initials: "MK", stars: "★★★★★" },
    { text: "The motion detection is uncanny. I half-expected it to be janky — it isn't. Lucernas just works.",
      name: "Theo R.", meta: "Reddit · r/AppleWatch", initials: "TR", stars: "★★★★★" },
    { text: "Duelling with my partner across the kitchen is now the best 30 seconds of my evening.",
      name: "Priya S.", meta: "App Store · 5★", initials: "PS", stars: "★★★★★" },
  ];
  return (
    <section className="block" id="loved">
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow">From the cauldron</span>
          <h2 className="section-title">Loved by<br/>apprentices.</h2>
        </div>
        <div className="testimonials">
          {quotes.map((q, i) => (
            <div key={i} className="quote">
              <p className="quote-text">{q.text}</p>
              <div className="quote-attr">
                <div className="quote-avatar">{q.initials}</div>
                <div className="quote-meta">
                  <strong>{q.name}</strong>
                  {q.meta}
                </div>
                <div className="stars-row">{q.stars}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Final CTA + Footer ---------- */
function FinalCTA() {
  return (
    <section className="final-cta">
      <div className="wrap">
        <h2>Your <em>wand</em><br/>awaits.</h2>
        <p className="lede" style={{margin: '0 auto 36px'}}>Free on the App Store. Premium unlocked when you're ready.</p>
        <AppStoreBadge />
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <div className="brand" style={{marginBottom: 14}}>
              <svg className="brand-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M14 4l-1.2 4-4 1.2 4 1.2L14 14.6l1.2-4.2 4-1.2-4-1.2zM6 14l-.6 2-2 .6 2 .6.6 2 .6-2 2-.6-2-.6zM18.5 17l-.4 1.3-1.3.4 1.3.4.4 1.3.4-1.3 1.3-.4-1.3-.4z"/>
              </svg>
              SPELLBOOK
            </div>
            <p style={{maxWidth: 320, lineHeight: 1.5}}>
              A wand for your wrist. Built for Apple Watch.
              All processing on-device. No tracking, no accounts.
            </p>
          </div>
          <div>
            <h4>App</h4>
            <ul>
              <li><a href="#spells">Spells</a></li>
              <li><a href="#features">Features</a></li>
              <li><a href="#duel">Duelling</a></li>
              <li><a href="#pricing">Pricing</a></li>
            </ul>
          </div>
          <div>
            <h4>Support</h4>
            <ul>
              <li><a href="#faq">FAQ</a></li>
              <li><a href="mailto:hello@spellbook.app">Contact</a></li>
              <li><a href="#">Press kit</a></li>
            </ul>
          </div>
          <div>
            <h4>Legal</h4>
            <ul>
              <li><a href="#">Privacy</a></li>
              <li><a href="https://www.apple.com/legal/internet-services/itunes/dev/stdeula/">EULA</a></li>
              <li><a href="#">Terms</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Spellbook. Made with ✦ for muggles with wristwear.</span>
          <span>v2.0 · Duelling</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------- ROOT ---------- */
function App() {
  // Tweaks
  const TWEAKS = window.useTweaks ? window.useTweaks(/*EDITMODE-BEGIN*/{
    "accent": "gold",
    "stars": "atmospheric"
  }/*EDITMODE-END*/) : [{accent: 'gold', stars: 'atmospheric'}, () => {}];
  const [t, setTweak] = TWEAKS;

  // Apply accent dynamically
  useEffect(() => {
    const root = document.documentElement;
    const palettes = {
      gold:   { primary: '#FFD43A', deep: '#c89a14', soft: '#ffe89a' },
      violet: { primary: '#b48aff', deep: '#6a3acc', soft: '#dccdff' },
      emerald:{ primary: '#5ee3a9', deep: '#1e8a5b', soft: '#a5f0cf' },
      rose:   { primary: '#ff8aa9', deep: '#b03f5e', soft: '#ffc7d4' },
    };
    const p = palettes[t.accent] || palettes.gold;
    root.style.setProperty('--gold', p.primary);
    root.style.setProperty('--gold-deep', p.deep);
    root.style.setProperty('--gold-soft', p.soft);
  }, [t.accent]);

  // Stars opacity
  useEffect(() => {
    const v = { subtle: 0.25, atmospheric: 0.7, intense: 1 }[t.stars] || 0.7;
    document.documentElement.style.setProperty('--starOpacity', v);
  }, [t.stars]);

  return (
    <>
      <Stars />
      <Nav />
      <Hero />
      <hr className="divider"/>
      <SpellsGallery />
      <hr className="divider"/>
      <Features />
      <Duelling />
      <WatchStandalone />
      <hr className="divider"/>
      <Pricing />
      <Testimonials />
      <FAQ />
      <FinalCTA />
      <Footer />

      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks">
          <window.TweakSection title="Accent color">
            <window.TweakRadio
              label="Accent"
              value={t.accent}
              options={[
                {value: 'gold', label: 'Gold'},
                {value: 'violet', label: 'Violet'},
                {value: 'emerald', label: 'Emerald'},
                {value: 'rose', label: 'Rose'},
              ]}
              onChange={v => setTweak('accent', v)}
            />
          </window.TweakSection>
          <window.TweakSection title="Background">
            <window.TweakRadio
              label="Star intensity"
              value={t.stars}
              options={[
                {value: 'subtle', label: 'Subtle'},
                {value: 'atmospheric', label: 'Atmospheric'},
                {value: 'intense', label: 'Intense'},
              ]}
              onChange={v => setTweak('stars', v)}
            />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </>
  );
}

/* ---------- starfield ---------- */
function Stars() {
  const ref = useRef(null);
  useEffect(() => {
    const c = ref.current;
    if (!c) return;
    const dpr = window.devicePixelRatio || 1;
    const resize = () => {
      c.width = window.innerWidth * dpr;
      c.height = window.innerHeight * dpr;
    };
    resize();
    window.addEventListener('resize', resize);
    const ctx = c.getContext('2d');
    // Pre-generate stars
    const n = 220;
    const stars = Array.from({length: n}, () => ({
      x: Math.random(),
      y: Math.random(),
      r: Math.random() * 1.2 + 0.2,
      tw: Math.random() * Math.PI * 2,
      ts: 0.6 + Math.random() * 1.4,
      hue: Math.random() < 0.15 ? 'gold' : 'white',
    }));
    let raf;
    const t0 = performance.now();
    const draw = () => {
      const t = (performance.now() - t0) / 1000;
      ctx.clearRect(0, 0, c.width, c.height);
      for (const s of stars) {
        const a = 0.4 + 0.6 * (0.5 + 0.5 * Math.sin(s.tw + t * s.ts));
        ctx.fillStyle = s.hue === 'gold'
          ? `rgba(255, 220, 120, ${a * 0.9})`
          : `rgba(220, 220, 255, ${a * 0.7})`;
        ctx.beginPath();
        ctx.arc(s.x * c.width, s.y * c.height, s.r * dpr, 0, Math.PI * 2);
        ctx.fill();
      }
      raf = requestAnimationFrame(draw);
    };
    draw();
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); };
  }, []);
  return <canvas ref={ref} className="stars" />;
}

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