// ── What WiseTip Includes · Weekly Ritual · TailorAudioBooks ────

// ─────────────────────────────────────────────────────────────
// WHAT WISETIP INCLUDES (Products layer)
function Products({ theme, dark, lang, nav }) {
  const items = WS_PRODUCTS;
  const N = nav || (() => {});
  const targets = { weekly:"home", activities:"activities", audiobooks:"audiobooks", tailor:"tailor", packs:"packs", membership:"membership" };
  const tierBadge = {
    free:     { label: { en:"Free forever",  es:"Gratis siempre" }, c: theme.sage },
    freemium: { label: { en:"Free + premium",es:"Gratis + premium" }, c: theme.sage },
    premium:  { label: { en:"WiseTip+",      es:"WiseTip+" },        c: theme.gold },
    paid:     { label: { en:"Pay per item",  es:"Pago por unidad" }, c: theme.gold },
    dual:     { label: { en:"Pay per item · or WiseTip+", es:"Pago único · o WiseTip+" }, c: theme.gold },
  };

  return (
    <section id="includes" className="section" style={{ background: dark ? theme.bg2 : theme.bg2 }}>
      <div className="wrap">
        {/* header */}
        <div style={{ maxWidth: 760, marginBottom: "3.5rem" }}>
          <Eyebrow theme={theme}>{lang==="en"?"What WiseTip includes":"Qué incluye WiseTip"}</Eyebrow>
          <h2 className="serif" style={{
            fontStyle:"italic", fontWeight: 300,
            fontSize:"clamp(2rem, 4.2vw, 3.4rem)",
            color: theme.text, marginTop: ".5rem", marginBottom: "1rem",
            letterSpacing:"-.01em", lineHeight: 1.05,
          }}>{lang==="en"
            ? <>Six pieces. <em style={{ color: theme.text2 }}>One quiet system.</em></>
            : <>Seis piezas. <em style={{ color: theme.text2 }}>Un sistema tranquilo.</em></>}</h2>
          <p style={{
            color: theme.text2, fontSize: "1.05rem", lineHeight: 1.7,
            fontWeight: 300, maxWidth: 580,
          }}>
            {lang==="en"
              ? "WiseTip is not a blog. It is a library, a ritual, and a small set of tools — designed to work together over years, not minutes."
              : "WiseTip no es un blog. Es una biblioteca, un ritual y un pequeño conjunto de herramientas — diseñado para funcionar junto durante años, no minutos."}
          </p>
        </div>

        {/* product grid */}
        <div className="grid-3" style={{ gap: 1, background: theme.border, border:`1px solid ${theme.border}`, borderRadius: 4, overflow:"hidden" }}>
          {items.map((p, i) => {
            const tb = tierBadge[p.tier];
            return (
              <button key={p.id} onClick={() => N(targets[p.id])} style={{
                padding:"2rem 1.75rem",
                background: dark ? theme.panel : "#fff",
                color: "inherit",
                display:"flex", flexDirection:"column", gap:"1.25rem",
                minHeight: 280,
                transition:"background .3s",
                position:"relative", overflow:"hidden",
                border:"none", textAlign:"left", cursor:"pointer",
                font:"inherit",
              }}
              onMouseEnter={e => e.currentTarget.style.background = dark ? theme.panel2 : theme.bg2}
              onMouseLeave={e => e.currentTarget.style.background = dark ? theme.panel : "#fff"}>
                {/* glyph + tier */}
                <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start" }}>
                  <span className="serif" style={{
                    fontSize:"3rem", fontWeight: 300, color: theme.sage,
                    lineHeight: .8, fontStyle:"italic",
                  }}>{p.glyph}</span>
                  <Pill color={tb.c} bd={`${tb.c}55`}>{tb.label[lang]}</Pill>
                </div>

                <div>
                  <h3 className="serif" style={{
                    fontSize:"1.5rem", color: theme.text, fontWeight: 400,
                    lineHeight: 1.15, marginBottom: 6,
                  }}>{p.title[lang]}</h3>
                  <div style={{ fontSize:".88rem", color: theme.text2, fontWeight: 300, fontStyle:"italic" }}>
                    {p.subtitle[lang]}
                  </div>
                </div>

                <p style={{
                  fontSize:".88rem", lineHeight: 1.65,
                  color: theme.text2, fontWeight: 300, flex: 1,
                }}>{p.body[lang]}</p>

                <div style={{
                  display:"flex", justifyContent:"space-between", alignItems:"center",
                  paddingTop:".75rem", borderTop: `1px solid ${theme.divider}`,
                }}>
                  <span className="mono" style={{ fontSize:".7rem", color: theme.text3 }}>
                    {p.meta[lang]}
                  </span>
                  <span style={{ fontSize:".8rem", color: theme.sage }}>→</span>
                </div>
              </button>
            );
          })}
        </div>

        {/* bottom note */}
        <div style={{ marginTop: "2.5rem", textAlign:"center" }}>
          <span className="serif italic" style={{ fontSize:"1.05rem", color: theme.text2 }}>
            {lang==="en"
              ? "Use one piece. Use them all. The system holds you, not the other way around."
              : "Usa una pieza. Úsalas todas. El sistema te sostiene a ti, no al revés."}
          </span>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// WEEKLY RITUAL — how families use WiseTip
function Ritual({ theme, dark, lang }) {
  const steps = WS_RITUAL;
  return (
    <section id="ritual" className="section" style={{
      background: dark
        ? `linear-gradient(180deg, ${theme.bg} 0%, ${theme.bg2} 100%)`
        : `linear-gradient(180deg, ${theme.bg} 0%, ${theme.bg3} 100%)`,
    }}>
      <div className="wrap">
        <div style={{ maxWidth: 760, marginBottom: "3.5rem" }}>
          <Eyebrow theme={theme}>{lang==="en"?"How families use WiseTip":"Cómo lo usan las familias"}</Eyebrow>
          <h2 className="serif" style={{
            fontStyle:"italic", fontWeight: 300,
            fontSize:"clamp(2rem, 4.2vw, 3.4rem)",
            color: theme.text, marginTop: ".5rem", marginBottom: "1rem",
            letterSpacing:"-.01em", lineHeight: 1.05,
          }}>{lang==="en"
            ? <>Twice a week. <em>Every week.</em><br/>Then it repeats.</>
            : <>Dos veces a la semana. <em>Cada semana.</em><br/>Después se repite.</>}</h2>
          <p style={{ color: theme.text2, fontSize:"1.05rem", lineHeight: 1.7, fontWeight: 300, maxWidth: 560 }}>
            {lang==="en"
              ? "No streaks. No badges. No notifications begging for attention. The rhythm is yours — these are the five moments most members fall into naturally."
              : "Sin rachas. Sin insignias. Sin notificaciones que piden tu atención. El ritmo es tuyo — estos son los cinco momentos en los que la mayoría de miembros cae de forma natural."}
          </p>
        </div>

        {/* flow grid with connecting line */}
        <div style={{ position:"relative" }}>
          {/* connecting horizontal line on desktop */}
          <div aria-hidden style={{
            position:"absolute", top: 38, left: "12%", right: "12%", height: 1,
            background: `repeating-linear-gradient(to right, ${theme.border2} 0 6px, transparent 6px 12px)`,
            zIndex: 0,
          }} className="ritual-line"/>

          <div className="flow-grid" style={{ position:"relative", zIndex: 1 }}>
            {steps.map((s, i) => (
              <div key={i} style={{
                padding: "1.5rem clamp(1rem, 2vw, 1.75rem)",
                display:"flex", flexDirection:"column", alignItems:"flex-start", gap: "1rem",
                borderLeft: i === 0 ? "none" : `1px solid ${theme.divider}`,
                position:"relative",
              }}>
                {/* number dot */}
                <div style={{
                  width: 60, height: 60, borderRadius: "50%",
                  background: dark ? theme.bg : theme.bg,
                  border: `1px solid ${theme.border2}`,
                  display:"flex", alignItems:"center", justifyContent:"center",
                  color: theme.sage, fontSize:"1.25rem", fontWeight: 400,
                  fontFamily:"'Cormorant Garamond', serif",
                  position:"relative", zIndex: 2,
                }}>
                  <span style={{ position:"absolute", inset:6, borderRadius:"50%", border:`1px dashed ${theme.border2}` }}/>
                  {String(i + 1).padStart(2, "0")}
                </div>

                <div>
                  <div className="label-tiny" style={{ color: theme.sage, marginBottom: 6 }}>
                    {lang==="en" ? s.step : s.es_step}
                  </div>
                  <h3 className="serif" style={{
                    fontSize: "1.45rem", color: theme.text, fontWeight: 400,
                    lineHeight: 1.15, marginBottom: 8,
                  }}>{s.title[lang]}</h3>
                  <p style={{
                    fontSize: ".9rem", color: theme.text2,
                    lineHeight: 1.6, fontWeight: 300, marginBottom: ".75rem",
                  }}>{s.body[lang]}</p>
                  <div style={{
                    fontSize: ".7rem", color: theme.gold,
                    display:"inline-flex", alignItems:"center", gap: 6,
                    padding:"3px 10px", borderRadius: 12,
                    background: theme.gold2, border: `1px solid ${theme.gold}40`,
                  }}>
                    <span>↳</span> {s.product[lang]}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* loop indicator at bottom */}
        <div style={{
          marginTop: "2.5rem", display:"flex", justifyContent:"center", alignItems:"center", gap: 14,
        }}>
          <span style={{ width: 60, height: 1, background: theme.divider }}/>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={theme.sage} strokeWidth="1.4">
            <path d="M3 12a9 9 0 1 0 3-6.7M3 4v5h5"/>
          </svg>
          <span className="serif italic" style={{ fontSize: "1rem", color: theme.text2 }}>
            {lang==="en" ? `and again, next Tuesday — ${WS_CURRENT && WS_CURRENT.num || 197} editions deep` : `y de nuevo, el próximo martes — ${WS_CURRENT && WS_CURRENT.num || 197} ediciones`}
          </span>
          <span style={{ width: 60, height: 1, background: theme.divider }}/>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// TAILORAUDIOBOOKS — featured secondary product
function TailorHero({ theme, dark, lang }) {
  const [name, setName] = useState("Lola");
  const [age, setAge] = useState(5);
  const [trait, setTrait] = useState(lang === "en" ? "loves stones" : "le encantan las piedras");
  const [format, setFormat] = useState("linear");
  const [building, setBuilding] = useState(false);
  const [done, setDone] = useState(false);

  useEffect(() => {
    setTrait(lang === "en" ? "loves stones" : "le encantan las piedras");
  }, [lang]);

  const formats = [
    { id: "linear", icon: "—", label: { en: "Linear",   es: "Lineal" },  meta: { en: "single arc, one ending", es: "un arco, un final" } },
    { id: "branch", icon: "Y", label: { en: "Branching",es: "Con ramas" }, meta: { en: "two paths, two audios", es: "dos rutas, dos audios" } },
    { id: "series", icon: "≡", label: { en: "Series",   es: "Serie" },     meta: { en: "3 connected episodes", es: "3 episodios conectados" } },
  ];

  const handleGenerate = () => {
    setBuilding(true); setDone(false);
    setTimeout(() => { setBuilding(false); setDone(true); }, 2200);
  };

  const previewTitle = lang === "en"
    ? `${name} and the Mint That Survived Winter`
    : `${name} y la Menta Que Sobrevivió al Invierno`;

  return (
    <section id="tailor" className="section" style={{
      background: dark ? theme.panel : "#1E4128",
      color: "#F0EBE0", position:"relative", overflow:"hidden",
    }}>
      {/* atmospheric backdrop */}
      <div aria-hidden style={{
        position:"absolute", inset:0,
        background: `radial-gradient(ellipse 60% 50% at 80% 20%, rgba(125,190,90,.18) 0%, transparent 60%),
                     radial-gradient(ellipse 50% 40% at 20% 80%, rgba(200,168,90,.1) 0%, transparent 55%)`,
      }}/>
      <Grain amount={.04}/>

      <div className="wrap" style={{ position:"relative", zIndex: 1 }}>
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"4rem", alignItems:"center" }} className="tailor-grid">
          {/* LEFT — pitch */}
          <div>
            <Pill color="#C8A85A" bd="#C8A85A66" style={{ marginBottom: "1.5rem" }}>
              ⌁ {lang==="en"?"Hero product":"Producto destacado"}
            </Pill>
            <h2 className="serif" style={{
              fontStyle:"italic", fontWeight: 300,
              fontSize:"clamp(2.2rem, 5vw, 4rem)",
              lineHeight: 1.04, letterSpacing:"-.02em",
              color: "#F0EBE0", marginBottom: "1.5rem",
            }}>
              {lang==="en"
                ? <>An <em style={{ color:"#9DC872" }}>original story</em>,<br/>narrated for your child<br/>by name.</>
                : <>Una <em style={{ color:"#9DC872" }}>historia original</em>,<br/>narrada para tu hijo,<br/>con su nombre.</>}
            </h2>
            <p style={{
              fontSize:"1.05rem", lineHeight: 1.75, fontWeight: 300,
              color:"rgba(240,235,224,.65)", marginBottom:"2rem", maxWidth: 480,
            }}>
              {lang==="en"
                ? "TailorAudioBooks turns any WiseTip theme into a personalised audiobook. You give us the name, age, and a few traits. We give you 5–15 minutes of original, narrated audio — delivered to your library, ready to listen at bedtime."
                : "TailorAudioBooks convierte cualquier tema de WiseTip en un audiolibro personalizado. Tú nos das el nombre, la edad y algunos rasgos. Te damos 5–15 minutos de audio original, narrado — entregado a tu biblioteca, listo para escuchar antes de dormir."}
            </p>

            {/* tiny feature row */}
            <div style={{ display:"grid", gridTemplateColumns:"repeat(3, auto)", gap:"1.25rem 2rem", marginBottom:"2rem" }}>
              {[
                ["5.99€", lang==="en"?"per story":"por historia"],
                ["3", lang==="en"?"audio formats":"formatos audio"],
                ["~12m", lang==="en"?"delivery time":"tiempo entrega"],
              ].map(([n, l]) => (
                <div key={l}>
                  <div className="serif" style={{ fontSize:"1.8rem", fontWeight: 300, color: "#F0EBE0", lineHeight: 1 }}>{n}</div>
                  <div style={{ fontSize:".68rem", color:"rgba(240,235,224,.5)", marginTop: 4 }}>{l}</div>
                </div>
              ))}
            </div>

            <div style={{ display:"flex", gap: 12, flexWrap:"wrap" }}>
              <a href="#tailor-configurator" onClick={(e)=>{e.preventDefault(); document.getElementById("configurator-card")?.scrollIntoView({behavior:"smooth", block:"center"});}} style={{
                background:"#9DC872", color:"#050F07",
                padding:"13px 26px", borderRadius: 30,
                fontSize:".88rem", fontWeight: 600,
              }}>{lang==="en"?"Build a story":"Crear una historia"} →</a>
              <a href="#tailor" style={{
                background:"transparent", color:"rgba(240,235,224,.7)",
                padding:"13px 24px", borderRadius: 30,
                border: "1px solid rgba(240,235,224,.18)", fontSize:".88rem",
              }}>{lang==="en"?"Listen to a sample":"Escuchar una muestra"}</a>
            </div>
          </div>

          {/* RIGHT — mini configurator preview */}
          <div id="configurator-card" style={{
            background: "rgba(8,15,10,.65)",
            backdropFilter:"blur(14px)", WebkitBackdropFilter:"blur(14px)",
            border:"1px solid rgba(125,190,90,.18)",
            borderRadius: 8, padding:"1.75rem",
            boxShadow:"0 20px 60px rgba(0,0,0,.4)",
          }}>
            {/* top tab indicator */}
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:"1.5rem" }}>
              <span className="label-tiny" style={{ color:"#9DC872" }}>TailorAudioBooks · Configurator</span>
              <span className="mono" style={{ fontSize:".64rem", color:"rgba(240,235,224,.3)" }}>Step 3 / 8</span>
            </div>

            {/* form */}
            <div style={{ display:"flex", flexDirection:"column", gap:"1rem" }}>
              <Field label={lang==="en"?"Child's name":"Nombre del niño"} value={name} setValue={setName} name="child-name"/>
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"1rem" }}>
                <NumField label={lang==="en"?"Age":"Edad"} value={age} setValue={setAge} name="child-age"/>
                <Field label={lang==="en"?"A trait":"Un rasgo"} value={trait} setValue={setTrait} name="child-trait"/>
              </div>

              {/* format picker */}
              <div>
                <div className="label-tiny" style={{ color:"rgba(240,235,224,.45)", marginBottom: 8 }}>
                  {lang==="en"?"Story format":"Formato"}
                </div>
                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap: 6 }}>
                  {formats.map(f => (
                    <button key={f.id} onClick={() => setFormat(f.id)} style={{
                      background: format === f.id ? "rgba(125,190,90,.16)" : "rgba(255,255,255,.03)",
                      border: `1px solid ${format === f.id ? "#9DC872" : "rgba(255,255,255,.08)"}`,
                      borderRadius: 4, padding:".75rem .5rem",
                      color: format === f.id ? "#F0EBE0" : "rgba(240,235,224,.55)",
                      display:"flex", flexDirection:"column", gap: 4, alignItems:"flex-start", textAlign:"left",
                    }}>
                      <span style={{ fontSize:"1.1rem", color: format === f.id ? "#9DC872" : "rgba(240,235,224,.4)", fontFamily:"'Cormorant Garamond',serif" }}>{f.icon}</span>
                      <span style={{ fontSize:".78rem", fontWeight: 500 }}>{f.label[lang]}</span>
                      <span style={{ fontSize:".62rem", color:"rgba(240,235,224,.4)" }}>{f.meta[lang]}</span>
                    </button>
                  ))}
                </div>
              </div>

              {/* preview */}
              <div style={{
                marginTop:".5rem",
                background:"rgba(125,190,90,.06)",
                border:"1px dashed rgba(125,190,90,.25)",
                borderRadius: 4, padding:"1rem",
              }}>
                <div className="label-tiny" style={{ color:"#9DC872", marginBottom: 6 }}>
                  {lang==="en"?"Preview title":"Título previa"}
                </div>
                <div className="serif italic" style={{ fontSize:"1.1rem", color:"#F0EBE0", lineHeight: 1.35 }}>
                  "{previewTitle}"
                </div>
                <div style={{ marginTop:".75rem", display:"flex", alignItems:"center", gap:".75rem" }}>
                  {done ? (
                    <>
                      <button style={{
                        width: 30, height: 30, borderRadius:"50%",
                        background:"#9DC872", color:"#050F07", border:"none",
                        display:"flex", alignItems:"center", justifyContent:"center",
                      }}>▶</button>
                      <Waveform color="#9DC872" bars={32} height={28}/>
                      <span className="mono" style={{ fontSize:".68rem", color:"rgba(240,235,224,.5)" }}>14:22</span>
                    </>
                  ) : building ? (
                    <>
                      <span style={{ width:30, height:30, borderRadius:"50%", border:"2px solid rgba(157,200,114,.3)", borderTopColor:"#9DC872", animation:"spin 1s linear infinite", display:"inline-block" }}/>
                      <span style={{ fontSize:".82rem", color:"rgba(240,235,224,.6)" }}>{lang==="en"?"Composing audio…":"Componiendo audio…"}</span>
                    </>
                  ) : (
                    <>
                      <span style={{ width:30, height:30, borderRadius:"50%", background:"rgba(255,255,255,.04)", border:"1px solid rgba(255,255,255,.1)", display:"inline-flex", alignItems:"center", justifyContent:"center", color:"rgba(240,235,224,.4)" }}>▶</span>
                      <span style={{ fontSize:".82rem", color:"rgba(240,235,224,.5)" }}>{lang==="en"?"Ready to generate":"Listo para generar"}</span>
                    </>
                  )}
                </div>
              </div>

              <button onClick={handleGenerate} disabled={building} style={{
                background: done ? "rgba(125,190,90,.16)" : "#9DC872",
                color: done ? "#9DC872" : "#050F07",
                border: done ? "1px solid #9DC872" : "none",
                padding:"12px 16px", borderRadius: 24,
                fontSize:".86rem", fontWeight: 600,
                opacity: building ? .6 : 1, cursor: building ? "wait" : "pointer",
              }}>
                {building ? (lang==="en"?"Generating…":"Generando…") :
                 done    ? (lang==="en"?"Add to library · 5.99€":"Añadir a biblioteca · 5,99 €") :
                           (lang==="en"?"Generate preview":"Generar muestra")}
              </button>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes spin { from { transform: rotate(0deg);} to { transform: rotate(360deg);} }
        @media (max-width: 900px) {
          .tailor-grid { grid-template-columns: 1fr !important; }
          .ritual-line { display: none; }
        }
      `}</style>
    </section>
  );
}

function Field({ label, value, setValue, name }) {
  return (
    <div>
      <div className="label-tiny" style={{ color:"rgba(240,235,224,.45)", marginBottom: 6 }}>{label}</div>
      <input name={name} value={value} onChange={e => setValue(e.target.value)} style={{
        width:"100%", padding:"10px 14px",
        background:"rgba(255,255,255,.04)",
        border:"1px solid rgba(255,255,255,.12)",
        borderRadius: 4, color:"#F0EBE0", fontSize:".9rem", outline:"none",
      }}/>
    </div>
  );
}
function NumField({ label, value, setValue, name }) {
  return (
    <div>
      <div className="label-tiny" style={{ color:"rgba(240,235,224,.45)", marginBottom: 6 }}>{label}</div>
      <input type="number" name={name} min={2} max={17} value={value} onChange={e => setValue(+e.target.value)} style={{
        width:"100%", padding:"10px 14px",
        background:"rgba(255,255,255,.04)",
        border:"1px solid rgba(255,255,255,.12)",
        borderRadius: 4, color:"#F0EBE0", fontSize:".9rem", outline:"none",
      }}/>
    </div>
  );
}

Object.assign(window, { Products, Ritual, TailorHero });
