/* ============================================================
   CONSUMER HOME — special-news slider + magazine grid + rails
   window: Home  (reads window.__tweaks.sliderStyle)
   ============================================================ */
(function () {
  const { useApp, H, Icon, ArticleCard, ImgPH, MediaFrame, isPlayableMedia, Views } = window;

  /* ---------- Special-news slider ---------- */
  function Slider({ items, style }) {
    const app = useApp();
    const [i, setI] = React.useState(0);
    const [paused, setPaused] = React.useState(false);
    const n = items.length;
    const go = (d) => setI(p => (p + d + n) % n);
    const to = (x) => setI(x);

    const aRaw = n > 0 ? items[Math.min(i, n - 1)] : null;
    const playable = aRaw && isPlayableMedia && isPlayableMedia(aRaw);

    React.useEffect(() => {
      if (paused || n === 0 || playable) return;
      const t = setInterval(() => setI(p => (p + 1) % n), 5500);
      return () => clearInterval(t);
    }, [paused, n, playable, i]);

    if (n === 0) return null;
    const a = aRaw;
    const cat = H.catBy(a.cat);
    const st = app.state.articleState[a.id] || { views: a.views };
    const featuredTxt = H.t("featured");
    const videoTxt = H.t("video");
    const title  = H.pick(a, "title");
    const author = H.pick(a, "author");
    const excerpt = H.pick(a, "excerpt");

    // --- BILLBOARD style: big hero left + ranked rail right ---
    if (style === "billboard") {
      return (
        <section className="wrap" style={{ paddingTop: 26 }} onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
          <div style={{ display: "grid", gridTemplateColumns: "1.62fr 1fr", gap: 26 }} className="bb-grid">
            <div className="fade-in" key={a.id} style={{ position: "relative" }}>
              <div style={{ position: "relative", borderRadius: "var(--radius)", overflow: "hidden", cursor: a.mediaKind === "embed" ? "default" : "pointer" }}
                onClick={() => { if (a.mediaKind !== "embed") app.nav("article", { id: a.id }); }}>
                <MediaFrame kind={a.mediaKind || "image"} url={a.mediaUrl || a.img} thumbnail={a.mediaThumbnail || a.img} mime={a.mediaMime} label={title}
                  style={{ width: "100%", aspectRatio: "16/10" }} />
                <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, oklch(0.16 0.02 250 / 0.92) 0%, oklch(0.16 0.02 250 / 0.32) 45%, transparent 72%)", pointerEvents: "none" }} />
                <span className="badge teal" style={{ position: "absolute", top: 16, right: 16, background: "var(--accent)", color: "#fff" }}>{featuredTxt}</span>
                {playable && <span className="badge" style={{ position: "absolute", top: 16, left: 16, background: "rgba(0,0,0,.7)", color: "#fff" }}>▶ {videoTxt}</span>}
                <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, padding: 26, color: "#fff", pointerEvents: "none" }}>
                  <div className="kicker bn" style={{ color: "rgba(255,255,255,.9)", marginBottom: 8 }}>{H.pick(cat, "label")}</div>
                  <h2 className="serif" style={{ fontSize: "clamp(24px,2.6vw,38px)", color: "#fff", marginBottom: 10 }}>{title}</h2>
                  <div className="meta" style={{ color: "rgba(255,255,255,.82)" }}><span>{author}</span><span className="dot" style={{ background: "#fff" }} /><Views n={st.views} light /><span className="dot" style={{ background: "#fff" }} />{H.rel(a.ts)}</div>
                </div>
              </div>
            </div>
            <div style={{ display: "flex", flexDirection: "column" }}>
              <div className="kicker" style={{ marginBottom: 10 }}>{H.t("moreFeatured")}</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 2, flex: 1 }}>
                {items.map((it, idx) => (
                  <button key={it.id} onClick={() => to(idx)}
                    style={{ display: "grid", gridTemplateColumns: "26px 1fr", gap: 12, textAlign: "right", background: idx === i ? "var(--surface-2)" : "none",
                      border: 0, borderBottom: "1px solid var(--line-2)", padding: "12px 8px", cursor: "pointer", alignItems: "start", borderRadius: "var(--radius)" }}>
                    <span className="serif" style={{ fontSize: 22, fontWeight: 700, color: idx === i ? "var(--accent)" : "var(--ink-3)" }}>{H.num(idx + 1)}</span>
                    <span>
                      <span className="serif headline-link" style={{ fontSize: 16, color: idx === i ? "var(--accent-ink)" : "var(--ink)", display: "block", lineHeight: 1.3 }}>{H.pick(it, "title")}</span>
                      <span className="meta" style={{ fontSize: 11.5, marginTop: 5 }}><Views n={(app.state.articleState[it.id] || {}).views || 0} /></span>
                    </span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        </section>
      );
    }

    // --- CINEMATIC style: full-width overlay hero + dots ---
    return (
      <section className="wrap" style={{ paddingTop: 26 }} onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
        <div style={{ position: "relative", borderRadius: "var(--radius)", overflow: "hidden" }}>
          <div className="fade-in" key={a.id} style={{ position: "relative" }}>
            <div style={{ cursor: a.mediaKind === "embed" ? "default" : "pointer" }}
              onClick={() => { if (a.mediaKind !== "embed") app.nav("article", { id: a.id }); }}>
              <MediaFrame kind={a.mediaKind || "image"} url={a.mediaUrl || a.img} thumbnail={a.mediaThumbnail || a.img} mime={a.mediaMime} label={title}
                style={{ width: "100%", aspectRatio: "21/9", minHeight: 320 }} />
            </div>
            <div style={{ position: "absolute", inset: 0, background: "linear-gradient(105deg, oklch(0.16 0.02 250 / 0.9) 0%, oklch(0.16 0.02 250 / 0.55) 42%, transparent 75%)", pointerEvents: "none" }} />
            <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", justifyContent: "flex-end", padding: "clamp(24px,4vw,52px)", maxWidth: 760, pointerEvents: "none" }}>
              <span className="badge" style={{ background: "var(--accent)", color: "#fff", width: "fit-content", marginBottom: 14 }}>{featuredTxt} · {H.pick(cat, "label")}{playable ? " · ▶ " + videoTxt : ""}</span>
              <h2 className="serif" style={{ fontSize: "clamp(28px,4vw,54px)", color: "#fff", marginBottom: 14, lineHeight: 1.08 }}>{title}</h2>
              <p style={{ color: "rgba(255,255,255,.9)", fontSize: "clamp(15px,1.4vw,18px)", lineHeight: 1.5, marginBottom: 16, maxWidth: 620 }}>{excerpt}</p>
              <div className="meta" style={{ color: "rgba(255,255,255,.82)" }}><span>{author}</span><span className="dot" style={{ background: "#fff" }} /><Views n={st.views} light /><span className="dot" style={{ background: "#fff" }} />{H.rel(a.ts)}</div>
            </div>
          </div>
          <button onClick={() => go(-1)} aria-label={H.t("prev")} className="slider-arr" style={{ left: 16 }}><Icon name="arrowL" size={20} /></button>
          <button onClick={() => go(1)} aria-label={H.t("next")} className="slider-arr" style={{ right: 16 }}><Icon name="arrowR" size={20} /></button>
          <div style={{ position: "absolute", bottom: 18, right: "clamp(24px,4vw,52px)", display: "flex", gap: 7 }}>
            {items.map((_, idx) => (
              <button key={idx} onClick={() => to(idx)} aria-label={H.t("slide") + " " + (idx + 1)}
                style={{ width: idx === i ? 28 : 9, height: 9, borderRadius: 999, border: 0, cursor: "pointer", background: idx === i ? "var(--accent)" : "rgba(255,255,255,.55)", transition: "all .25s ease" }} />
            ))}
          </div>
        </div>
      </section>
    );
  }

  function SectionHead({ cat, onMore }) {
    return (
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", borderBottom: "2px solid var(--ink)", paddingBottom: 10, marginBottom: 18 }}>
        <h2 className="serif nowrap" style={{ fontSize: 24, fontWeight: 700 }}>{H.pick(cat, "label")}</h2>
        <button onClick={onMore} style={{ background: "none", border: 0, cursor: "pointer", color: "var(--accent-ink)", fontSize: 13.5, fontWeight: 700, display: "inline-flex", alignItems: "center", gap: 5 }}>
          {H.t("seeAll")} <Icon name="arrowL" size={14} />
        </button>
      </div>
    );
  }

  function Home() {
    const app = useApp();
    const T = window.__tweaks || {};
    const all = app.state.articles;
    const featured = app.state.featured && app.state.featured.length ? app.state.featured : all.filter(a => a.special);
    const sorted = [...all].sort((x, y) => y.ts - x.ts);
    const mostViewed = [...all].sort((x, y) => ((app.state.articleState[y.id] || {}).views || 0) - ((app.state.articleState[x.id] || {}).views || 0)).slice(0, 5);

    if (!sorted.length) {
      const en = app.state.lang === "en";
      if (app.state.booting) {
        return (
          <div className="wrap" style={{ padding: "80px 20px", textAlign: "center" }}>
            <p className="muted">{H.t("loading")}</p>
          </div>
        );
      }
      const err = app.state.loadError;
      return (
        <div className="wrap" style={{ padding: "80px 20px", textAlign: "center" }}>
          <p className="serif" style={{ fontSize: 22, fontWeight: 700, marginBottom: 10 }}>
            {err
              ? (en ? "Could not reach the server" : "সার্ভার থেকে তথ্য আনা যায়নি")
              : (en ? "No news yet" : "এখনো কোনো সংবাদ নেই")}
          </p>
          {err && (
            <p className="muted" style={{ marginBottom: 18, fontSize: 14 }}>
              {en
                ? "Check that the backend is running at " + (window.API_BASE || "")
                : "ব্যাকএন্ড চালু আছে কি না দেখুন — " + (window.API_BASE || "")}
            </p>
          )}
          <button className="btn primary" onClick={() => app.loadPublic()}>
            {en ? "Retry" : "আবার চেষ্টা করুন"}
          </button>
        </div>
      );
    }
    const lead = sorted.find(a => !a.special) || sorted[0];
    const secondary = sorted.filter(a => a.id !== lead.id).slice(0, 4);

    // group remaining by category for sections
    const sectionCats = ["bangladesh", "sports", "tech", "world"];

    return (
      <div className="fade-in">
        {featured.length > 0 && <Slider items={featured} style={T.sliderStyle || "cinematic"} />}

        {/* lead block */}
        <div className="wrap" style={{ paddingTop: 40 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.7fr 320px", gap: "var(--gap)" }} className="home-top">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--gap)", borderRight: "1px solid var(--line)", paddingRight: "var(--gap)" }} className="home-lead">
              <div style={{ gridColumn: "1 / -1" }}><ArticleCard a={lead} size="lead" /></div>
              <div style={{ gridColumn: "1 / -1", height: 1, background: "var(--line-2)" }} />
              {secondary.map(a => <ArticleCard key={a.id} a={a} size="text" />)}
            </div>

            {/* most-viewed rail */}
            <aside>
              <div style={{ position: "sticky", top: 168 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, borderBottom: "2px solid var(--accent)", paddingBottom: 9, marginBottom: 4 }}>
                  <Icon name="bolt" size={16} fill style={{ color: "var(--accent)" }} />
                  <h3 className="serif nowrap" style={{ fontSize: 19, fontWeight: 700 }}>{H.t("mostRead")}</h3>
                </div>
                {mostViewed.map((a, idx) => (
                  <button key={a.id} onClick={() => app.nav("article", { id: a.id })}
                    style={{ display: "grid", gridTemplateColumns: "30px 1fr", gap: 12, textAlign: "right", background: "none", border: 0, borderBottom: "1px solid var(--line-2)", padding: "14px 2px", cursor: "pointer", alignItems: "start", width: "100%" }}>
                    <span className="serif" style={{ fontSize: 26, fontWeight: 700, color: "var(--line)", lineHeight: 1 }}>{H.num(idx + 1)}</span>
                    <span>
                      <span className="serif headline-link" style={{ fontSize: 15.5, color: "var(--ink)", display: "block", lineHeight: 1.3, marginBottom: 5 }}>{H.pick(a, "title")}</span>
                      <span className="meta" style={{ fontSize: 11.5 }}><Views n={(app.state.articleState[a.id] || {}).views || 0} /></span>
                    </span>
                  </button>
                ))}
              </div>
            </aside>
          </div>
        </div>

        {/* category sections */}
        <div className="wrap" style={{ paddingTop: 50, display: "grid", gap: 50 }}>
          {sectionCats.map((slug) => {
            const cat = H.catBy(slug);
            const list = all.filter(a => a.cat === slug);
            if (!list.length) return null;
            const featured = list[0], rest = list.slice(1, 4);
            return (
              <section key={slug}>
                <SectionHead cat={cat} onMore={() => app.nav("category", { slug })} />
                <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr 1fr", gap: "var(--gap)" }} className="cat-row">
                  <ArticleCard a={featured} size="tall" />
                  <div style={{ gridColumn: "span 2", display: "grid", gap: 20, alignContent: "start" }}>
                    {rest.length ? rest.map(a => <ArticleCard key={a.id} a={a} size="row" />) : <ArticleCard a={featured} size="row" />}
                  </div>
                </div>
              </section>
            );
          })}
        </div>
      </div>
    );
  }

  window.Home = Home;
})();
