/* Voice — HI-FI. Polished dark mode: pulsing play button, animated waveform,
   sweeping transcript highlight, smooth audio-row hover with gold play-button fill.
*/

const HF_VOICE_LIST = [
  { n: "01", date: "Fri · 14 Feb 1992",  title: "On Education and the Patient Cultivation of the Mind",  dur: "47:22", place: "Istanbul", cat: "Friday talks" },
  { n: "02", date: "Fri · 22 Aug 1992",  title: "Friendship and Brotherhood in Islam",                    dur: "52:08", place: "Istanbul", cat: "Friday talks" },
  { n: "03", date: "Sun · 11 Oct 1993",  title: "Without the Sunnah, There Is No Ummah",                  dur: "38:54", place: "Konya",    cat: "Lectures" },
  { n: "04", date: "Fri · 03 Mar 1995",  title: "Mi'rāj: The Path, The Journey, The Traveler",            dur: "59:12", place: "Istanbul", cat: "Friday talks" },
  { n: "05", date: "Mon · 19 Jan 1998",  title: "The Main Issue in the 21st Century",                     dur: "1:04:30", place: "London", cat: "Lectures" },
  { n: "06", date: "Wed · 04 Aug 1999",  title: "The Art of Servanthood in the 21st Century",             dur: "41:18", place: "Sydney",   cat: "Conversations" },
  { n: "07", date: "Sat · 12 Apr 1996",  title: "A Letter to My Brothers on the Subtleties of Sincerity", dur: "12:46", place: "—",        cat: "Letters read aloud" },
  { n: "08", date: "Tue · 28 Nov 2000",  title: "Conversation with Students on Knowledge and Adab",       dur: "1:14:02", place: "Istanbul", cat: "Conversations" },
];
const HF_VOICE_FILTERS = ["All", "Friday talks", "Lectures", "Conversations", "Letters read aloud"];

/* Animated waveform — 18 bars with varied delays so it ripples. */
function HfWaveform({ accent, bars = 22, height = 48 }) {
  return (
    <span className="hf-wave" style={{ color: accent, height }}>
      {Array.from({ length: bars }).map((_, i) => (
        <i key={i} style={{ animationDelay: `${(i % 11) * 80}ms` }} />
      ))}
    </span>
  );
}

function VoiceHiFi({ mode = "desktop", accent = "#B89968" }) {
  const mobile = mode === "mobile";
  const rootRef = React.useRef(null);
  const [theme] = (typeof useTheme === "function" ? useTheme() : ["light", () => {}]);
  const dark = theme === "dark";
  const [lang] = (typeof useLang === "function" ? useLang() : ["en"]);
  const mt = (k) => (typeof miscT === "function" ? miscT(k, lang) : k);
  const [activeFilter, setActiveFilter] = React.useState("All");

  React.useEffect(() => {
    const root = rootRef.current; if (!root) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add("is-in"); io.unobserve(e.target); } });
    }, { root, threshold: 0.12, rootMargin: "0px 0px -6% 0px" });
    root.querySelectorAll(".hf-reveal:not(.is-in)").forEach(t => io.observe(t));
    return () => io.disconnect();
  }, [activeFilter]);

  const hairline = "var(--hairline)";
  const hairlineSoft = "var(--hairline)";
  const grayLight = "var(--gray-warm)";
  const inkColor = "var(--ink)";
  const inkSoft = "var(--ink-soft)";
  const bgColor = "var(--bg)";

  return (
    <div ref={rootRef} className={"cw-frame" + (dark ? " dark" : "")} style={{ overflowY: "auto", background: bgColor, color: inkColor }}>
      <TopNav current="Library" mobile={mobile} accent={accent} dark={dark} />

      {/* Hero */}
      <section style={{
        padding: mobile ? "60px 22px 40px" : "120px 96px 80px",
        display: "grid", gridTemplateColumns: mobile ? "1fr" : "1.2fr 1fr",
        gap: mobile ? 24 : 80, alignItems: "end",
        borderBottom: `1px solid ${hairline}`,
        position: "relative",
      }}>
        <div>
          <span className="hf-eyebrow-rule hf-rise" style={{ color: grayLight, animationDelay: "150ms" }}>04  /  {mt("the_voice")}  ·  {mt("recorded_archive")}</span>
          <h1 className="serif hf-rise" style={{
            fontWeight: 300, fontSize: mobile ? 80 : 168, lineHeight: 0.92, letterSpacing: "-0.03em",
            margin: "16px 0 0", color: inkColor,
            fontVariationSettings: '"opsz" 144, "SOFT" 30',
            animationDelay: "300ms",
          }}>
            <span style={{ color: accent, fontStyle: "italic", fontVariationSettings: '"opsz" 9, "SOFT" 100' }}>{mt("the_voice")}</span>
          </h1>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: mobile ? 16 : 32 }}>
          <div className="hf-rise" style={{ borderTop: `1px solid ${accent}`, paddingTop: 14, animationDelay: "650ms" }}>
            <span className="eyebrow" style={{ color: grayLight }}>{mt("hours")}</span>
            <p className="serif" style={{ fontSize: mobile ? 44 : 76, fontWeight: 350, lineHeight: 1, margin: "8px 0 0",
              color: "var(--bg)", letterSpacing: "-0.02em",
              fontVariationSettings: '"opsz" 144, "SOFT" 30', color: inkColor }}>211</p>
          </div>
          <div className="hf-rise" style={{ borderTop: `1px solid ${accent}`, paddingTop: 14, animationDelay: "850ms" }}>
            <span className="eyebrow" style={{ color: grayLight }}>{mt("range")}</span>
            <p className="serif" style={{ fontSize: mobile ? 28 : 48, fontWeight: 350, lineHeight: 1, margin: "8px 0 0",
              color: "var(--bg)", letterSpacing: "-0.015em",
              fontVariationSettings: '"opsz" 144, "SOFT" 30', color: inkColor }}>1987<br/><span style={{ color: accent }}>—</span> 2001</p>
          </div>
        </div>
      </section>

      {/* Filters */}
      <section className="hf-reveal" style={{ padding: mobile ? "20px 22px 4px" : "32px 96px 16px", borderBottom: `1px solid ${hairline}` }}>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
          <span className="eyebrow" style={{ marginRight: 8, color: grayLight }}>— Filter</span>
          {HF_VOICE_FILTERS.map((f) => {
            const sel = f === activeFilter;
            return (
              <span key={f} onClick={() => setActiveFilter(f)} style={{
                display: "inline-flex", padding: "6px 14px", borderRadius: 100,
                border: sel ? `1px solid ${inkColor}` : `1px solid ${hairlineSoft}`,
                background: sel ? inkColor : "transparent",
                color: sel ? bgColor : inkColor,
                fontSize: 12, letterSpacing: "0.04em",
                transition: "all 250ms cubic-bezier(0.22,1,0.36,1)", cursor: "pointer",
              }}>{mt(VF_KEYS[f] || "vf_all")}</span>
            );
          })}
        </div>
      </section>

      {/* Now playing — pulsing button + animated waveform progress */}
      <section className="hf-reveal" style={{ padding: mobile ? "40px 22px" : "80px 96px" }}>
        <span className="eyebrow" style={{ color: accent }}>— {mt("now_playing")}</span>
        <div style={{ marginTop: mobile ? 18 : 28, padding: mobile ? "24px 0" : "40px 0",
          borderTop: `1px solid ${hairlineSoft}`, borderBottom: `1px solid ${hairlineSoft}` }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14 }}>
            <span className="eyebrow" style={{ color: grayLight }}>Friday talk · 14 Feb 1992 · Istanbul</span>
            <span className="eyebrow" style={{ color: grayLight }}>47:22</span>
          </div>
          <h2 className="serif" style={{
            fontWeight: 350, fontSize: mobile ? 32 : 60, lineHeight: 1.04, letterSpacing: "-0.02em",
            margin: 0,
            fontVariationSettings: '"opsz" 144, "SOFT" 30',
            color: inkColor,
          }}>On Education and the Patient Cultivation of the Mind</h2>

          {/* Play row — pulsing button + waveform + timestamps */}
          <div style={{ display: "flex", alignItems: "center", gap: mobile ? 14 : 28, marginTop: mobile ? 28 : 48 }}>
            <button
              className="hf-play-pulse"
              style={{
                width: mobile ? 52 : 64, height: mobile ? 52 : 64, borderRadius: "50%",
                background: accent, color: bgColor, border: 0, flexShrink: 0,
                display: "grid", placeItems: "center", fontSize: 18, cursor: "pointer",
                transition: "transform 280ms cubic-bezier(0.22,1,0.36,1)",
              }}
              onMouseEnter={(e) => e.currentTarget.style.transform = "scale(1.06)"}
              onMouseLeave={(e) => e.currentTarget.style.transform = "scale(1)"}
            >▶</button>

            <div style={{ flex: 1, display: "flex", alignItems: "center", gap: mobile ? 12 : 20 }}>
              <span style={{ fontSize: 12, color: grayLight, fontVariantNumeric: "tabular-nums", letterSpacing: "0.04em", minWidth: 44 }}>15:08</span>
              {/* Waveform progress: filled portion in accent, rest in low-opacity */}
              <div style={{ flex: 1, position: "relative", height: mobile ? 36 : 48 }}>
                <div style={{ position: "absolute", inset: 0, opacity: 0.18 }}>
                  <HfWaveform accent={inkColor} bars={mobile ? 26 : 48} height={mobile ? 36 : 48} />
                </div>
                <div style={{ position: "absolute", inset: 0, width: "32%", overflow: "hidden" }}>
                  <HfWaveform accent={accent} bars={mobile ? 26 : 48} height={mobile ? 36 : 48} />
                </div>
                <span style={{ position: "absolute", left: "32%", top: 0, bottom: 0, width: 1, background: accent, opacity: 0.6 }} />
              </div>
              <span style={{ fontSize: 12, color: grayLight, fontVariantNumeric: "tabular-nums", letterSpacing: "0.04em", minWidth: 44, textAlign: "right" }}>47:22</span>
            </div>
          </div>
        </div>

        {/* Transcript with sweeping highlight */}
        <div className="hf-transcript-sweep" style={{ marginTop: mobile ? 36 : 64, display: "grid", gridTemplateColumns: mobile ? "1fr" : "180px 1fr", gap: mobile ? 16 : 56 }}>
          <span className="eyebrow" style={{ color: accent }}>— {mt("transcript")}</span>
          <div style={{ maxWidth: 760 }}>
            <p className="serif" style={{ fontSize: mobile ? 17 : 22, lineHeight: 1.7, color: inkSoft, margin: 0,
              fontVariationSettings: '"opsz" 24', textWrap: "pretty" }}>
              The first thing — and I want you to remember this — is that education is a kind of patience. <mark>Knowledge does not arrive the way news arrives.</mark> It comes the way trees come; quietly, in seasons. You water; you wait. You water again; you wait again. And one morning, without warning, you find a shade where there was none before…
            </p>
            <a className="hf-link" style={{ color: accent, fontSize: 13, letterSpacing: "0.04em", marginTop: 22, display: "inline-block", paddingBottom: 2 }}>{mt("read_full")} →</a>
          </div>
        </div>
      </section>

      {/* More from the archive — hover fills the play button gold */}
      <section style={{ padding: mobile ? "40px 22px 80px" : "60px 96px 120px" }}>
        <div className="hf-reveal" style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: mobile ? 20 : 32 }}>
          <span className="eyebrow" style={{ color: grayLight }}>— {mt("more_archive")}</span>
          <span className="eyebrow" style={{ color: grayLight }}>{mobile ? `211 ${mt("recordings")}` : `211 ${mt("recordings")} · ${mt("four_languages")}`}</span>
        </div>
        {HF_VOICE_LIST.filter(a => activeFilter === "All" || a.cat === activeFilter).map((a, i) => (
          <article
            key={a.n}
            className="hf-reveal"
            style={{
              display: "grid",
              gridTemplateColumns: mobile ? "44px 1fr auto" : "60px 220px 1fr 80px",
              alignItems: "center", gap: mobile ? 12 : 24,
              padding: mobile ? "18px 0" : "26px 0",
              borderTop: i === 0 ? `1px solid ${inkColor}` : `1px solid ${hairline}`,
              transitionDelay: `${i * 40}ms`,
              cursor: "pointer",
              position: "relative",
            }}
            onMouseEnter={(e) => {
              const btn = e.currentTarget.querySelector("button");
              if (btn) { btn.style.background = accent; btn.style.color = bgColor; }
            }}
            onMouseLeave={(e) => {
              const btn = e.currentTarget.querySelector("button");
              if (btn) { btn.style.background = "transparent"; btn.style.color = accent; }
            }}
          >
            <button style={{
              width: mobile ? 36 : 42, height: mobile ? 36 : 42, borderRadius: "50%",
              border: `1px solid ${accent}`, background: "transparent", color: accent,
              fontSize: 12, cursor: "pointer",
              transition: "all 280ms cubic-bezier(0.22,1,0.36,1)",
            }}>▶</button>
            {!mobile && <span style={{ fontSize: 12, color: grayLight, letterSpacing: "0.04em" }}>{a.date}</span>}
            <div>
              <h4 className="serif" style={{ fontWeight: 400, fontSize: mobile ? 16 : 21, letterSpacing: "-0.01em", margin: 0, color: inkColor, lineHeight: 1.25 }}>{a.title}</h4>
              {mobile && <span style={{ fontSize: 11, color: grayLight, letterSpacing: "0.04em" }}>{a.date} · {a.place}</span>}
              {!mobile && <span style={{ fontSize: 11, color: grayLight, letterSpacing: "0.04em" }}>{a.place}</span>}
            </div>
            <span style={{ fontSize: 12, color: grayLight, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{a.dur}</span>
          </article>
        ))}
      </section>

      <SiteFooter mobile={mobile} accent={accent} dark={dark} />
    </div>
  );
}

Object.assign(window, { VoiceHiFi });
