/* ============================================================
   COMMONS — app shell, router, page transitions
   ============================================================ */

function Footer({ go }) {
  return (
    <footer className="footer">
      <div className="shell footer-inner">
        <div className="footer-brand">
          <Logo onClick={() => go("community")} />
          <p>A warm, well-made commons for the global Punjabi diaspora.</p>
        </div>
        <div className="footer-cols">
          <div>
            <span className="kicker">Explore</span>
            <a onClick={() => go("community")}>Community</a>
            <a onClick={() => go("read")}>Stories</a>
          </div>
          <div>
            <span className="kicker">Create</span>
            <a onClick={() => go("community")}>Start a thread</a>
            <a onClick={() => go("read")}>Write a story</a>
          </div>
          <div>
            <span className="kicker">iPanjab</span>
            <a>About</a>
            <a>Guidelines</a>
            <a>Contact</a>
          </div>
        </div>
      </div>
      <div className="shell footer-bottom">
        <span>© 2026 iPanjab</span>
        <span>Made for the diaspora, by the diaspora.</span>
      </div>
    </footer>
  );
}

function NotificationsPage({ go }) {
  const src = (typeof window !== "undefined" && window.__DATA__ && window.__DATA__.notifs) || [];
  const [items] = useState(() => src.map(n => ({ ...n })));
  useEffect(() => {
    fetch("/api/notifications/read", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }).catch(() => {});
  }, []);
  const open = (n) => {
    if (n.id) fetch("/api/notifications/read", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: n.id }) }).catch(() => {});
    go(n.link || "community");
  };
  return (
    <div className="view notif-page">
      <div className="shell notif-shell">
        <span className="kicker">iPanjab</span>
        <h1 className="serif notif-page-title">Notifications</h1>
        {items.length === 0 ? (
          <div className="pf-empty">
            <Icon name="bell" size={28} />
            <b className="serif">You are all caught up</b>
            <p>When people reply to your posts or comment on your stories, you will see it here.</p>
            <button className="btn btn-primary" onClick={() => go("community")}>Go to community</button>
          </div>
        ) : (
          <div className="notif-page-list">
            {items.map((n, i) => (
              <button key={n.id || i} className="notif-row" data-unread={n.unread} style={{ "--i": i }} onClick={() => open(n)}>
                <Avatar seed={n.seed} label={n.who} size={42} />
                <div className="notif-row-main">
                  <p><b>{n.who}</b> {n.txt}</p>
                  <span>{n.time}</span>
                </div>
                {n.unread && <span className="notif-row-dot" />}
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function PeoplePage({ go }) {
  const all = (typeof window !== "undefined" && window.__DATA__ && window.__DATA__.people) || [];
  const [q, setQ] = useState("");
  const list = all.filter(p => !q || (p.name || "").toLowerCase().includes(q.toLowerCase()) || (p.handle || "").toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="view people-page">
      <section className="comm-banner">
        <div className="shell comm-banner-inner">
          <div>
            <span className="kicker" style={{ "--i": 0 }}>iPanjab Members</span>
            <h1 className="comm-title serif" style={{ "--i": 1 }}>Find your people.</h1>
          </div>
        </div>
      </section>
      <div className="shell people-wrap">
        <div className="people-search">
          <Icon name="search" size={18} />
          <input placeholder="Search members by name or handle" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        {list.length === 0 ? (
          <div className="empty">No members found.</div>
        ) : (
          <div className="people-grid">
            {list.map((p, i) => (
              <button key={p.id} className="person-card" style={{ "--i": i }} onClick={() => go("profile/u" + p.id)}>
                <Avatar seed={p.handle} label={p.name} size={52} />
                <div className="person-main">
                  <b>{p.name}</b>
                  <span className="person-handle">{p.handle}</span>
                  <span className="person-meta">{p.posts} posts, {p.articles} stories, {p.joined}</span>
                </div>
                <Icon name="arrowRight" size={16} className="person-go" />
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function SearchPage({ go }) {
  const D = (typeof window !== "undefined" && window.__DATA__) || {};
  const people = D.people || [], posts = D.posts || [], arts = D.articles || [];
  const [q, setQ] = useState("");
  const ql = q.trim().toLowerCase();
  const match = (s) => (s || "").toLowerCase().includes(ql);
  const ppl = ql ? people.filter(p => match(p.name) || match(p.handle)).slice(0, 10) : [];
  const pst = ql ? posts.filter(p => match(p.title) || match(p.body) || match(p.sub)).slice(0, 10) : [];
  const sty = ql ? arts.filter(a => match(a.title) || match(a.dek) || match(a.author)).slice(0, 10) : [];
  const coms = ql ? (D.communities || []).filter(c => match(c.name) || match(c.desc)).slice(0, 8) : [];
  const total = ppl.length + pst.length + sty.length + coms.length;
  return (
    <div className="view search-page">
      <div className="shell search-shell">
        <span className="kicker">iPanjab</span>
        <h1 className="serif notif-page-title">Search</h1>
        <div className="people-search">
          <Icon name="search" size={18} />
          <input autoFocus placeholder="Search people, posts and stories" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        {!ql && <div className="empty">Start typing to search across members, posts and stories.</div>}
        {ql && total === 0 && <div className="empty">No results for that search.</div>}
        {coms.length > 0 && (
          <div className="search-sec">
            <span className="kicker">Communities</span>
            <div className="search-list">
              {coms.map(c => (
                <button key={c.id} className="search-row" onClick={() => go("community")}>
                  <span className="comm-badge" style={{ background: c.color }}>{c.name[0]}</span>
                  <div className="search-row-main"><b>{c.name}</b><span>{c.members} members - {c.desc}</span></div>
                </button>
              ))}
            </div>
          </div>
        )}
        {ppl.length > 0 && (
          <div className="search-sec">
            <span className="kicker">People</span>
            <div className="people-grid">
              {ppl.map(p => (
                <button key={p.id} className="person-card" onClick={() => go("profile/u" + p.id)}>
                  <Avatar seed={p.handle} label={p.name} size={46} />
                  <div className="person-main"><b>{p.name}</b><span className="person-handle">{p.handle}</span></div>
                  <Icon name="arrowRight" size={16} className="person-go" />
                </button>
              ))}
            </div>
          </div>
        )}
        {pst.length > 0 && (
          <div className="search-sec">
            <span className="kicker">Posts</span>
            <div className="search-list">
              {pst.map(p => (
                <button key={p.id} className="search-row" onClick={() => go("community/" + p.id)}>
                  <Icon name="chat" size={17} />
                  <div className="search-row-main"><b>{p.title}</b><span>{p.sub} - {p.author}</span></div>
                </button>
              ))}
            </div>
          </div>
        )}
        {sty.length > 0 && (
          <div className="search-sec">
            <span className="kicker">Stories</span>
            <div className="search-list">
              {sty.map(a => (
                <button key={a.id} className="search-row" onClick={() => go("read/" + a.id)}>
                  <Icon name="book" size={17} />
                  <div className="search-row-main"><b>{a.title}</b><span>{a.author}</span></div>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

const TWEAK_DEFAULTS = {
  accent: "#E8482A",
  dark: false,
  radius: 14,
  headline: "editorial",
  motion: true,
};

function App() {
  const [route, setRoute] = useState(() => (location.hash.replace(/^#\/?/, "") || "community"));
  const [favs, setFavs] = useState(() => new Set(EVENTS.filter(e => e.fav).map(e => e.id)));
  const [posts, setPosts] = useState(POSTS);
  const addPost = (p) => setPosts(prev => [p, ...prev]);
  const [trans, setTrans] = useState(false);
  const scrollerRef = useRef(null);
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--accent", t.accent);
    root.style.setProperty("--accent-deep", `color-mix(in oklch, ${t.accent} 76%, black)`);
    root.style.setProperty("--accent-soft", `color-mix(in oklch, ${t.accent} 15%, var(--card))`);
    root.setAttribute("data-theme", t.dark ? "dark" : "light");
    root.style.setProperty("--radius", t.radius + "px");
    root.style.setProperty("--radius-sm", Math.round(t.radius * 0.64) + "px");
    root.style.setProperty("--radius-lg", Math.round(t.radius * 1.6) + "px");
    root.style.setProperty("--serif", t.headline === "modern"
      ? '"Hanken Grotesk", system-ui, sans-serif'
      : '"Newsreader", Georgia, "Times New Roman", serif');
    root.classList.toggle("no-motion", !t.motion);
  }, [t.accent, t.dark, t.radius, t.headline, t.motion]);

  const go = (r) => {
    if (r === route) { window.scrollTo({ top: 0, behavior: "smooth" }); return; }
    setTrans(true);
    setTimeout(() => {
      setRoute(r);
      location.hash = "/" + r;
      window.scrollTo(0, 0);
      requestAnimationFrame(() => setTrans(false));
    }, 220);
  };

  useEffect(() => {
    const onHash = () => {
      const r = location.hash.replace(/^#\/?/, "") || "community";
      setRoute(r);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const toggleFav = (id) => setFavs(prev => {
    const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n;
  });

  const [top, sub] = route.split("/");
  let view;
  if (top === "community" && sub) view = <PostThread id={sub} go={go} posts={posts} />;
  else if (top === "community") view = <Community go={go} posts={posts} />;
  else if (top === "compose") view = <NewPost go={go} addPost={addPost} />;
  else if (top === "read" && sub) view = <Reader id={sub} go={go} />;
  else if (top === "read") view = <Read go={go} />;
  else if (top === "notifications") view = <NotificationsPage go={go} />;
  else if (top === "people") view = <PeoplePage go={go} />;
  else if (top === "search") view = <SearchPage go={go} />;
  else if (top === "profile") view = <Profile sub={sub} go={go} favs={favs} toggleFav={toggleFav} posts={posts} />;
  else if (top === "settings") view = <Settings go={go} tweaks={t} setTweak={setTweak} />;
  else view = <Community go={go} posts={posts} />;

  return (
    <React.Fragment>
      <Nav route={route} go={go} />
      <main className={"stage" + (trans ? " leaving" : " entering")} key={route} ref={scrollerRef}>
        {view}
      </main>
      <Footer go={go} />
      <TweaksPanel title="Tweaks">
        <TweakSection label="Color" />
        <TweakColor label="Accent" value={t.accent}
          options={["#E8482A", "#2C4A6E", "#5E7355", "#6B3F5E", "#B98326"]}
          onChange={(v) => setTweak("accent", v)} />
        <TweakToggle label="Dark mode" value={t.dark} onChange={(v) => setTweak("dark", v)} />
        <TweakSection label="Shape & type" />
        <TweakSlider label="Corner radius" value={t.radius} min={2} max={24} unit="px"
          onChange={(v) => setTweak("radius", v)} />
        <TweakRadio label="Headlines" value={t.headline}
          options={["editorial", "modern"]}
          onChange={(v) => setTweak("headline", v)} />
        <TweakSection label="Motion" />
        <TweakToggle label="Animations" value={t.motion} onChange={(v) => setTweak("motion", v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
