/* ============================================================
   CONSUMER SHELL — header, category nav, footer, search, toast
   window: Header, Footer, Toast
   ============================================================ */
(function () {
  const { useApp, H, Icon } = window;

  function Logo({ onClick }) {
    return (
      <button onClick={onClick} aria-label="হোম"
        style={{ background: "none", border: 0, padding: 0, cursor: "pointer", display: "flex", alignItems: "baseline", gap: 2 }}>
        <span className="serif" style={{ fontSize: 30, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--ink)" }}>প্রভাত</span>
        <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--accent)", display: "inline-block", marginLeft: 2, transform: "translateY(-2px)" }} />
      </button>
    );
  }

  function Header() {
    const app = useApp();
    const cats = window.SEED.CATEGORIES;
    const active = app.state.route;
    const [search, setSearch] = React.useState(false);
    const [q, setQ] = React.useState("");
    const [menu, setMenu] = React.useState(false);
    const user = app.state.user;
    const inCat = (slug) => active.view === "category" && active.params.slug === slug;

    return (
      <header style={{ background: "var(--surface)", borderBottom: "1px solid var(--line)", position: "sticky", top: 0, zIndex: 40 }}>
        {/* top utility bar */}
        <div style={{ borderBottom: "1px solid var(--line-2)" }}>
          <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 38, fontSize: 12.5 }}>
            <span className="muted">{H.fullDate()}</span>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <button className="link-btn muted" onClick={() => app.nav("admin")}
                style={{ background: "none", border: 0, cursor: "pointer", fontSize: 12.5, display: "inline-flex", alignItems: "center", gap: 5, color: "var(--ink-3)" }}>
                <Icon name="settings" size={13} /> {H.t("admin")}
              </button>
            </div>
          </div>
        </div>

        {/* masthead */}
        <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 72, gap: 20 }}>
          <button className="hamb" onClick={() => setMenu(true)}
            style={{ background: "none", border: 0, cursor: "pointer", color: "var(--ink)", display: "none" }}><Icon name="menu" size={22} /></button>
          <Logo onClick={() => app.nav("home")} />
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <button className="btn ghost sm" onClick={() => setSearch(true)} aria-label={app.state.lang === "en" ? "Search" : "খুঁজুন"}><Icon name="search" size={18} /></button>
            <button className="btn ghost sm" onClick={() => app.nav("bookmarks")} aria-label={H.t("bookmarks")} style={{ position: "relative" }}>
              <Icon name="bookmark" size={18} fill={app.state.bookmarks.length > 0} />
              {app.state.bookmarks.length > 0 &&
                <span style={{ position: "absolute", top: 2, right: 2, background: "var(--accent)", color: "#fff", fontSize: 9, fontWeight: 700, borderRadius: 999, minWidth: 14, height: 14, display: "grid", placeItems: "center", padding: "0 3px" }}>{H.num(app.state.bookmarks.length)}</span>}
            </button>
            {user ? (
              <button className="btn sm" onClick={() => app.nav("account")} style={{ paddingLeft: 6 }}>
                <span style={{ width: 26, height: 26, borderRadius: "50%", background: "var(--accent)", color: "#fff", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 13 }}>{user.initials}</span>
                <span className="hide-sm">{user.name}</span>
              </button>
            ) : (
              <button className="btn primary sm" onClick={() => app.nav("login")}><Icon name="user" size={15} /> <span className="hide-sm">{H.t("loginBtn")}</span></button>
            )}
          </div>
        </div>

        {/* category nav */}
        <nav style={{ borderTop: "1px solid var(--line-2)" }}>
          <div className="wrap catnav" style={{ display: "flex", alignItems: "center", gap: 2, height: 46, overflowX: "auto" }}>
            <button onClick={() => app.nav("home")} className="catlink" data-active={active.view === "home"}>{H.t("home")}</button>
            {cats.map(c => (
              <button key={c.slug} onClick={() => app.nav("category", { slug: c.slug })} className="catlink" data-active={inCat(c.slug)}>{H.pick(c, "label")}</button>
            ))}
          </div>
        </nav>

        {search && <SearchOverlay q={q} setQ={setQ} onClose={() => setSearch(false)} />}
        {menu && <MobileMenu onClose={() => setMenu(false)} />}
      </header>
    );
  }

  function SearchOverlay({ q, setQ, onClose }) {
    const app = useApp();
    const all = app.state.articles;
    const res = q.trim() ? all.filter(a => ((a.bn || "") + (a.en || "")).toLowerCase().includes(q.toLowerCase())).slice(0, 6) : [];
    React.useEffect(() => {
      const h = (e) => e.key === "Escape" && onClose();
      window.addEventListener("keydown", h); return () => window.removeEventListener("keydown", h);
    }, []);
    return (
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "oklch(0.2 0.02 250 / 0.4)", zIndex: 60, display: "flex", justifyContent: "center", paddingTop: 90 }}>
        <div onClick={e => e.stopPropagation()} className="fade-in"
          style={{ width: "min(640px,92vw)", background: "var(--surface)", borderRadius: 8, boxShadow: "var(--shadow-2)", overflow: "hidden", height: "fit-content" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 18px", borderBottom: "1px solid var(--line)" }}>
            <Icon name="search" size={20} style={{ color: "var(--ink-3)" }} />
            <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder={H.t("searchPlaceholder")}
              style={{ border: 0, padding: 0, fontSize: 17 }} />
            <button className="btn ghost sm" onClick={onClose}><Icon name="x" size={16} /></button>
          </div>
          <div style={{ maxHeight: "50vh", overflowY: "auto" }}>
            {res.map(a => (
              <button key={a.id} onClick={() => { app.nav("article", { id: a.id }); onClose(); }}
                style={{ display: "block", width: "100%", textAlign: "right", background: "none", border: 0, borderBottom: "1px solid var(--line-2)", padding: "13px 18px", cursor: "pointer" }}>
                <div className="kicker bn" style={{ marginBottom: 3 }}>{H.pick(H.catBy(a.cat), "label")}</div>
                <div className="serif" style={{ fontSize: 16, color: "var(--ink)" }}>{H.pick(a, "title")}</div>
              </button>
            ))}
            {q.trim() && res.length === 0 && <div className="muted" style={{ padding: 24, textAlign: "center" }}>{H.t("noResults")}</div>}
            {!q.trim() && <div className="muted" style={{ padding: 24, textAlign: "center", fontSize: 13 }}>{H.t("typeToSearch")}</div>}
          </div>
        </div>
      </div>
    );
  }

  function MobileMenu({ onClose }) {
    const app = useApp();
    return (
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "oklch(0.2 0.02 250 / 0.4)", zIndex: 60 }}>
        <div onClick={e => e.stopPropagation()} className="fade-in"
          style={{ position: "absolute", top: 0, right: 0, bottom: 0, width: "min(320px,82vw)", background: "var(--surface)", padding: 20, boxShadow: "var(--shadow-2)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
            <span className="serif" style={{ fontSize: 22, fontWeight: 700 }}>{H.t("menu")}</span>
            <button className="btn ghost sm" onClick={onClose}><Icon name="x" size={18} /></button>
          </div>
          {window.SEED.CATEGORIES.map(c => (
            <button key={c.slug} onClick={() => { app.nav("category", { slug: c.slug }); onClose(); }}
              style={{ display: "flex", justifyContent: "space-between", width: "100%", background: "none", border: 0, borderBottom: "1px solid var(--line-2)", padding: "14px 2px", fontSize: 17, cursor: "pointer", color: "var(--ink)" }}>
              <span className="serif">{H.pick(c, "label")}</span><span className="muted" style={{ fontSize: 12 }}>{c.en}</span>
            </button>
          ))}
        </div>
      </div>
    );
  }

  function Footer() {
    const app = useApp();
    const cats = window.SEED.CATEGORIES;
    return (
      <footer style={{ background: "var(--surface-2)", borderTop: "1px solid var(--line)", marginTop: 56 }}>
        <div className="wrap" style={{ padding: "44px 24px 28px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr", gap: 32 }} className="foot-grid">
            <div>
              <div className="serif" style={{ fontSize: 28, fontWeight: 700, marginBottom: 10 }}>প্রভাত<span style={{ color: "var(--accent)" }}>.</span></div>
              <p className="ink2" style={{ fontSize: 14, lineHeight: 1.6, maxWidth: 320 }}>{H.t("tagline")}</p>
            </div>
            <div>
              <div className="kicker" style={{ marginBottom: 12 }}>{H.t("categories")}</div>
              <div style={{ display: "grid", gap: 8 }}>
                {cats.slice(0, 6).map(c => (
                  <button key={c.slug} onClick={() => app.nav("category", { slug: c.slug })}
                    style={{ background: "none", border: 0, padding: 0, textAlign: "left", cursor: "pointer", color: "var(--ink-2)", fontSize: 14 }}>{H.pick(c, "label")}</button>
                ))}
              </div>
            </div>
            <div>
              <div className="kicker" style={{ marginBottom: 12 }}>{H.t("organization")}</div>
              <div style={{ display: "grid", gap: 8 }}>
                {window.SEED.ORG_PAGES.map(p => (
                  <button key={p.slug} onClick={() => app.nav("page", { slug: p.slug })}
                    style={{ background: "none", border: 0, padding: 0, textAlign: "left", cursor: "pointer", color: "var(--ink-2)", fontSize: 14 }}>{H.pick(p, "label")}</button>
                ))}
              </div>
            </div>
          </div>
          <div style={{ borderTop: "1px solid var(--line)", marginTop: 32, paddingTop: 18, display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 10 }}>
            <span className="muted" style={{ fontSize: 12.5 }}>© {H.num(2026)} {app.state.lang === "en" ? "Probhat" : "প্রভাত"}। {H.t("allRights")}</span>
          </div>
        </div>
      </footer>
    );
  }

  function Toast() {
    const app = useApp();
    const t = app.state.toast;
    if (!t) return null;
    return (
      <div className="fade-in" style={{ position: "fixed", bottom: 26, left: "50%", transform: "translateX(-50%)", zIndex: 80,
        background: "var(--ink)", color: "var(--bg)", padding: "11px 20px", borderRadius: 999, fontSize: 14, fontWeight: 600, boxShadow: "var(--shadow-2)" }}>
        {t.msg}
      </div>
    );
  }

  Object.assign(window, { Header, Footer, Toast });
})();
