/* Sections part 2: Testimoni, Edukasi, Sosmed, Kontak, Footer */
const { useState: uS2 } = React;

/* ---------------- TESTIMONI (video scroller per age group) ---------------- */
const { useRef: uR2 } = React;
const Testimoni = () => {
  const ages = Object.keys(SITE.testimoni);
  const icons = { Remaja: "users", Dewasa: "shield", Lansia: "leaf" };
  const [age, setAge] = uS2(ages[0]);
  const [playing, setPlaying] = uS2(null);
  const trackRef = uR2(null);

  const scrollBy = (dir) => {
    const el = trackRef.current;
    if (!el) return;
    el.scrollBy({ left: dir * Math.min(el.clientWidth * 0.8, 640), behavior: "smooth" });
  };
  const list = SITE.testimoni[age];

  return (
    <section className="section testi-section" id="testimoni">
      <div className="wrap">
        <Reveal as="div" className="section-head center">
          <span className="eyebrow center">Testimoni</span>
          <h2>Cerita nyata dari setiap generasi</h2>
          <p>Dengar langsung pengalaman mereka yang sudah bergabung bersama Perwatusi Riau — dari remaja hingga lansia.</p>
        </Reveal>
        <Reveal className="age-tabs">
          {ages.map((a) => (
            <button key={a} className={`age-tab ${age === a ? "active" : ""}`} onClick={() => { setAge(a); setPlaying(null); }}>
              <Icon name={icons[a]} style={{ width: 18, height: 18 }} />{a}
              <span className="age-count">{SITE.testimoni[a].length}</span>
            </button>
          ))}
        </Reveal>

        <div className="testi-scroller">
          <button className="testi-arrow left" aria-label="Sebelumnya" onClick={() => scrollBy(-1)}><Icon name="arrow" style={{ transform: "rotate(180deg)" }} /></button>
          <div className="testi-track" ref={trackRef} key={age}>
            {list.map((t, i) => (
              <article className="vtesti-card" key={t.name}>
                <div className="vtesti-media">
                  {t.video && playing === i ? (
                    <iframe src={t.video + (t.video.includes("?") ? "&" : "?") + "autoplay=1"} title={t.name} allow="autoplay; encrypted-media" allowFullScreen></iframe>
                  ) : (
                    <button className="vtesti-poster" onClick={() => t.video && setPlaying(i)} aria-label={`Putar video ${t.name}`}>
                      <Placeholder icon="camera" dark label="Video testimoni" />
                      <span className="vtesti-play"><Icon name="play" /></span>
                      <span className="vtesti-grad"></span>
                      <span className="vtesti-cap">{t.caption}</span>
                    </button>
                  )}
                </div>
                <div className="vtesti-foot">
                  <div className="av">{t.name.split(" ").map((w) => w[0]).slice(0, 2).join("")}</div>
                  <div><b>{t.name}</b><span>{t.meta}</span></div>
                </div>
              </article>
            ))}
          </div>
          <button className="testi-arrow right" aria-label="Berikutnya" onClick={() => scrollBy(1)}><Icon name="arrow" /></button>
        </div>
        <p className="testi-hint">Geser untuk melihat lebih banyak testimoni →</p>
      </div>
    </section>
  );
};

/* ---------------- EDUKASI ---------------- */
const Edukasi = () => {
  const v = SITE.videoFeature;
  const [selectedCategory, setSelectedCategory] = useState("Semua");
  const categories = ["Semua", ...new Set(SITE.articles.map(a => a.cat || "Umum"))];
  const filteredArticles = selectedCategory === "Semua" 
    ? SITE.articles 
    : SITE.articles.filter(a => (a.cat || "Umum") === selectedCategory);
  const pg = usePaged(filteredArticles, 6, [selectedCategory]);
  const changePage = (n) => { pg.setPage(n); document.getElementById("edukasi")?.scrollIntoView({ behavior: "smooth" }); };
  const initials = (name) => name.replace(/^(dr\.?|hj\.?|h\.?)\s*/i, "").split(" ").map((w) => w[0]).filter(Boolean).slice(0, 2).join("").toUpperCase();
  return (
    <section className="section" id="edukasi">
      <div className="wrap">
        <Reveal as="div" className="section-head">
          <span className="eyebrow">Edukasi</span>
          <h2>Materi Kesehatan Tulang</h2>
          <p>Artikel, video, dan panduan praktis kesehatan tulang yang mudah dipahami dan bisa langsung diterapkan.</p>
        </Reveal>

        <Reveal className="edu-feature-wide">
          <div className="edu-video">
            {v.youtube
              ? <iframe src={v.youtube} title={v.title} allowFullScreen></iframe>
              : <>
                  <Placeholder dark label="Slot video — sematkan YouTube" />
                  <div className="edu-play"><Icon name="play" /></div>
                </>}
          </div>
          <div className="edu-feature-body">
            <div className="tag">{v.label}</div>
            <h3>{v.title}</h3>
            <p>{v.desc}</p>
          </div>
        </Reveal>

        <div className="edu-sub">
          <h3>Artikel Edukasi</h3>
          <span className="count">{pg.total} artikel tersedia</span>
        </div>

        <div className="art-filter-bar">
          {categories.map((cat) => (
            <button
              key={cat}
              className={`filter-pill ${selectedCategory === cat ? "active" : ""}`}
              onClick={() => setSelectedCategory(cat)}
              aria-current={selectedCategory === cat ? "page" : undefined}
              aria-label={`Filter articles by ${cat}`}
            >
              {cat}
            </button>
          ))}
        </div>
        <div className="art-grid">
          {pg.pageItems.map((a, i) => (
            <Reveal as="a" key={a.title} className="keg-card" delay={(i % 3) + 1} href={`/artikel/${slugify(a.title)}`} onClick={(e) => { e.preventDefault(); navigate("artikel/" + slugify(a.title)); }}>
              <div className="keg-media">
                <Media media={a.hero} label={a.title} />
                <span className="keg-cat">{a.cat}</span>
              </div>
              <div className="keg-body">
                <div className="keg-loc"><Icon name="clock" /> {a.rt}</div>
                <h3 style={{ fontSize: 19, marginTop: 8 }}>{a.title}</h3>
                <p>{a.excerpt}</p>
                <div className="art-byline"><div className="av">{initials(a.by)}</div><span>{a.by}</span></div>
              </div>
            </Reveal>
          ))}
        </div>
        <p className="list-count">Menampilkan <b>{pg.from}–{pg.to}</b> dari <b>{pg.total}</b> artikel</p>
        <Pager page={pg.page} pages={pg.pages} onChange={changePage} />
      </div>
    </section>
  );
};

/* ---------------- SOSMED ---------------- */
const Sosmed = () => {
  const { tiktok, ig } = SITE.social;
  return (
    <section className="section wash" id="sosmed">
      <div className="wrap">
        <Reveal as="div" className="section-head center">
          <span className="eyebrow center">Sosial Media</span>
          <h2>Ikuti perjalanan kami setiap hari</h2>
          <p>Tips harian, dokumentasi kegiatan, dan edukasi singkat — ada di TikTok dan Instagram Perwatusi Riau.</p>
        </Reveal>
        <div className="sosmed-grid">
          <Reveal className="sm-panel sm-tiktok" delay={1}>
            <div className="sm-head">
              <div className="ic"><Icon name="tiktok" /></div>
              <div><b>TikTok</b><span>{tiktok.handle}</span></div>
            </div>
            <div className="sm-stats">
              <div><b>{tiktok.followers}</b><span>Pengikut</span></div>
              <div><b>{tiktok.likes}</b><span>Suka</span></div>
            </div>
            <div className="sm-feed">
              {[0,1,2,3,4,5].map((i) => <div key={i} className="sm-post"><Placeholder icon="play" dark /></div>)}
            </div>
            <a className="sm-follow" href={tiktok.url} target="_blank" rel="noopener"><Icon name="tiktok" style={{ width: 18, height: 18 }} /> Ikuti di TikTok</a>
          </Reveal>
          <Reveal className="sm-panel sm-ig" delay={2}>
            <div className="sm-head">
              <div className="ic"><Icon name="instagram" /></div>
              <div><b>Instagram</b><span>{ig.handle}</span></div>
            </div>
            <div className="sm-stats">
              <div><b>{ig.followers}</b><span>Pengikut</span></div>
              <div><b>{ig.posts}</b><span>Postingan</span></div>
            </div>
            <div className="sm-feed">
              {[0,1,2,3,4,5].map((i) => <div key={i} className="sm-post"><Placeholder icon="camera" dark /></div>)}
            </div>
            <a className="sm-follow" href={ig.url} target="_blank" rel="noopener"><Icon name="instagram" style={{ width: 18, height: 18 }} /> Ikuti di Instagram</a>
          </Reveal>
        </div>
      </div>
    </section>
  );
};

/* ---------------- KONTAK ---------------- */
const Kontak = () => {
  const [vals, setVals] = uS2({ nama: "", email: "", subjek: "Informasi Umum", pesan: "" });
  const [errs, setErrs] = uS2({});
  const [sent, setSent] = uS2(false);
  const [loading, setLoading] = uS2(false);
  const set = (k) => (e) => { setVals((v) => ({ ...v, [k]: e.target.value })); setErrs((x) => ({ ...x, [k]: false })); };
  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!vals.nama.trim()) er.nama = true;
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(vals.email)) er.email = true;
    if (vals.pesan.trim().length < 8) er.pesan = true;
    setErrs(er);
    if (Object.keys(er).length > 0) return;
    setLoading(true);
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(vals),
      });
      const data = await res.json();
      if (data.ok) {
        setSent(true);
        setVals({ nama: "", email: "", subjek: "Informasi Umum", pesan: "" });
      } else {
        alert(data.message || "Gagal mengirim pesan. Coba lagi.");
      }
    } catch {
      alert("Gagal menghubungi server. Periksa koneksi Anda.");
    } finally {
      setLoading(false);
    }
  };
  return (
    <section className="section" id="kontak">
      <div className="wrap kontak-grid">
        <div>
          <Reveal as="div" className="section-head">
            <span className="eyebrow">Kontak</span>
            <h2>Mari terhubung & bergabung</h2>
            <p>Punya pertanyaan, ingin mengundang kami, atau bergabung sebagai relawan? Hubungi sekretariat DPD Perwatusi Riau.</p>
          </Reveal>
          <Reveal className="kontak-info" delay={1}>
            {SITE.kontak.rows.map((r) => (
              <div key={r.title} className="ki-row">
                <div className="ic"><Icon name={r.icon} /></div>
                <div><b>{r.title}</b><p>{r.text}</p></div>
              </div>
            ))}
          </Reveal>
          <Reveal className="kontak-map" delay={2}>
            <iframe title="Lokasi" loading="lazy" src="https://www.google.com/maps?q=Pekanbaru,Riau&output=embed"></iframe>
          </Reveal>
        </div>
        <Reveal className="form-card" delay={1}>
          {sent && <div className="form-ok"><Icon name="check" style={{ width: 20, height: 20 }} /> Terima kasih! Pesan Anda telah terkirim. Tim kami akan segera menghubungi.</div>}
          <form onSubmit={submit} noValidate>
            <div className={`field ${errs.nama ? "err" : ""}`}>
              <label>Nama Lengkap</label>
              <input value={vals.nama} onChange={set("nama")} placeholder="Nama Anda" />
              <div className="msg">Mohon isi nama Anda.</div>
            </div>
            <div className={`field ${errs.email ? "err" : ""}`}>
              <label>Email</label>
              <input type="email" value={vals.email} onChange={set("email")} placeholder="nama@email.com" />
              <div className="msg">Masukkan email yang valid.</div>
            </div>
            <div className="field">
              <label>Subjek</label>
              <select value={vals.subjek} onChange={set("subjek")}>
                <option>Informasi Umum</option>
                <option>Ingin menjadi relawan</option>
                <option>Undangan kegiatan</option>
                <option>Konsultasi kesehatan tulang</option>
              </select>
            </div>
            <div className={`field ${errs.pesan ? "err" : ""}`}>
              <label>Pesan</label>
              <textarea value={vals.pesan} onChange={set("pesan")} placeholder="Tuliskan pesan Anda..."></textarea>
              <div className="msg">Pesan minimal 8 karakter.</div>
            </div>
            <button type="submit" className="btn btn-green" style={{ width: "100%" }} disabled={loading}>
              {loading ? "Mengirim..." : <><span>Kirim Pesan</span> <Icon name="arrow" /></>}
            </button>
          </form>
        </Reveal>
      </div>
    </section>
  );
};

/* ---------------- FOOTER ---------------- */
const Footer = () => {
  const go = (e, id) => { e.preventDefault(); document.getElementById(id)?.scrollIntoView({ behavior: "smooth" }); };
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div className="footer-col">
            <div className="footer-brand">
              <div className="nav-logo"><img src="/assets/logo.png" alt="" /></div>
              <div><b>PERWATUSI</b><span>DPD Riau</span></div>
            </div>
            <p>Perkumpulan Warga Tulang Sehat Indonesia — Dewan Pengurus Daerah Riau. Bersama menjaga tulang sehat untuk semua usia.</p>
            <div className="footer-socials">
              <a href={SITE.social.tiktok.url} aria-label="TikTok" target="_blank" rel="noopener"><Icon name="tiktok" /></a>
              <a href={SITE.social.ig.url} aria-label="Instagram" target="_blank" rel="noopener"><Icon name="instagram" /></a>
              <a href="#" aria-label="WhatsApp"><Icon name="whatsapp" /></a>
              <a href="#" aria-label="YouTube"><Icon name="youtube" /></a>
            </div>
          </div>
          <div className="footer-col">
            <h5>Navigasi</h5>
            <ul>
              {SITE.nav.map((n) => <li key={n.id}><a href={`#${n.id}`} onClick={(e) => go(e, n.id)}>{n.label}</a></li>)}
            </ul>
          </div>
          <div className="footer-col">
            <h5>Program</h5>
            <ul>
              <li><a href="#kegiatan" onClick={(e) => go(e, "kegiatan")}>Skrining Tulang</a></li>
              <li><a href="#kegiatan" onClick={(e) => go(e, "kegiatan")}>Senam Sehat</a></li>
              <li><a href="#edukasi" onClick={(e) => go(e, "edukasi")}>Edukasi Dokter</a></li>
              <li><a href="#kegiatan" onClick={(e) => go(e, "kegiatan")}>Bakti Sosial</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Sekretariat</h5>
            <ul>
              {SITE.kontak.rows.map((r) => <li key={r.title}>{r.text}</li>)}
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 DPD Perwatusi Riau. Hak cipta dilindungi.</span>
          <span>Dibuat untuk tulang sehat warga Riau.</span>
        </div>
      </div>
    </footer>
  );
};

Object.assign(window, { Testimoni, Edukasi, Sosmed, Kontak, Footer });
