/* global React */
const { useState: useStateV3, useEffect: useEffectV3, useMemo: useMemoV3 } = React;
const { Ico, Star, AppStoreBadge, PlayStoreBadge } = window;

const DEMO_NAMES = ["Lily", "Nevo", "Emma", "Aviv", "Noah", "Maya", "Ethan", "Aria", "Liam", "Yael"];

// =============== V3: Live Personalization Demo ===============
const V3 = () => {
  const [name, setName] = useStateV3("");
  const [age, setAge] = useStateV3("3-4");
  const [theme, setTheme] = useStateV3("bedtime");
  const [generating, setGenerating] = useStateV3(false);
  const [storyKey, setStoryKey] = useStateV3(0);
  const [demoIdx, setDemoIdx] = useStateV3(0);
  const [typed, setTyped] = useStateV3("");      // typewriter display string
  const [userTyped, setUserTyped] = useStateV3(false);

  // Typewriter: type → pause → erase → next name
  useEffectV3(() => {
    if (userTyped) return;
    const target = DEMO_NAMES[demoIdx];
    let frame;
    let chars = typed.length;
    let phase = chars < target.length ? "typing" : "pausing";
    let pauseTicks = 0;

    const tick = () => {
      if (phase === "typing") {
        chars++;
        setTyped(target.slice(0, chars));
        if (chars === target.length) { phase = "pausing"; pauseTicks = 0; }
        frame = setTimeout(tick, 90);
      } else if (phase === "pausing") {
        pauseTicks++;
        if (pauseTicks >= 14) phase = "erasing";
        frame = setTimeout(tick, 100);
      } else {
        chars--;
        setTyped(target.slice(0, chars));
        if (chars === 0) {
          setDemoIdx(i => (i + 1) % DEMO_NAMES.length);
          return;
        }
        frame = setTimeout(tick, 55);
      }
    };
    frame = setTimeout(tick, 120);
    return () => clearTimeout(frame);
  }, [demoIdx, userTyped]);

  // When demoIdx changes, reset typed string
  useEffectV3(() => {
    if (!userTyped) setTyped("");
  }, [demoIdx]);

  const activeName = userTyped ? name.trim() : typed;
  const safeName = (userTyped ? name.trim() : DEMO_NAMES[demoIdx]) || "your child";
  const displayName = activeName;

  // Check localStorage for signed-in user (set by account page)
  const [navUser] = useStateV3(() => {
    try { return JSON.parse(localStorage.getItem("talio_user")); } catch { return null; }
  });

  const story = useMemoV3(() => buildStory(safeName, age, theme), [safeName, age, theme, storyKey]);

  const regenerate = () => {
    setGenerating(true);
    setTimeout(() => {
      setStoryKey(k => k + 1);
      setGenerating(false);
    }, 900);
  };

  return (
    <div className="v3">
      <div className="sky-bg" />
      <img className="v3-prop star-a" src="img/star_a.png" alt="" />
      <img className="v3-prop star-b" src="img/star_b.png" alt="" />
      <img className="v3-prop star-c" src="img/star_c.png" alt="" />
      <img className="v3-prop star-d" src="img/star_a.png" alt="" />
      <img className="v3-prop cloud-a" src="img/cloud_a.png" alt="" />
      <img className="v3-prop cloud-b" src="img/cloud_b.png" alt="" />
      <img className="v3-prop cloud-c" src="img/cloud_c.png" alt="" />

      <nav className="v3-nav">
        <div className="talio-mark">
          <img src="img/talio_logo.png" alt="Talio"/>
        </div>
        <div className="v3-nav-right">
          {navUser ? (
            <a className="v3-nav-account" href="/account">
              <span className="v3-nav-account-dot">
                {(navUser.displayName || navUser.email || "?")[0].toUpperCase()}
              </span>
              My Account
            </a>
          ) : (
            <a className="btn-ghost" href="/account">Sign in</a>
          )}
        </div>
      </nav>

      <section className="v3-hero">
        <div className="v3-left">
          <div className="v3-pill">
            <div className="dot"><Star size={12} color="white"/></div>
            Personalized in under a minute
          </div>
          <h1 className="v3-h1">
            Tonight's story<br/>
            stars <span className="name-slot">
              {displayName || <span style={{opacity:.25}}>_</span>}
              {!userTyped && <span className="cursor">|</span>}
            </span>.
          </h1>
          <p className="v3-sub">
            Type a name, pick what tonight is about, and watch Talio weave a
            story made just for your little one. Try it right here — no signup.
          </p>

          <div className="v3-try-card">
            <div className="v3-try-label">
              Who's the story for?
              <span className="thought-tag">No account needed ✨</span>
            </div>
            <div className="v3-input-row">
              <div className="input-pill">
                <Star size={16} color="#f5c43a"/>
                <input
                  value={name}
                  placeholder={DEMO_NAMES[demoIdx]}
                  onChange={e => { setName(e.target.value.slice(0, 14)); setUserTyped(true); }}
                  placeholder="Child's name"
                />
              </div>
            </div>

            <div className="v3-try-label">Age</div>
            <div className="v3-age-row">
              {["2-3","3-4","4-5","5-6","7+"].map((a, i) => (
                <button
                  key={a}
                  className={`v3-age age-${i+1} ${age===a?"active":""}`}
                  onClick={() => setAge(a)}
                >{a}</button>
              ))}
            </div>

            <div className="v3-theme-label">Tonight's theme</div>
            <div className="v3-theme-row">
              <ThemeBtn id="bedtime" cur={theme} onClick={setTheme} cls="t-violet" icon={<Ico.Moon/>}>Bedtime fears</ThemeBtn>
              <ThemeBtn id="friends" cur={theme} onClick={setTheme} cls="t-leaf" icon={<Ico.Friends/>}>Making friends</ThemeBtn>
              <ThemeBtn id="confidence" cur={theme} onClick={setTheme} cls="t-tang" icon={<Ico.Confidence/>}>Confidence</ThemeBtn>
              <ThemeBtn id="sibling" cur={theme} onClick={setTheme} cls="t-coral" icon={<Ico.Sibling/>}>New sibling</ThemeBtn>
              <ThemeBtn id="sharing" cur={theme} onClick={setTheme} cls="t-sky" icon={<Ico.Share/>}>Sharing</ThemeBtn>
              <ThemeBtn id="fun" cur={theme} onClick={setTheme} cls="t-gold" icon={<Ico.Magic/>}>Just fun</ThemeBtn>
            </div>

            <div className="v3-generate">
              <div className="v3-generate-meta">Ready in ~40 seconds</div>
              <button className="btn-pill" onClick={regenerate}>
                <Ico.Magic/> Regenerate
              </button>
            </div>
          </div>

          <div style={{display:"flex", gap:12, flexWrap:"wrap"}}>
            <AppStoreBadge/>
            <PlayStoreBadge/>
          </div>
        </div>

        {/* Preview */}
        <div className="v3-right">
          <div className="v3-preview-wrap">
            <div className="v3-thought thought tb-left">Ooh — let me<br/>read it aloud!</div>
            <div className="v3-phone">
              <div className="v3-phone-screen">
                <div className="v3-status">
                  <span>9:41</span>
                  <div className="v3-status-icons">
                    <span>5G</span><span>●●●</span>
                  </div>
                </div>

                {generating && (
                  <div className="v3-phone-generating" key={storyKey}>
                    <div className="sparkle-text">
                      <Ico.Magic/> Writing your story…
                    </div>
                  </div>
                )}

                <div className="v3-story-card" key={storyKey}>
                  <div className="v3-story-illus">
                    <img src={story.illus} alt="" />
                    <div className="pg-dots">
                      <span className="on"/><span/><span/><span/><span/>
                    </div>
                  </div>
                  <div className="v3-story-title">{story.title}</div>
                  <div
                    className="v3-story-body"
                    dangerouslySetInnerHTML={{__html: story.body}}
                  />
                  <div className="v3-play-bar">
                    <div className="v3-play-btn">
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="white"><path d="M6 4l14 8-14 8V4Z"/></svg>
                    </div>
                    <div className="v3-progress"><span/></div>
                    <div style={{fontSize:11, fontWeight:700, color:"var(--ink-3)"}}>0:42</div>
                  </div>
                </div>
              </div>
            </div>
            <img className="v3-owl-peek" src="img/owl_on_branch.png" alt="" />
          </div>
        </div>
      </section>

      {/* Stats strip */}
      <section className="v3-strip">
        <div className="v3-strip-inner">
          <Stat n="12k+" label="Bedtimes made easier" />
          <Stat n="4.9" label="App Store rating" italic />
          <Stat n="40s" label="Average story time" />
          <Stat n="2–7" label="Designed for ages" />
        </div>
      </section>

      {/* Themes */}
      <section className="v3-themes">
        <div className="v3-themes-inner">
          <div className="v3-themes-head">
            <div className="v1-eyebrow">Gentle help for big feelings</div>
            <h2>Stories for the moments that <span className="italic">matter.</span></h2>
          </div>
          <div className="v3-theme-grid">
            <ThemeCard cls="c1" icon={<Ico.Moon/>} title="Bedtime fears" body="Shadows on the wall, the dark, monsters under the bed — met with gentle courage."/>
            <ThemeCard cls="c2" icon={<Ico.Friends/>} title="Making friends" body="First day of school, a new playground, how to say hello and ask to play."/>
            <ThemeCard cls="c3" icon={<Ico.Confidence/>} title="Building confidence" body="Trying, falling, trying again. Stories that celebrate every brave step."/>
            <ThemeCard cls="c4" icon={<Ico.Sibling/>} title="New sibling" body="Big brother, big sister. Room for more love, written just for them."/>
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section className="v3-faq">
        <div className="v3-faq-inner">
          <div className="v3-faq-head">
            <div className="v1-eyebrow">Parent questions</div>
            <h2 className="v3-h1" style={{fontSize:"clamp(32px, 3.6vw, 44px)"}}>The small print.</h2>
          </div>
          <details className="v3-q" open>
            <summary>Is it safe for young children?</summary>
            <p>Every story passes through child-safety filters and is reviewed against guidance from child psychologists. No scary surprises, no ads, no third-party tracking. Ever.</p>
          </details>
          <details className="v3-q">
            <summary>What devices does Talio work on?</summary>
            <p>Talio is available on iPhone, iPad, Android, and on the web — any device you use for bedtime. Stories sync across devices so you can start on the couch and finish under the covers.</p>
          </details>
          <details className="v3-q">
            <summary>How much does it cost?</summary>
            <p>Your first three stories are free. After that, Talio is $6.99/month or $59/year for unlimited stories for up to four children. Cancel anytime.</p>
          </details>
          <details className="v3-q">
            <summary>Can more than one child share an account?</summary>
            <p>Yes — add up to four little ones with their own names, ages, and saved stories. Each child gets their own cozy library.</p>
          </details>
        </div>
      </section>

      {/* CTA */}
      <section className="v3-cta">
        <h2>One story. <span className="italic">Every night.</span><br/>Made just for your little one.</h2>
        <p>Free to try. Takes 30 seconds to set up.</p>
        <div className="btn-row">
          <AppStoreBadge/>
          <PlayStoreBadge/>
        </div>
      </section>

      <footer className="v3-foot">
        <div className="talio-mark">
          <img src="img/talio_logo.png" alt="Talio" style={{height:44, filter:"brightness(0) invert(1) opacity(.85)"}}/>
        </div>
        <div className="v3-foot-links">
          <a href="#">Privacy</a>
          <a href="#">Parents' guide</a>
          <a href="#">Support</a>
          <a href="/dashboard/">Dashboard</a>
        </div>
        <div>talio.fun · © 2026</div>
      </footer>
    </div>
  );
};

const ThemeBtn = ({id, cur, onClick, cls, icon, children}) => (
  <button
    className={`v3-theme ${cls} ${cur===id?"active":""}`}
    onClick={() => onClick(id)}
  >{icon}{children}</button>
);
const ThemeCard = ({cls, icon, title, body}) => (
  <div className={`v3-theme-card ${cls}`}>
    <div className="badge">{icon}</div>
    <h3>{title}</h3>
    <p>{body}</p>
  </div>
);
const Stat = ({n, label, italic}) => (
  <div className="v3-stat">
    <div className="n">{italic ? <span className="italic">{n}</span> : n}</div>
    <div className="l">{label}</div>
  </div>
);

// ===== Story templates =====
function buildStory(name, age, theme) {
  const T = {
    bedtime: {
      title: `The Night ${name} Met the Moon`,
      body: `When the room went dark, <em>${name}</em> wasn't so sure. But the little moon outside the window winked — and whispered, <em>"I'll keep watch."</em>`,
      illus: "img/setting_enchanted_forest.png",
    },
    friends: {
      title: `${name} and the Playground Hello`,
      body: `The playground was big and loud and a little scary. Then <em>${name}</em> spotted a kind rabbit with a blue scarf, who waved and said, <em>"Want to play?"</em>`,
      illus: "img/comp_fluffy_bunny.png",
    },
    confidence: {
      title: `${name}'s Brave Big Step`,
      body: `The ladder looked <em>very</em> tall. But <em>${name}</em> remembered: small steps, one at a time. Up, up, up — and there was the whole sky, cheering.`,
      illus: "img/char_brave_knight.png",
    },
    sibling: {
      title: `Room for Two, Said ${name}`,
      body: `A new little baby was coming soon. <em>${name}</em> was worried there wouldn't be enough love. Then Grandma smiled: <em>"Love grows — like stars at night."</em>`,
      illus: "img/char_kind_princess.png",
    },
    sharing: {
      title: `${name} and the Dragon's Cookie`,
      body: `There was only <em>one</em> cookie left. <em>${name}</em> looked at the tiny dragon, and the tiny dragon looked back. Then they broke it in half — and it tasted twice as good.`,
      illus: "img/comp_baby_dragon.png",
    },
    fun: {
      title: `${name} and the Starlight Express`,
      body: `The train's whistle tooted <em>wheee!</em> and away they went — <em>${name}</em> on a sparkling train made of stars, straight up into a sky full of jellybean planets.`,
      illus: "img/mood_magical_quest.png",
    },
  };
  return T[theme] || T.bedtime;
}

window.V3 = V3;
