// ── ACTIVITIES BY CATEGORY · page ───────────────────────────
// Presents the full activity catalog grouped the way the WiseTip taxonomy
// works: by the season-axis categories (Seasons / Holidays / Moments), then
// a second pass grouped by accessibility & need. Every category shows its set.

const { useState: useCat } = React;

function tagOf(id) { return (window.WS_SEASON_TAGS || []).find(t => t.id === id); }
function needOf(id) { return (window.WS_NEEDS_TAGS || []).find(t => t.id === id); }

function ActivityCatalog(props) {
  // Dual-mode: router props in-app, own state as standalone "Activities by Category.html".
  const inApp = !!(props && props.nav);
  const goTo = inApp ? props.nav : null;
  const [langS, setLangS] = useCat("en");
  const [darkS, setDarkS] = useCat(true);
  const [tier, setTier] = useCat("all"); // all | free | premium  (always local)

  const lang = inApp ? props.lang : langS;
  const setLang = inApp ? (props.setLang || (() => {})) : setLangS;
  const dark = inApp ? props.dark : darkS;
  const theme = inApp ? props.theme : (dark ? window.WS_DARK : window.WS_LIGHT);

  const all = window.WS_CATALOG;
  const groups = window.WS_CATALOG_GROUPS;
  const publicNeeds = (window.WS_NEEDS_TAGS || []).filter(t => !t.sensitive);

  const tierOk = (a) => tier === "all" || a.tier === tier;
  const total = all.filter(tierOk).length;

  const nav = [
    ...groups.map(g => ({ id: g.id, label: g.label[lang] })),
    { id: "needs", label: lang === "en" ? "By need" : "Por necesidad" },
  ];

  return (
    <div style={{ background: theme.bg, color: theme.text, minHeight: "100vh" }}>
      <style>{window.WS_FONT_CSS}</style>
      <style>{`.cat-scroll::-webkit-scrollbar{height:6px}.cat-scroll::-webkit-scrollbar-thumb{background:${theme.border2};border-radius:3px}`}</style>

      {/* CONTROL BAR — standalone only (the app supplies its own global Nav) */}
      {!inApp && <div style={{
        position: "sticky", top: 0, zIndex: 30,
        background: theme.navBg, backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)",
        borderBottom: `1px solid ${theme.border}`,
        padding: ".8rem clamp(1.25rem, 5vw, 3rem)",
        display: "flex", alignItems: "center", justifyContent: "space-between", gap: "1rem", flexWrap: "wrap",
      }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
          <span className="serif italic" style={{ fontSize: "1.3rem", color: theme.text, fontWeight: 500 }}>WiseTip</span>
          <span style={{ width: 4, height: 4, borderRadius: "50%", background: theme.sage, display: "inline-block" }}/>
          <span className="label-tiny" style={{ color: theme.sage }}>{lang === "en" ? "Activity system" : "Sistema de actividades"}</span>
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <CatSeg theme={theme} dark={dark} value={tier} onChange={setTier} options={[["all", lang === "en" ? "All" : "Todo"], ["free", "Free"], ["premium", "WiseTip+"]]}/>
          <CatSeg theme={theme} dark={dark} value={lang} onChange={setLang} options={[["en", "EN"], ["es", "ES"]]}/>
          <button onClick={() => setDarkS(!dark)} style={{ background: theme.sage3, border: `1px solid ${theme.border2}`, borderRadius: 16, color: theme.text2, padding: "6px 12px", fontSize: ".74rem" }}>{dark ? "☾" : "☀"}</button>
        </div>
      </div>}

      {/* HERO */}
      <header style={{
        position: "relative", overflow: "hidden",
        background: dark
          ? `radial-gradient(ellipse 60% 60% at 18% 100%, #163E1E 0%, transparent 58%), linear-gradient(180deg, #0A1A10 0%, ${theme.bg} 100%)`
          : `radial-gradient(ellipse 60% 60% at 18% 100%, #C8DAB8 0%, transparent 58%), linear-gradient(180deg, ${theme.bg2} 0%, ${theme.bg} 100%)`,
        padding: "clamp(3rem, 8vh, 5.5rem) clamp(1.5rem, 5vw, 5vw) clamp(2rem, 5vh, 3.5rem)",
      }}>
        <div className="wrap" style={{ position: "relative" }}>
          <Eyebrow theme={theme}>{lang === "en" ? `Activities · ${total} · a set per category` : `Actividades · ${total} · un set por categoría`}</Eyebrow>
          <h1 className="serif" style={{
            fontStyle: "italic", fontWeight: 300, fontSize: "clamp(2.2rem, 5.5vw, 4.4rem)",
            color: theme.text, lineHeight: 1.03, letterSpacing: "-.02em", marginTop: ".75rem", marginBottom: "1rem", maxWidth: 920,
          }}>{lang === "en"
            ? <>Screen-free activities, <em>organised by every category</em> that matters at home.</>
            : <>Actividades sin pantallas, <em>organizadas por cada categoría</em> que importa en casa.</>}</h1>
          <p style={{ color: theme.text2, fontSize: "1.05rem", lineHeight: 1.7, fontWeight: 300, maxWidth: 640 }}>
            {lang === "en"
              ? "Each season, holiday and moment of the year carries its own set — and the same activities are cross-listed by accessibility and family need. Filter by tier with the toggle above."
              : "Cada estación, fiesta y momento del año tiene su propio set — y las mismas actividades se cruzan por accesibilidad y necesidad familiar. Filtra por plan con el control de arriba."}
          </p>
        </div>
      </header>

      {/* CATEGORY NAV */}
      <div style={{
        position: "sticky", top: inApp ? 62 : 53, zIndex: 20,
        background: theme.navBg, backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)",
        borderTop: `1px solid ${theme.border}`, borderBottom: `1px solid ${theme.border}`,
        padding: ".7rem clamp(1.5rem, 5vw, 5vw)",
      }}>
        <div className="wrap" style={{ display: "flex", gap: 6, flexWrap: "wrap", alignItems: "center" }}>
          {nav.map(n => (
            <button key={n.id} onClick={() => { const el = document.getElementById("grp-" + n.id); if (el) window.scrollTo({ top: el.offsetTop - 96, behavior: "smooth" }); }}
              style={{ padding: "5px 13px", borderRadius: 16, background: theme.sage3, border: `1px solid ${theme.border2}`, color: theme.text2, fontSize: ".74rem" }}>
              {n.label}
            </button>
          ))}
        </div>
      </div>

      {/* GROUPS · Seasons / Holidays / Moments */}
      {groups.map(g => (
        <section key={g.id} id={"grp-" + g.id} style={{ padding: "clamp(2.5rem,5vh,4rem) clamp(1.5rem, 5vw, 5vw) 1rem" }}>
          <div className="wrap">
            <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: "2rem" }}>
              <span className="serif" style={{ fontSize: "2rem", color: theme.text, fontStyle: "italic", fontWeight: 300 }}>{g.label[lang]}</span>
              <span style={{ flex: 1, height: 1, background: theme.divider }}/>
              <span className="mono" style={{ fontSize: ".7rem", color: theme.text3 }}>{g.cats.length} {lang === "en" ? "categories" : "categorías"}</span>
            </div>

            {g.cats.map(catId => {
              const t = tagOf(catId);
              const items = all.filter(a => a.cat === catId && tierOk(a));
              if (!t) return null;
              return (
                <div key={catId} style={{ marginBottom: "2.75rem" }}>
                  {/* category header */}
                  <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: "1rem", paddingBottom: ".6rem", borderBottom: `1px solid ${t.hue}33` }}>
                    <span style={{
                      width: 34, height: 34, borderRadius: 9, background: `${t.hue}1c`, border: `1px solid ${t.hue}55`,
                      display: "flex", alignItems: "center", justifyContent: "center",
                      fontFamily: "'Cormorant Garamond',serif", fontSize: "1.15rem", color: t.hue,
                    }}>{t.glyph}</span>
                <svg aria-hidden='true' width='18' height='22' viewBox='0 0 18 22' fill='none' style={{ opacity:.28, flexShrink:0 }}>
                  <path d='M9 20C5 17 3 13 5 7C7 2 13 2 15 7C17 13 13 17 9 20Z' stroke={t.hue} strokeWidth='1.1' fill='none'/>
                  <line x1='9' y1='20' x2='9' y2='7' stroke={t.hue} strokeWidth='.8' strokeLinecap='round'/>
                  <path d='M9 15C7 14 5.5 12 4.5 10' stroke={t.hue} strokeWidth='.7' strokeLinecap='round'/>
                  <path d='M9 11C11 10 12.5 8 13.5 6' stroke={t.hue} strokeWidth='.7' strokeLinecap='round'/>
                </svg>
                    <div style={{ flex: 1 }}>
                      <div className="serif" style={{ fontSize: "1.3rem", color: theme.text, fontStyle: "italic", fontWeight: 400, lineHeight: 1 }}>{t.label[lang]}</div>
                    </div>
                    <span style={{ fontSize: ".72rem", color: theme.text3 }}>{items.length} {lang === "en" ? "activities" : "actividades"}</span>
                  </div>
                  {/* cards */}
                  {items.length > 0 ? (
                    <div className="grid-3" style={{ gap: ".85rem" }}>
                      {items.map(a => <CatCard key={a.id} a={a} theme={theme} dark={dark} lang={lang} accent={t.hue} nav={goTo}/>)}
                    </div>
                  ) : (
                    <div style={{ fontSize: ".82rem", color: theme.text3, fontStyle: "italic", padding: ".5rem 0" }}>
                      {lang === "en" ? "No activities at this tier." : "Sin actividades en este plan."}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </section>
      ))}

      {/* BY NEED */}
      <section id="grp-needs" style={{ padding: "clamp(2.5rem,5vh,4rem) clamp(1.5rem, 5vw, 5vw) 4rem", background: dark ? theme.bg2 : theme.bg2, borderTop: `1px solid ${theme.border}` }}>
        <div className="wrap">
          <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: ".5rem" }}>
            <span className="serif" style={{ fontSize: "2rem", color: theme.text, fontStyle: "italic", fontWeight: 300 }}>{lang === "en" ? "By accessibility & need" : "Por accesibilidad y necesidad"}</span>
            <span style={{ flex: 1, height: 1, background: theme.divider }}/>
            <span className="mono" style={{ fontSize: ".7rem", color: theme.text3 }}>{publicNeeds.length} {lang === "en" ? "needs" : "necesidades"}</span>
          </div>
          <p style={{ color: theme.text2, fontSize: ".95rem", lineHeight: 1.7, fontWeight: 300, maxWidth: 620, marginBottom: "2.25rem" }}>
            {lang === "en"
              ? "The same activities, re-listed by what your family needs. Each need is its own lane — scroll sideways."
              : "Las mismas actividades, reordenadas por lo que tu familia necesita. Cada necesidad es su propia fila — desliza de lado."}
          </p>

          <div style={{ display: "flex", flexDirection: "column", gap: "2rem" }}>
            {publicNeeds.map(n => {
              const items = all.filter(a => a.needs.includes(n.id) && tierOk(a));
              if (items.length === 0) return null;
              return (
                <div key={n.id}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: ".85rem" }}>
                    <span style={{ fontSize: "1rem", color: n.hue, fontFamily: "'Cormorant Garamond',serif", width: 22, textAlign: "center" }}>{n.glyph}</span>
                    <span style={{ fontSize: ".95rem", color: theme.text, fontWeight: 500 }}>{n.label[lang]}</span>
                    <span style={{ fontSize: ".7rem", color: theme.text3 }}>· {items.length}</span>
                    <span style={{ flex: 1, height: 1, background: theme.divider }}/>
                  </div>
                  <div className="cat-scroll" style={{ display: "flex", gap: ".75rem", overflowX: "auto", paddingBottom: 8 }}>
                    {items.map(a => <NeedCard key={a.id} a={a} theme={theme} dark={dark} lang={lang} accent={n.hue} nav={goTo}/>)}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>


    </div>
  );
}

// ── full card (in category grids) ───────────────────────────
function CatCard({ a, theme, dark, lang, accent, nav }) {
  return (
    <article onClick={nav ? () => nav("activitydetail", { id: a.id }) : undefined} style={{
      background: dark ? theme.panel : "#fff", border: `1px solid ${theme.border}`,
      borderRadius: 8, padding: "1.25rem 1.2rem", display: "flex", flexDirection: "column", gap: ".7rem",
      borderTop: `2px solid ${accent}`, cursor: nav ? "pointer" : "default",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
        <span className="mono" style={{ fontSize: ".64rem", color: theme.text3 }}>{a.ages[0]}–{a.ages[1]}y · {a.duration} min</span>
        <Pill color={a.tier === "premium" ? theme.gold : theme.sage} bd={`${a.tier === "premium" ? theme.gold : theme.sage}55`} size=".56rem">{a.tier === "premium" ? "WiseTip+" : "Free"}</Pill>
      </div>
      <h3 className="serif" style={{ fontStyle: "italic", fontWeight: 400, fontSize: "1.32rem", color: theme.text, lineHeight: 1.12 }}>{a.title[lang]}</h3>
      <p style={{ fontSize: ".86rem", color: theme.text2, fontWeight: 300, lineHeight: 1.55, flex: 1 }}>{a.summary[lang]}</p>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 4, paddingTop: ".5rem", borderTop: `1px solid ${theme.divider}` }}>
        {a.needs.slice(0, 4).map(nid => {
          const tag = needOf(nid); if (!tag) return null;
          return <span key={nid} style={{ fontSize: ".6rem", padding: "2px 8px", borderRadius: 9, background: theme.sage3, color: theme.text3, letterSpacing: ".04em" }}>{tag.glyph} {tag.label[lang]}</span>;
        })}
      </div>
    </article>
  );
}

// ── compact card (in need lanes) ────────────────────────────
function NeedCard({ a, theme, dark, lang, accent, nav }) {
  const otherSeasons = a.seasons.filter(s => { const t = tagOf(s); return t && !t.hidden; }).slice(0, 2);
  return (
    <article onClick={nav ? () => nav("activitydetail", { id: a.id }) : undefined} style={{
      flexShrink: 0, width: 230, background: dark ? theme.panel : "#fff",
      border: `1px solid ${theme.border}`, borderLeft: `2px solid ${accent}`,
      borderRadius: 8, padding: "1rem 1.05rem", display: "flex", flexDirection: "column", gap: ".5rem", cursor: nav ? "pointer" : "default",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
        <span className="mono" style={{ fontSize: ".6rem", color: theme.text3 }}>{a.ages[0]}–{a.ages[1]}y · {a.duration}m</span>
        <span style={{ width: 7, height: 7, borderRadius: "50%", background: a.tier === "premium" ? theme.gold : theme.sage }}/>
      </div>
      <h4 className="serif" style={{ fontStyle: "italic", fontWeight: 400, fontSize: "1.1rem", color: theme.text, lineHeight: 1.12 }}>{a.title[lang]}</h4>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginTop: "auto" }}>
        {otherSeasons.map(sid => { const t = tagOf(sid); return <span key={sid} style={{ fontSize: ".58rem", padding: "1px 7px", borderRadius: 8, background: `${t.hue}1a`, color: t.hue, border: `1px solid ${t.hue}3a` }}>{t.glyph} {t.label[lang]}</span>; })}
      </div>
    </article>
  );
}

// ── segmented control ───────────────────────────────────────
// ── segmented control ───────────────────────────────────
function CatSeg({ theme, dark, value, onChange, options }) {
  return (
    <div style={{ display: "flex", gap: 3, padding: 3, background: theme.sage3, borderRadius: 16, border: `1px solid ${theme.border}` }}>
      {options.map(([v, l]) => (
        <button key={v} onClick={() => onChange(v)} style={{
          padding: "5px 12px", borderRadius: 13, border: "none",
          background: value === v ? theme.sage : "transparent",
          color: value === v ? (dark ? "#050F07" : "#fff") : theme.text2,
          fontSize: ".72rem", fontWeight: value === v ? 600 : 400,
        }}>{l}</button>
      ))}
    </div>
  );
}

// Export for the in-app router (Homepage.html loads this before app.jsx).
Object.assign(window, { ActivityCatalog });

// Self-render only when opened as the standalone "Activities by Category.html",
// which sets window.WS_SELF_RENDER = "catalog" before this script runs.
if (window.WS_SELF_RENDER === "catalog") {
  ReactDOM.createRoot(document.getElementById("root")).render(<ActivityCatalog/>);
}
