// ── AUDIOBOOKS + PODCAST PAGE ───────────────────────────────
// Two surfaces in one tab. Top: Audiobooks (per-edition narration).
// Bottom: Podcast — three layers (weekly consolidate · themed seasons
// · tailor-on-request). The tailor-on-request layer is the new ask:
// a member picks theme + voice + duration and gets a private episode
// stitched from the archive.

function Audiobooks({ theme, dark, lang, isMember, nav }) {
  const [layer, setLayer] = useState("weekly");
  const [now, setNow] = useState(null);

  return (
    <div style={{ background: theme.bg, color: theme.text, paddingTop:"5rem" }}>
      {/* Migration notice */}
      <div id="mig-banner" style={{
        background: 'rgba(200,168,90,.08)', border: '1px solid rgba(200,168,90,.22)',
        borderRadius: 6, margin: '0 clamp(1rem, 5vw, 4rem)', padding: '14px 20px',
        textAlign: 'center', fontSize: '.85rem', color: theme.gold || '#C8A85A', lineHeight: 1.5,
      }}>
        {lang === 'en'
          ? "We\u2019re migrating WiseTip to new servers \u2014 audiobooks and podcast will be available soon."
          : "Estamos migrando WiseTip a nuevos servidores \u2014 los audiolibros y el podcast estar\u00e1n disponibles pronto."}
      </div>
      {/* HEADER */}
      <div style={{
        background: dark
          ? `radial-gradient(ellipse 50% 40% at 80% 0%, rgba(200,168,90,.12) 0%, transparent 55%), linear-gradient(180deg, #0A1A10 0%, ${theme.bg} 100%)`
          : `radial-gradient(ellipse 50% 40% at 80% 0%, rgba(138,96,32,.08) 0%, transparent 55%), linear-gradient(180deg, ${theme.bg2} 0%, ${theme.bg} 100%)`,
        padding:"5rem clamp(1.5rem, 5vw, 5vw) 3rem", position:"relative",
      }}>
        <div className="wrap">
          <Eyebrow theme={theme}>{lang==="en"?"Listen · audiobooks & podcast":"Escucha · audiolibros y podcast"}</Eyebrow>
          <h1 className="serif" style={{
            fontStyle:"italic", fontWeight:300, fontSize:"clamp(2.4rem, 5.5vw, 4.6rem)",
            color: theme.text, lineHeight: 1.02, letterSpacing:"-.02em",
            marginTop:".75rem", marginBottom:"1rem", maxWidth: 900,
          }}>{lang==="en"
            ? <>For the school run, <em>the long drive,</em> and the night you can't read.</>
            : <>Para ir al cole, <em>el viaje largo</em> y la noche que no puedes leer.</>}</h1>
          <p style={{ color: theme.text2, fontSize:"1.05rem", lineHeight: 1.7, fontWeight: 300, maxWidth: 640 }}>
            {lang==="en"
              ? "Two listening surfaces. Forty-nine audiobooks adapted from the archive, and a podcast in three layers — including episodes you can request on demand."
              : "Dos formas de escuchar. Cuarenta y nueve audiolibros adaptados del archivo y un podcast en tres capas — incluyendo episodios bajo demanda."}
          </p>
        </div>
      </div>

      {/* ── AUDIOBOOKS GRID ── */}
      <section className="section" style={{ padding:"4rem clamp(1.5rem, 5vw, 5vw) 5rem" }}>
        <div className="wrap">
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom:"2rem", flexWrap:"wrap", gap:"1rem" }}>
            <div>
              <Eyebrow theme={theme}>{lang==="en"?"Audiobooks · 49 in archive":"Audiolibros · 49 en archivo"}</Eyebrow>
              <h2 className="serif" style={{
                fontStyle:"italic", fontWeight: 300, fontSize:"clamp(1.8rem, 3.6vw, 2.8rem)",
                color: theme.text, marginTop:".5rem", letterSpacing:"-.01em",
              }}>{lang==="en"
                ? <>Editions, <em>narrated.</em></>
                : <>Ediciones, <em>narradas.</em></>}</h2>
            </div>
            <span className="mono" style={{ fontSize:".74rem", color: theme.text3 }}>
              {lang==="en"?"12–20 min avg · WiseTip+":"12–20 min media · WiseTip+"}
            </span>
          </div>

          <div className="grid-3" style={{ gap:"1rem" }}>
            {WS_PODCAST_EPISODES.slice(0, 6).map((ep, i) => {
              const editor = WS_EDITORS.find(e => e.id === ep.editor);
              return (
                <AudioCard key={i} ep={ep} editor={editor} theme={theme} dark={dark} lang={lang} isMember={isMember}
                  onPlay={() => setNow(`book-${i}`)} playing={now === `book-${i}`}/>
              );
            })}
          </div>
        </div>
      </section>

      {/* ── PODCAST · 3 LAYERS ── */}
      <section id="podcast" style={{
        background: dark ? theme.panel : "#0E2318",
        color:"#F0EBE0", padding:"5rem clamp(1.5rem, 5vw, 5vw)",
        position:"relative", overflow:"hidden",
      }}>
        <div aria-hidden style={{
          position:"absolute", inset: 0,
          background:"radial-gradient(ellipse 60% 50% at 80% 100%, rgba(125,190,90,.12) 0%, transparent 60%)",
        }}/>
        <Grain amount={.04}/>

        <div className="wrap" style={{ position:"relative", zIndex: 1 }}>
          <div style={{ maxWidth: 720, marginBottom:"3rem" }}>
            <Pill color="#C8A85A" bd="#C8A85A66" style={{ marginBottom: "1.25rem" }}>
              ◉ {lang==="en"?"WiseTip Podcast · new":"WiseTip Podcast · nuevo"}
            </Pill>
            <h2 className="serif" style={{
              fontStyle:"italic", fontWeight: 300,
              fontSize:"clamp(2rem, 4.5vw, 3.6rem)",
              color:"#F0EBE0", lineHeight: 1.04, marginBottom:"1rem",
              letterSpacing:"-.02em",
            }}>{lang==="en"
              ? <>One feed. Three ways <em style={{ color:"#9DC872" }}>to listen.</em></>
              : <>Un feed. Tres formas <em style={{ color:"#9DC872" }}>de escuchar.</em></>}</h2>
            <p style={{ color:"rgba(240,235,224,.6)", fontSize:"1.02rem", lineHeight: 1.7, fontWeight: 300, maxWidth: 540 }}>
              {lang==="en"
                ? "The weekly is for the rhythm. Themed seasons are for catching up. Tailor-on-request is for when only your story will do — pick a theme, an editor's voice, a length, and we'll stitch you a private episode from the archive."
                : "El semanal marca el ritmo. Las temporadas para ponerte al día. A medida para cuando solo tu historia sirve — elige tema, voz y duración y montamos un episodio privado del archivo."}
            </p>
          </div>

          {/* layer tabs */}
          <div style={{
            display:"flex", gap: 6, marginBottom:"2rem",
            borderBottom:"1px solid rgba(255,255,255,.08)", paddingBottom: "1rem",
            flexWrap:"wrap",
          }}>
            {WS_PODCAST_LAYERS.map(l => (
              <button key={l.id} onClick={() => setLayer(l.id)} style={{
                background: layer === l.id ? "rgba(125,190,90,.14)" : "transparent",
                color: layer === l.id ? "#F0EBE0" : "rgba(240,235,224,.55)",
                border: `1px solid ${layer === l.id ? "#9DC872" : "rgba(255,255,255,.1)"}`,
                padding:"10px 18px", borderRadius: 24,
                fontSize:".82rem", fontWeight: 500, cursor:"pointer",
                display:"flex", alignItems:"center", gap: 8,
              }}>
                <span style={{ fontSize:".64rem", letterSpacing:".18em", color:"#9DC872" }}>
                  {l.eyebrow[lang].split("·")[0]}
                </span>
                {l.title[lang].split(/[·—]/)[0].trim()}
              </button>
            ))}
          </div>

          {/* layer detail panel */}
          {(() => {
            const L = WS_PODCAST_LAYERS.find(x => x.id === layer);
            return (
              <div style={{ display:"grid", gridTemplateColumns: "1fr 1fr", gap:"3rem", alignItems:"start" }} className="grid-2">
                <div>
                  <div className="label-tiny" style={{ color:"#9DC872", marginBottom: 10 }}>{L.eyebrow[lang]}</div>
                  <h3 className="serif italic" style={{
                    fontWeight: 300, fontSize:"clamp(1.6rem, 3vw, 2.4rem)",
                    color:"#F0EBE0", lineHeight: 1.1, marginBottom:"1.25rem", letterSpacing:"-.01em",
                  }}>{L.title[lang]}</h3>
                  <p style={{ color:"rgba(240,235,224,.65)", fontSize:".96rem", lineHeight: 1.75, fontWeight: 300, marginBottom:"1.25rem" }}>
                    {L.body[lang]}
                  </p>
                  <div className="mono" style={{ fontSize:".7rem", color:"rgba(240,235,224,.4)" }}>
                    {L.meta[lang]}
                  </div>
                </div>

                {/* right content depends on layer */}
                {layer === "ondemand"
                  ? <TailorPodcastForm theme={theme} dark={dark} lang={lang} isMember={isMember}/>
                  : <PodcastList episodes={WS_PODCAST_EPISODES.filter((_, i) => layer === "seasonal" ? i >= 2 : true)}
                                 theme={theme} dark={dark} lang={lang} isMember={isMember}
                                 now={now} setNow={setNow}/>}
              </div>
            );
          })()}
        </div>
      </section>

      {/* TAILOR AUDIOBOOK CROSSLINK */}
      <section style={{ padding:"4rem clamp(1.5rem, 5vw, 5vw)", background: theme.bg }}>
        <div className="wrap" style={{
          background: theme.sage3, border:`1px dashed ${theme.border2}`,
          borderRadius: 8, padding:"2rem 2.25rem",
          display:"flex", justifyContent:"space-between", alignItems:"center", gap:"2rem", flexWrap:"wrap",
        }}>
          <div>
            <div className="label-tiny" style={{ color: theme.sage, marginBottom: 6 }}>
              {lang==="en"?"Different from podcast":"Distinto del podcast"}
            </div>
            <h3 className="serif" style={{
              fontStyle:"italic", fontWeight: 400, fontSize:"1.5rem", color: theme.text,
              marginBottom: 4,
            }}>{lang==="en"
              ? <>TailorAudioBooks · an <em>original</em> story for your child.</>
              : <>TailorAudioBooks · una historia <em>original</em> para tu hijo.</>}</h3>
            <p style={{ color: theme.text2, fontSize:".88rem", fontWeight: 300, maxWidth: 560 }}>
              {lang==="en"
                ? "Where the podcast curates the archive, TailorAudioBooks writes new fiction with your child's name — linear, branching, or as a 3-episode series."
                : "Mientras el podcast cura el archivo, TailorAudioBooks escribe ficción nueva con el nombre de tu hijo — lineal, con ramas o en serie de 3 episodios."}
            </p>
          </div>
          <button onClick={() => nav("tailor")} style={{
            background: theme.sage, color: dark?"#050F07":"#fff",
            border:"none", padding:"12px 22px", borderRadius: 24,
            fontSize:".84rem", fontWeight: 600, cursor:"pointer", whiteSpace:"nowrap",
          }}>{lang==="en"?"Build a story →":"Crear historia →"}</button>
        </div>
      </section>
    </div>
  );
}

function AudioCard({ ep, editor, theme, dark, lang, isMember, onPlay, playing }) {
  const isLocked = ep.tier === "premium" && !isMember;
  return (
    <article style={{
      background: dark ? theme.panel : "#fff",
      border: `1px solid ${theme.border}`, borderRadius: 6,
      padding:"1.4rem 1.3rem",
      display:"flex", flexDirection:"column", gap:".85rem",
      position:"relative",
    }}>
      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start" }}>
        <span className="mono" style={{ fontSize:".66rem", color: theme.text3, letterSpacing:".06em" }}>
          {ep.num} · {ep.date}
        </span>
        <Pill color={ep.tier === "premium" ? theme.gold : theme.sage}
              bd={`${ep.tier === "premium" ? theme.gold : theme.sage}55`} size=".58rem">
          {ep.tier === "premium" ? "WiseTip+" : "Free"}
        </Pill>
      </div>

      <h3 className="serif" style={{
        fontStyle:"italic", fontWeight: 400, fontSize:"1.25rem",
        color: theme.text, lineHeight: 1.2,
      }}>{ep.title[lang]}</h3>

      <div style={{ display:"flex", alignItems:"center", gap: 10, paddingTop:".25rem" }}>
        <span style={{
          width: 26, height: 26, borderRadius: "50%",
          background: `${editor.color}28`, border:`1px solid ${editor.color}55`,
          display:"inline-flex", alignItems:"center", justifyContent:"center",
          fontFamily:"'Cormorant Garamond',serif", color: editor.color, fontSize:".82rem",
        }}>{editor.name[0]}</span>
        <span style={{ fontSize:".78rem", color: theme.text2 }}>{editor.name}</span>
        <span className="mono" style={{ fontSize:".7rem", color: theme.text3, marginLeft:"auto" }}>
          {ep.duration}
        </span>
      </div>

      <div style={{ display:"flex", alignItems:"center", gap: 12, padding:".75rem 0",
        borderTop:`1px solid ${theme.divider}`, marginTop:".25rem",
      }}>
        <button onClick={onPlay} disabled={isLocked} style={{
          width: 34, height: 34, borderRadius:"50%",
          background: isLocked ? theme.locked : theme.sage,
          color: isLocked ? theme.gold : (dark?"#050F07":"#fff"),
          border: isLocked ? `1px solid ${theme.gold}` : "none",
          display:"flex", alignItems:"center", justifyContent:"center",
          cursor: isLocked ? "not-allowed" : "pointer",
        }}>{isLocked ? "🔒" : playing ? "❚❚" : "▶"}</button>
        {playing ? (
          <Waveform color={theme.sage} bars={26} height={26}/>
        ) : (
          <span style={{ fontSize:".82rem", color: theme.text3, fontStyle:"italic" }}>
            {isLocked ? (lang==="en"?"Unlock with WiseTip+":"Desbloquea con WiseTip+") : (lang==="en"?"Tap to listen":"Toca para escuchar")}
          </span>
        )}
      </div>
    </article>
  );
}

function PodcastList({ episodes, theme, dark, lang, isMember, now, setNow }) {
  return (
    <div style={{
      background:"rgba(8,15,10,.5)", border:"1px solid rgba(125,190,90,.18)",
      borderRadius: 6, overflow:"hidden",
    }}>
      {episodes.map((ep, i) => {
        const editor = WS_EDITORS.find(e => e.id === ep.editor);
        const id = `pod-${ep.num}-${i}`;
        const playing = now === id;
        const isLocked = ep.tier === "premium" && !isMember;
        return (
          <div key={id} style={{
            display:"grid", gridTemplateColumns:"auto 1fr auto auto", gap:"1rem", alignItems:"center",
            padding:"1rem 1.25rem",
            borderBottom: i === episodes.length - 1 ? "none" : "1px solid rgba(255,255,255,.05)",
          }}>
            <button onClick={() => setNow(playing ? null : id)} disabled={isLocked} style={{
              width: 32, height: 32, borderRadius:"50%",
              background: isLocked ? "rgba(200,168,90,.12)" : "#9DC872",
              color: isLocked ? "#C8A85A" : "#050F07",
              border:"none", cursor: isLocked ? "not-allowed" : "pointer",
              display:"flex", alignItems:"center", justifyContent:"center",
            }}>{isLocked ? "🔒" : playing ? "❚❚" : "▶"}</button>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize:".88rem", color:"#F0EBE0", fontWeight: 500, marginBottom: 2,
                overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>
                {ep.title[lang]}
              </div>
              <div style={{ fontSize:".7rem", color:"rgba(240,235,224,.45)" }}>
                <span className="mono">{ep.num}</span> · {editor.name} · {ep.date}
              </div>
            </div>
            {playing
              ? <Waveform color="#9DC872" bars={14} height={20}/>
              : <span className="mono" style={{ fontSize:".7rem", color:"rgba(240,235,224,.4)" }}>{ep.duration}</span>}
            <Pill color={ep.tier === "premium" ? "#C8A85A" : "#9DC872"}
                  bd={ep.tier === "premium" ? "#C8A85A66" : "#9DC87266"} size=".58rem">
              {ep.tier === "premium" ? "+" : "free"}
            </Pill>
          </div>
        );
      })}
    </div>
  );
}

// ── TAILOR-ON-REQUEST PODCAST FORM ─────────────────────────
function TailorPodcastForm({ theme, dark, lang, isMember }) {
  // Surfaces the three podcast format types from WiseTip Audio System §2.3:
  // narrative (single narrator) · multivoice (host + cast) · episodic (3-part series).
  const [format, setFormat] = useState("narrative");
  const [theme_, setTheme_] = useState(lang==="en"?"Winter without screens":"Invierno sin pantallas");
  const [voice, setVoice] = useState("markus");
  const [length, setLength] = useState(25);
  const [sent, setSent] = useState(false);

  const formats = [
    { id: "narrative",  glyph: "🎙", t: { en: "Narrative",  es: "Narrativo" },
      sub: { en: "Single narrator. Reflective or non-fiction prose, read aloud.",
             es: "Un solo narrador. Reflexivo o no-ficción, en voz alta." } },
    { id: "multivoice", glyph: "🎭", t: { en: "Multi-voice", es: "Multi-voz" },
      sub: { en: "Host + guest format. Two or more ElevenLabs voices in dialogue.",
             es: "Anfitrión + invitado. Dos o más voces ElevenLabs en diálogo." } },
    { id: "episodic",  glyph: "📼", t: { en: "Episodic",   es: "Episódico" },
      sub: { en: "Three-part series: setup → development → resolution. Each stands alone.",
             es: "Serie en tres partes: planteamiento → desarrollo → resolución. Cada parte se sostiene sola." } },
  ];

  const themes = lang === "en"
    ? ["Winter without screens", "Hard conversations", "Bedtime", "Siblings", "Travel days", "First days at school"]
    : ["Invierno sin pantallas", "Conversaciones difíciles", "Antes de dormir", "Hermanos", "Días de viaje", "Primer día de cole"];

  return (
    <div style={{
      background:"rgba(8,15,10,.5)", border:"1px solid rgba(125,190,90,.18)",
      borderRadius: 6, padding:"1.75rem",
    }}>
      <div className="label-tiny" style={{ color:"#9DC872", marginBottom: 6 }}>
        {lang==="en"?"Request a private episode":"Pide un episodio privado"}
      </div>
      <div className="serif italic" style={{ fontSize:"1.15rem", color:"#F0EBE0", marginBottom:"1.25rem" }}>
        {lang==="en"?"Four choices. We do the rest.":"Cuatro elecciones. Nosotros hacemos el resto."}
      </div>

      {/* 1 · format type — from spec §2.3 */}
      <div style={{ marginBottom:"1.25rem" }}>
        <div className="label-tiny" style={{ color:"rgba(240,235,224,.45)", marginBottom: 6 }}>
          {lang==="en"?"1. Format":"1. Formato"}
        </div>
        <div className="podcast-format-grid" style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap: 6 }}>
          {formats.map(fm => (
            <button key={fm.id} onClick={() => setFormat(fm.id)} style={{
              background: format === fm.id ? "rgba(125,190,90,.14)" : "rgba(255,255,255,.03)",
              border: `1px solid ${format === fm.id ? "#9DC872" : "rgba(255,255,255,.1)"}`,
              color:"#F0EBE0", padding:"10px 12px", borderRadius: 6,
              cursor:"pointer", textAlign:"left", display:"flex", flexDirection:"column", gap: 4,
            }}>
              <span style={{ fontSize:".88rem" }}>{fm.glyph} <span style={{ fontWeight: 500 }}>{fm.t[lang]}</span></span>
              <span style={{ fontSize:".66rem", color:"rgba(240,235,224,.55)", lineHeight: 1.4 }}>{fm.sub[lang]}</span>
            </button>
          ))}
        </div>
      </div>
      <style>{`@media (max-width: 540px) { .podcast-format-grid { grid-template-columns: 1fr !important; } }`}</style>

      {/* 2 · theme */}
      <div style={{ marginBottom:"1rem" }}>
        <div className="label-tiny" style={{ color:"rgba(240,235,224,.45)", marginBottom: 6 }}>
          {lang==="en"?"2. Theme":"2. Tema"}
        </div>
        <div style={{ display:"flex", gap: 6, flexWrap:"wrap" }}>
          {themes.map(t => (
            <button key={t} onClick={() => setTheme_(t)} style={{
              background: theme_ === t ? "rgba(125,190,90,.18)" : "rgba(255,255,255,.03)",
              border: `1px solid ${theme_ === t ? "#9DC872" : "rgba(255,255,255,.1)"}`,
              color: theme_ === t ? "#F0EBE0" : "rgba(240,235,224,.55)",
              padding:"5px 12px", borderRadius: 14,
              fontSize:".72rem", cursor:"pointer",
            }}>{t}</button>
          ))}
        </div>
      </div>

      {/* voice */}
      <div style={{ marginBottom:"1rem" }}>
        <div className="label-tiny" style={{ color:"rgba(240,235,224,.45)", marginBottom: 6 }}>
          {lang==="en" ? (format==="multivoice"?"3. Host voice":"3. Voice") : (format==="multivoice"?"3. Voz anfitrión":"3. Voz")}
        </div>
        <div style={{ display:"flex", gap: 6, flexWrap:"wrap" }}>
          {WS_EDITORS.map(ed => (
            <button key={ed.id} onClick={() => setVoice(ed.id)} style={{
              background: voice === ed.id ? `${ed.color}24` : "rgba(255,255,255,.03)",
              border: `1px solid ${voice === ed.id ? ed.color : "rgba(255,255,255,.1)"}`,
              color: voice === ed.id ? "#F0EBE0" : "rgba(240,235,224,.55)",
              padding:"5px 12px", borderRadius: 14,
              fontSize:".72rem", cursor:"pointer",
              display:"flex", alignItems:"center", gap: 6,
            }}>
              <span style={{
                width: 12, height: 12, borderRadius:"50%", background: ed.color,
                display:"inline-block", border:"1px solid rgba(255,255,255,.2)",
              }}/>
              {ed.name}
            </button>
          ))}
        </div>
      </div>

      {/* length */}
      <div style={{ marginBottom:"1.25rem" }}>
        <div className="label-tiny" style={{ color:"rgba(240,235,224,.45)", marginBottom: 6 }}>
          {lang==="en" ? `4. Length · ${format==="episodic" ? `3 × ${Math.round(length/3)} min` : `${length} min`}` : `4. Duración · ${format==="episodic" ? `3 × ${Math.round(length/3)} min` : `${length} min`}`}
        </div>
        <input type="range" min={10} max={60} step={5} value={length}
          onChange={e => setLength(+e.target.value)}
          style={{ width:"100%", accentColor:"#9DC872" }}/>
      </div>

      {/* submit */}
      {sent ? (
        <div style={{
          padding:"1rem", background:"rgba(125,190,90,.12)",
          border:"1px solid #9DC872", borderRadius: 4,
          fontSize:".82rem", color:"#F0EBE0",
        }}>
          ✓ {lang==="en"
               ? `Got it. Your ${format === "episodic" ? "3-episode series" : format === "multivoice" ? "multi-voice episode" : "narrative episode"} on "${theme_}" arrives within 24h to your library.`
               : `Recibido. Tu ${format === "episodic" ? "serie de 3 episodios" : format === "multivoice" ? "episodio multi-voz" : "episodio narrativo"} sobre «${theme_}» llega en 24h a tu biblioteca.`}
        </div>
      ) : (
        <button onClick={() => isMember ? setSent(true) : null}
          disabled={!isMember}
          style={{
            width:"100%", background: isMember ? "#9DC872" : "rgba(125,190,90,.16)",
            color: isMember ? "#050F07" : "rgba(240,235,224,.5)",
            border:"none", padding:"12px 16px", borderRadius: 24,
            fontSize:".86rem", fontWeight: 600, cursor: isMember ? "pointer" : "not-allowed",
          }}>
          {isMember
            ? (lang==="en"?"Request episode · €4.99 / free with WiseTip+":"Pedir episodio · 4,99 € / gratis con WiseTip+")
            : (lang==="en"?"WiseTip+ members only":"Solo miembros WiseTip+")}
        </button>
      )}
    </div>
  );
}

Object.assign(window, { Audiobooks });
