/* ===== AI Ki Baat — components (from the original design) ===== */
const { useState, useEffect, useRef } = React;

/* --- language context --- */
const LangCtx = React.createContext(["en", () => {}]);
const useLang = () => React.useContext(LangCtx);
function useTr() {
  const [lang] = useLang();
  const T = (v) => (v && typeof v === 'object' && !Array.isArray(v) && ('en' in v || 'hi' in v)) ? (v[lang] ?? v.en) : v;
  return [lang, T];
}

/* --- YouTube helpers: accept a full link OR a bare 11-char video id --- */
function ytId(s) {
  if (!s) return "";
  s = String(s).trim();
  if (/^[A-Za-z0-9_-]{11}$/.test(s)) return s;
  const m = s.match(/(?:youtu\.be\/|[?&]v=|\/embed\/|\/shorts\/|\/live\/|\/v\/)([A-Za-z0-9_-]{11})/);
  return m ? m[1] : s;
}
function ytThumb(id) { return `https://img.youtube.com/vi/${id}/maxresdefault.jpg`; }
function ytThumbFallback(e, id) {
  // maxres isn't generated for every video — fall back to the always-present hqdefault.
  if (!e.target.dataset.fb) { e.target.dataset.fb = "1"; e.target.src = `https://img.youtube.com/vi/${id}/hqdefault.jpg`; }
}

/* --- tiny icon set (functional UI glyphs only) --- */
const Icon = ({ n, s = 20 }) => {
  const p = { width: s, height: s, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor",
    strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" };
  const paths = {
    play:  <polygon points="6 4 20 12 6 20 6 4" fill="currentColor" stroke="none" />,
    arrow: <g><line x1="5" y1="12" x2="19" y2="12" /><polyline points="13 6 19 12 13 18" /></g>,
    bell:  <g><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" /><path d="M13.7 21a2 2 0 0 1-3.4 0" /></g>,
    mail:  <g><rect x="3" y="5" width="18" height="14" rx="2" /><polyline points="3 7 12 13 21 7" /></g>,
    headphone: <g><path d="M3 14v-2a9 9 0 0 1 18 0v2" /><rect x="3" y="14" width="4" height="6" rx="1.5" /><rect x="17" y="14" width="4" height="6" rx="1.5" /></g>,
    spark: <g><path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M18 6l-2.5 2.5M8.5 15.5 6 18" /></g>,
    clock: <g><circle cx="12" cy="12" r="9" /><polyline points="12 7 12 12 15 14" /></g>,
    eye:   <g><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" /><circle cx="12" cy="12" r="3" /></g>,
    check: <polyline points="4 12 10 18 20 6" />,
    x:     <g><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></g>,
    menu:  <g><line x1="4" y1="7" x2="20" y2="7" /><line x1="4" y1="12" x2="20" y2="12" /><line x1="4" y1="17" x2="20" y2="17" /></g>,
    globe: <g><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3c2.5 2.7 2.5 15.3 0 18M12 3c-2.5 2.7-2.5 15.3 0 18" /></g>,
    mic:   <g><rect x="9" y="3" width="6" height="11" rx="3" /><path d="M5 11a7 7 0 0 0 14 0M12 18v3" /></g>
  };
  return <svg {...p}>{paths[n]}</svg>;
};

/* --- striped placeholder for thumbnails --- */
const Placeholder = ({ label, color }) => (
  <div className="ph" style={{ "--c1": color }}>
    <span className="phlabel">{label}</span>
  </div>
);

/* --- scroll reveal wrapper --- */
const Reveal = ({ children, className = "", delay = 0, tag = "div", ...rest }) => {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { el.classList.add("in"); io.disconnect(); }
    }, { threshold: .12 });
    io.observe(el); return () => io.disconnect();
  }, []);
  const Tag = tag;
  return <Tag ref={ref} className={"reveal " + className} style={{ transitionDelay: delay + "ms" }} {...rest}>{children}</Tag>;
};

/* --- language toggle --- */
function LangToggle() {
  const [lang, setLang] = useLang();
  return (
    <div className="lang-toggle" role="group" aria-label="Language">
      <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
      <button className={lang === "hi" ? "on" : ""} onClick={() => setLang("hi")}>Hinglish</button>
    </div>
  );
}

/* --- NAV --- */
function Nav() {
  const [open, setOpen] = useState(false);
  const [lang, T] = useTr();
  const U = AKB.ui;
  const links = [["episodes", U.nav_episodes], ["quiz", U.nav_quiz], ["blog", U.nav_blog], ["about", U.nav_host]];
  return (
    <nav className="nav">
      <div className="wrap nav-inner">
        <a href="#top" className="brand">
          <span className="mic"><Icon n="mic" s={20} /></span>
          <span><span className="ai">AI</span> <span className="ki">की बात</span></span>
        </a>
        <div className="nav-links">
          {links.map(([h, l]) => <a key={h} href={"#" + h}>{T(l)}</a>)}
        </div>
        <div className="nav-cta">
          <LangToggle />
          <a href="#newsletter" className="btn btn-gold"><Icon n="bell" s={18} /> {T(U.nav_subscribe)}</a>
          <button className="nav-burger" onClick={() => setOpen(o => !o)} aria-label="menu"><Icon n={open ? "x" : "menu"} /></button>
        </div>
      </div>
    </nav>
  );
}

/* --- HERO --- */
function Hero({ onPlay }) {
  const [lang, T] = useTr();
  const U = AKB.ui; const L = AKB.latest;
  const HS = AKB.heroStats || {};
  const sparks = [[18, 120], [42, 200], [70, 90], [86, 170], [30, 260], [60, 300]];
  const vid = ytId(L.yt);
  const hasVid = /^[A-Za-z0-9_-]{11}$/.test(vid);
  const coverSrc = hasVid
    ? ytThumb(vid)
    : ((window.__resources && window.__resources.heroCover) || "assets/hero-cover.webp");
  return (
    <header className="hero" id="top">
      <div className="sky"></div>
      <div className="sun"></div>
      <div className="cloud c1"></div><div className="cloud c2"></div><div className="cloud c3"></div>
      {sparks.map(([l, t], i) => <span key={i} className="spark" style={{ left: l + "%", top: t + "px", animationDelay: (i * 0.7) + "s" }}></span>)}
      <Drone className="d1" /><Drone className="d2" />

      <div className="wrap hero-inner">
        <div className="hero-grid">
          <div className="hero-copy">
            <span className="hero-badge"><span className="dot"></span> {T(U.hero_badge)} • {T(L.date)}</span>
            <h1 className="hero-head"><span className="g">AI</span> {T(U.hero_head)}</h1>
            <p className="hero-sub-id">{T(U.hero_sub)}</p>
            <p className="hero-tag">{T(U.hero_tag)}</p>
            <div className="hero-actions">
              <button className="btn btn-gold" onClick={() => onPlay(vid, T(L.title))}><Icon n="play" s={18} /> {T(U.hero_btn)}</button>
              <a href="#episodes" className="btn btn-ghost">{T(U.hero_all)} <Icon n="arrow" s={18} /></a>
            </div>
            <div className="hero-meta">
              <div className="m"><b>{HS.eps}</b><span>{T(U.m_eps)}</span></div>
              <div className="m"><b>{HS.listeners}</b><span>{T(U.m_listeners)}</span></div>
              <div className="m"><b>{HS.rating}</b><span>{T(U.m_rating)}</span></div>
            </div>
          </div>

          <div className="hero-vis">
            <div className="cover-card">
              <div className="cover-art" onClick={() => onPlay(vid, T(L.title))}>
                <img src={coverSrc} onError={hasVid ? (e) => ytThumbFallback(e, vid) : undefined}
                  alt="AI Ki Baat — a podcast with Akshat Ratanpal" />
                <span className="play-fab"><Icon n="play" s={26} /></span>
              </div>
              <div className="cover-meta">
                <div className="ep">{L.epno} • {L.guest}</div>
                <h3>{T(L.title)}</h3>
                <div className="row">
                  <span><Icon n="clock" s={15} /> {L.len}</span>
                  <span><Icon n="eye" s={15} /> {L.views} views</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="cityband">
        <img src={(window.__resources && window.__resources.cityBand) || "assets/city-band.webp"} alt="AI city — robots and people living together" />
        <div className="ground"></div>
      </div>
    </header>
  );
}
const Drone = ({ className }) => (
  <div className={"drone " + className}>
    <span className="rotor l"></span><span className="rotor r"></span>
    <span className="arm l"></span><span className="arm r"></span>
    <span className="body"></span>
  </div>
);

/* --- LISTEN STRIP --- */
function ListenStrip() {
  const [lang, T] = useTr();
  return (
    <section className="listen" id="listen">
      <div className="wrap listen-inner">
        <span className="lbl"><Icon n="headphone" s={20} /> {T(AKB.ui.listen_lbl)}</span>
        <div className="platforms">
          {AKB.platforms.map(p => (
            <a key={p.name} className="plat" href={p.url}>
              <span style={{ width: 9, height: 9, borderRadius: 9, background: "var(--gold)", display: "inline-block" }}></span>{p.name}
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* --- VIDEO MODAL --- */
function VideoModal({ video, onClose }) {
  useEffect(() => {
    const k = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", k); return () => window.removeEventListener("keydown", k);
  }, []);
  if (!video) return null;
  return (
    <div className="modal" onClick={onClose}>
      <div className="box" onClick={e => e.stopPropagation()}>
        <button className="close" onClick={onClose} style={{ position: "absolute" }}><Icon n="x" s={18} /> Close</button>
        <div className="mframe">
          <iframe src={`https://www.youtube.com/embed/${ytId(video.yt)}?autoplay=1&rel=0`}
            title={video.title} allow="autoplay; encrypted-media; picture-in-picture" allowFullScreen></iframe>
        </div>
      </div>
    </div>
  );
}

/* --- EPISODES --- */
function Episodes({ onPlay }) {
  const [lang, T] = useTr(); const U = AKB.ui;
  const [cat, setCat] = useState("All");
  const list = cat === "All" ? AKB.episodes : AKB.episodes.filter(e => e.cat === cat);
  return (
    <section className="section-pad" id="episodes">
      <div className="wrap">
        <div className="sec-head">
          <div>
            <span className="eyebrow">{T(U.ep_eyebrow)}</span>
            <h2 className="sec-title">{T(U.ep_title)}</h2>
            <p className="sec-sub">{T(U.ep_sub)}</p>
          </div>
          <div className="filters">
            {AKB.cats.map(c => (
              <button key={c} className={"chip" + (c === cat ? " active" : "")} onClick={() => setCat(c)}>{c}</button>
            ))}
          </div>
        </div>
        <div className="ep-grid">
          {list.map((e, i) => {
            const vid = ytId(e.yt);
            const hasVid = /^[A-Za-z0-9_-]{11}$/.test(vid);
            return (
            <Reveal key={(e.yt || "") + i} className="ep-card" delay={(i % 3) * 70}>
              <div className="vframe" onClick={() => onPlay(vid, T(e.title))} style={{ aspectRatio: "16/9" }}>
                {hasVid
                  ? <img src={ytThumb(vid)} onError={(ev) => ytThumbFallback(ev, vid)} alt={T(e.title)} />
                  : <Placeholder label={`▶  ${e.cat} • ${T(U.ep_thumb)}`} color={e.c} />}
                <div className="play">
                  <span className="tag">{e.cat}</span>
                  <span className="pbtn"><Icon n="play" s={28} /></span>
                </div>
              </div>
              <div className="vmeta">
                <h3>{T(e.title)}</h3>
                <div className="row">
                  <span><Icon n="clock" s={15} /> {e.len}</span>
                  <span><Icon n="eye" s={15} /> {e.views}</span>
                </div>
              </div>
            </Reveal>
          );})}
        </div>
      </div>
    </section>
  );
}

/* --- QUIZ --- */
function Quiz() {
  const [lang, T] = useTr(); const U = AKB.ui;
  const Q = AKB.quiz;
  const [i, setI] = useState(0);
  const [picked, setPicked] = useState(null);
  const [score, setScore] = useState(0);
  const [done, setDone] = useState(false);

  const q = Q[i];
  const pct = Math.round(((done ? Q.length : i) / Q.length) * 100);
  const opts = T(q.opts);

  const choose = (idx) => { if (picked !== null) return; setPicked(idx); if (idx === q.a) setScore(s => s + 1); };
  const next = () => { if (i + 1 < Q.length) { setI(i + 1); setPicked(null); } else setDone(true); };
  const restart = () => { setI(0); setPicked(null); setScore(0); setDone(false); };

  const verdict = () => {
    const r = score / Q.length;
    if (r === 1) return [T(U.quiz_v1t), T(U.quiz_v1p)];
    if (r >= 0.6) return [T(U.quiz_v2t), T(U.quiz_v2p)];
    return [T(U.quiz_v3t), T(U.quiz_v3p)];
  };

  return (
    <section className="quiz-sec section-pad" id="quiz">
      <div className="wrap">
        <div style={{ textAlign: "center", marginBottom: 34 }}>
          <span className="eyebrow" style={{ justifyContent: "center" }}><Icon n="spark" s={16} /> {T(U.quiz_eyebrow)}</span>
          <h2 className="sec-title">{T(U.quiz_title)}</h2>
          <p className="sec-sub" style={{ margin: "0 auto" }}>{T(U.quiz_sub)}</p>
        </div>

        <div className="quiz-card">
          {!done ? (
            <React.Fragment>
              <div className="quiz-top">
                <span className="quiz-prog">{T(U.quiz_q)} {i + 1} / {Q.length}</span>
                <span className="quiz-score">{T(U.quiz_score)}: {score}</span>
              </div>
              <div className="qbar"><i style={{ width: pct + "%" }}></i></div>
              <h3 className="qtext">{T(q.q)}</h3>
              <div className="qopts">
                {opts.map((o, idx) => {
                  let cls = "qopt";
                  if (picked !== null) {
                    if (idx === q.a) cls += " correct";
                    else if (idx === picked) cls += " wrong";
                  }
                  return (
                    <button key={idx} className={cls} disabled={picked !== null} onClick={() => choose(idx)}>
                      <span className="k">{["A", "B", "C", "D"][idx]}</span>{o}
                    </button>
                  );
                })}
              </div>
              {picked !== null && (
                <div className="qexp"><b>{picked === q.a ? T(U.quiz_right) : T(U.quiz_wrong)}</b>{T(q.exp)}</div>
              )}
              <div className="quiz-foot">
                <button className="btn btn-gold" disabled={picked === null} onClick={next}
                  style={{ opacity: picked === null ? .45 : 1 }}>
                  {i + 1 < Q.length ? T(U.quiz_next) : T(U.quiz_result)} <Icon n="arrow" s={18} />
                </button>
              </div>
            </React.Fragment>
          ) : (
            <div className="quiz-result">
              <div className="big">{score}/{Q.length}</div>
              <h3>{verdict()[0]}</h3>
              <p>{verdict()[1]}</p>
              <div className="actions">
                <button className="btn btn-navy" onClick={restart}>{T(U.quiz_again)}</button>
                <a className="btn btn-gold" href={AKB.quizUrl} target="_blank" rel="noopener">
                  {T(U.quiz_full)} <Icon n="arrow" s={18} />
                </a>
              </div>
            </div>
          )}
        </div>

        <p style={{ textAlign: "center", marginTop: 22, color: "var(--ink-soft)", fontSize: ".95rem" }}>
          {T(U.quiz_more)} <a href={AKB.quizUrl} target="_blank" rel="noopener"
            style={{ color: "var(--gold-deep)", fontWeight: 700 }}>{T(U.quiz_morelink)}</a>
        </p>
      </div>
    </section>
  );
}

/* --- BLOG --- */
function Blog() {
  const [lang, T] = useTr(); const U = AKB.ui;
  return (
    <section className="section-pad" id="blog" style={{ background: "color-mix(in srgb,var(--sky-mid) 7%,var(--paper))" }}>
      <div className="wrap">
        <div className="sec-head">
          <div>
            <span className="eyebrow">{T(U.blog_eyebrow)}</span>
            <h2 className="sec-title">{T(U.blog_title)}</h2>
            <p className="sec-sub">{T(U.blog_sub)}</p>
          </div>
          <a href="#blog" className="btn btn-ghost">{T(U.blog_all)} <Icon n="arrow" s={18} /></a>
        </div>
        <div className="blog-grid">
          {AKB.posts.map((p, i) => (
            <Reveal key={i} className="post" tag="article" delay={i * 80}>
              <div className="thumb"><Placeholder label="drop cover image" color={p.c} /></div>
              <div className="body">
                <span className="ptag">{T(p.tag)}</span>
                <h3>{T(p.title)}</h3>
                <p>{T(p.excerpt)}</p>
                <div className="pf">
                  <span>{p.date}</span><span>•</span><span>{p.read} {T(U.blog_min)}</span>
                  <span className="read">{T(U.blog_read)} <Icon n="arrow" s={15} /></span>
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* --- ABOUT --- */
function About() {
  const [lang, T] = useTr(); const U = AKB.ui;
  const AS = AKB.aboutStats || {};
  return (
    <section className="about section-pad" id="about">
      <div className="wrap about-grid">
        <Reveal className="about-portrait">
          <div className="frame"><img src={(window.__resources && window.__resources.akshat) || "assets/akshat-portrait.webp"} alt="Akshat Ratanpal" /></div>
          <div className="badge">Akshat Ratanpal<span>Host & AI explainer</span></div>
        </Reveal>
        <Reveal className="about-body" delay={120}>
          <span className="eyebrow">{T(U.about_eyebrow)}</span>
          <h2 className="sec-title">{T(U.about_title)}</h2>
          <p>{T(U.about_p1)}</p>
          <p>{T(U.about_p2)}</p>
          <div className="about-stats">
            <div className="s"><b>{AS.episodes}</b><span>{T(U.about_s1)}</span></div>
            <div className="s"><b>{AS.guests}</b><span>{T(U.about_s2)}</span></div>
            <div className="s"><b>{AS.community}</b><span>{T(U.about_s3)}</span></div>
          </div>
          <div className="hero-actions">
            <a href="#newsletter" className="btn btn-navy"><Icon n="bell" s={18} /> {T(U.about_join)}</a>
            <a href="#listen" className="btn btn-ghost"><Icon n="headphone" s={18} /> {T(U.about_listen)}</a>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* --- NEWSLETTER --- */
function Newsletter() {
  const [lang, T] = useTr(); const U = AKB.ui;
  const [sent, setSent] = useState(false);
  const [email, setEmail] = useState("");
  return (
    <section className="news" id="newsletter">
      <div className="wrap">
        <div className="news-card">
          <div className="glow"></div>
          <div className="news-grid">
            <div>
              <span className="eyebrow"><Icon n="spark" s={16} /> {T(U.news_eyebrow)}</span>
              <h2>{T(U.news_title)}</h2>
              <p>{T(U.news_p)}</p>
            </div>
            <form className="news-form" onSubmit={e => { e.preventDefault(); if (email) setSent(true); }}>
              <div className="field">
                <input type="email" required placeholder={T(U.news_ph)} value={email}
                  onChange={e => setEmail(e.target.value)} aria-label="email" />
                <button className="btn btn-gold" type="submit"><Icon n="mail" s={18} /> {T(U.news_btn)}</button>
              </div>
              {sent ? <span className="ok"><Icon n="check" s={15} /> {T(U.news_ok)}</span>
                    : <span className="news-note">{T(U.news_note)}</span>}
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}

/* --- FOOTER --- */
function Footer() {
  const [lang, T] = useTr(); const U = AKB.ui;
  return (
    <footer className="foot">
      <div className="wrap">
        <div className="foot-top">
          <div style={{ maxWidth: 340 }}>
            <a href="#top" className="brand"><span className="mic"><Icon n="mic" s={20} /></span>
              <span><span className="ai">AI</span> <span className="ki">की बात</span></span></a>
            <p className="foot-tag">{T(U.foot_tag)}</p>
            <div className="socials">
              {AKB.socials.map(s => <a key={s} href="#" title={s} aria-label={s}>{s[0]}</a>)}
            </div>
          </div>
          <div className="foot-cols">
            <div><h4>{T(U.foot_explore)}</h4>
              <a href="#episodes">{T(U.nav_episodes)}</a><a href="#quiz">{T(U.nav_quiz)}</a><a href="#blog">{T(U.nav_blog)}</a><a href="#about">{T(U.nav_host)}</a></div>
            <div><h4>{T(U.foot_listen)}</h4>
              {AKB.platforms.map(p => <a key={p.name} href={p.url}>{p.name}</a>)}</div>
            <div><h4>{T(U.foot_connect)}</h4>
              <a href="#newsletter">Newsletter</a><a href="#">{T(U.foot_contact)}</a><a href="#">{T(U.foot_guest)}</a></div>
          </div>
        </div>
        <div className="foot-bottom">
          <span>{T(U.foot_made)}</span>
          <span>Privacy • Terms</span>
        </div>
      </div>
    </footer>
  );
}
