/* stations-lib.jsx — bodies for stations 06–09.
 * Content is DATA: components read through window.NBA.getContent(type) and
 * render the canonical record shapes. Costly actions (community post, request
 * submit) require an account + a mocked Turnstile token via requireAuth.
 */
const { useState: useLState } = React;
const getLC = (t) => window.NBA.getContent(t);

// Filter chrome is real + live UI; it just has nothing to filter until the
// agent adds plugin records. ("cost" = cost-sheet plugins — a category.)
const PLUGIN_FILTERS = ["all", "files", "web", "shell", "model", "cost"];
const PLUGIN_EMPTY = {
  title: "The index opens when OpenAgent v0 ships.",
  body: "No placeholder plugins live here on purpose. When there are real ones, you'll browse, search, and filter them right here.",
};
const COMMUNITY_EMPTY = {
  title: "Nothing posted yet.",
  body: "This feed fills in once people start posting. No seeded members, no fake activity — it's empty because it's new.",
};

/* ---- 06 · Plugin Index — search/filter chrome; renders entries when live ---- */
function StPlugins() {
  const p = getLC("plugins") || { state: "empty", entries: [] };
  const entries = p.entries || [];
  // Cross-nav from the Pricing Sheet can pre-select the cost filter.
  const preset = (window.NBA._stationOpts && window.NBA._stationOpts.filter) || "all";
  const [q, setQ] = useLState("");
  const [f, setF] = useLState(preset);

  const cat = (e) => (e.category || e.scope || "").toLowerCase();
  const matches = entries.filter((e) => {
    const inFilter = f === "all" || cat(e).includes(f) || (e.tier || "").toLowerCase() === f;
    const term = q.trim().toLowerCase();
    const inSearch = !term || (e.name || "").toLowerCase().includes(term) || (e.does || "").toLowerCase().includes(term);
    return inFilter && inSearch;
  });
  const live = p.state === "live" && entries.length > 0;
  const costMode = f === "cost";

  const Card = (e) => (
    <div key={e.id} className="plugin-card">
      <div className="plugin-card__top">
        <span className="plugin-card__name">{e.name}</span>
        {e.tier && <window.Pill kind="active">{e.tier}</window.Pill>}
      </div>
      <p className="plugin-card__does">{e.does}</p>
      <div className="plugin-card__meta">
        <span className="plugin-card__cost">{e.cost ? "cost · " + e.cost : "cost · —"}</span>
        {e.scope && <span className="plugin-card__chip">scope · {e.scope}</span>}
        {e.category && <span className="plugin-card__chip">{e.category}</span>}
      </div>
    </div>
  );

  return (
    <div className="st st--plugins">
      <div className="plugins__bar">
        <span className="plugins__search">
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><circle cx="7" cy="7" r="5" stroke="currentColor" strokeWidth="1.4"/><path d="M11 11l3.5 3.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
          <input className="plugins__input" placeholder="search plugins…" value={q} onChange={(e) => setQ(e.target.value)}/>
        </span>
      </div>
      <div className="plugins__filters">
        {PLUGIN_FILTERS.map((x) => (
          <button key={x} className={"chip" + (x === f ? " is-on" : "")} onClick={() => setF(x)}>{x}</button>
        ))}
      </div>

      {/* "cost" is the same sortable board as the Pricing Sheet — one panel, two doors. */}
      {costMode && (
        <div className="plugins__costview">
          <span className="plugins__costlabel">COST SHEET</span>
          <window.CostBoard/>
        </div>
      )}

      {!live
        ? (!costMode && <window.EmptyState tag="empty on purpose" title={PLUGIN_EMPTY.title} body={PLUGIN_EMPTY.body}/>)
        : matches.length === 0
          ? <p className="st__hint">{costMode ? "No cost-sheet plugins yet — the board above is the live sheet." : "No plugins match that."}</p>
          : <div className="plugins__grid">{matches.map(Card)}</div>}
    </div>
  );
}

/* ---- 07 · About Nate — portrait + sections + links (from `about`) ---- */
function StAboutNate() {
  const a = getLC("about") || { name: "", tagline: "", sections: [], links: [] };
  const go = (url) => {
    if (url && url.indexOf("station:") === 0) { const id = url.slice(8); window.NBA.openStation && window.NBA.openStation(id); }
  };
  return (
    <div className="st st--about">
      <div className="about__head">
        <div className="about__avatar" title="Photo placeholder — Nathan adds his own">
          <img src="assets/gold-paws.jpg" alt="" className="about__avatar-img"/>
          <span className="about__avatar-tag">photo — placeholder</span>
        </div>
        <div className="col" style={{ gap: 3, flex: 1, minWidth: 0 }}>
          <span className="about__name">{a.name}</span>
          <span className="about__tagline">{a.tagline}</span>
        </div>
      </div>

      {(a.sections || []).map((s, k) => (
        s.heading
          ? (
            <div key={k} className={"about__section" + (s.placeholder ? " is-placeholder" : "")}>
              <span className="about__section-h">{s.heading}</span>
              {s.placeholder && <window.Tag kind="paper">placeholder</window.Tag>}
              <p className="about__section-b">{s.body}</p>
            </div>
          )
          : <p key={k} className="about__intro">{s.body}</p>
      ))}

      {(a.links || []).length > 0 && (
        <div className="about__find">
          <span className="about__label">FIND ME</span>
          <div className="about__links">
            {a.links.map((l, k) => {
              const internal = l.url && l.url.indexOf("station:") === 0;
              if (internal) return <button key={k} className="btn btn--ghost btn--sm" onClick={() => go(l.url)}>{l.label} →</button>;
              const cls = k === 0 ? "btn btn--primary btn--sm" : "btn btn--ghost btn--sm";
              return <a key={k} className={cls} href={l.url || "#"} onClick={(e) => { if (!l.url || l.url === "#") e.preventDefault(); }}>{l.label}</a>;
            })}
          </div>
        </div>
      )}
    </div>
  );
}

/* ---- 08 · Community — feed from content + Discord door + gated post ---- */
function StCommunity() {
  const cm = getLC("community") || { lead: "", discordUrl: "#", feed: [] };
  const { requireAuth, account } = window.useAccount();
  const [posts, setPosts] = useLState(() => (cm.feed || []).map((p) => ({ who: p.author, text: p.body, at: p.at })));
  const [composing, setComposing] = useLState(false);
  const [text, setText] = useLState("");
  const [token, setToken] = useLState(null);

  const startPost = () => requireAuth("post to the community", () => setComposing(true));
  const submit = () => {
    if (!token || !text.trim()) return;
    setPosts([{ who: account.handle, text: text.trim(), at: Date.now() }, ...posts]); // your own words, not fabricated members
    setText(""); setToken(null); setComposing(false);
  };

  return (
    <div className="st st--community">
      <p className="cm__blurb">{cm.lead}</p>
      <div className="cm__actions">
        <a className="btn btn--primary btn--sm" href={cm.discordUrl} onClick={(e) => { if (!cm.discordUrl || cm.discordUrl === "#") e.preventDefault(); }}>Join the Discord</a>
        {cm.roadSoFarUrl && <a className="btn btn--ghost btn--sm" href={cm.roadSoFarUrl} onClick={(e) => { if (!cm.roadSoFarUrl || cm.roadSoFarUrl === "#") e.preventDefault(); }}>The Road So Far</a>}
        <button className="btn btn--ghost btn--sm" onClick={startPost}>Share something</button>
      </div>

      {composing && (
        <div className="cm__composer nopan">
          <textarea className="textarea" rows={3} placeholder="a win, an idea, a question…" value={text} onChange={(e) => setText(e.target.value)}/>
          <window.Turnstile onToken={setToken}/>
          <div className="row" style={{ gap: 8, justifyContent: "flex-end" }}>
            <button className="linkbtn" onClick={() => setComposing(false)}>cancel</button>
            <button className="btn btn--warm btn--sm" disabled={!token || !text.trim()} onClick={submit}>post</button>
          </div>
        </div>
      )}

      {posts.length === 0
        ? <window.EmptyState tag="new + quiet" title={COMMUNITY_EMPTY.title} body={COMMUNITY_EMPTY.body}/>
        : (
          <div className="cm__feed">
            {posts.map((p, k) => (
              <div key={k} className="cm__post">
                <span className="cm__post-who">@{p.who}</span>
                <p className="cm__post-text">{p.text}</p>
              </div>
            ))}
          </div>
        )}
    </div>
  );
}

/* ---- 09 · Request Desk — form → your requests with states ---- */
function StRequests() {
  const rq = getLC("requests") || { lead: "", kinds: ["build help"], list: [] };
  const kinds = rq.kinds || ["build help"];
  const { requireAuth, account } = window.useAccount();
  const [kind, setKind] = useLState(kinds[0]);
  const [title, setTitle] = useLState("");
  const [body, setBody] = useLState("");
  const [token, setToken] = useLState(null);
  const [list, setList] = useLState(() => window.NBA.listRequests(window.NBA.currentAccount()));

  const refresh = () => setList(window.NBA.listRequests(window.NBA.currentAccount()));
  const submit = () => {
    requireAuth("open a request", (acct) => {
      if (!token || !title.trim()) return;
      window.NBA.openRequest(acct, { kind, title: title.trim(), body: body.trim(), turnstileToken: token });
      setTitle(""); setBody(""); setToken(null); refresh();
    });
  };

  const stateKind = { open: "pending", "in progress": "active", closed: "mute" };
  return (
    <div className="st st--requests">
      <p className="rq__blurb">{rq.lead}</p>
      <div className="rq__form nopan">
        <div className="rq__kinds">
          {kinds.map((k) => <button key={k} className={"chip" + (k === kind ? " is-on" : "")} onClick={() => setKind(k)}>{k}</button>)}
        </div>
        <input className="input" placeholder="one line: what do you need?" value={title} onChange={(e) => setTitle(e.target.value)}/>
        <textarea className="textarea" rows={2} placeholder="any detail that helps (optional)" value={body} onChange={(e) => setBody(e.target.value)}/>
        {account && <window.Turnstile onToken={setToken}/>}
        <button className="btn btn--warm btn--sm" onClick={submit} disabled={account && (!token || !title.trim())}>
          {account ? "open request" : "sign in to open a request"}
        </button>
      </div>

      <div className="rq__list">
        <span className="rq__list-label">YOUR REQUESTS</span>
        {list.length === 0
          ? <p className="st__hint">Nothing open yet. Anything you send, I read.</p>
          : list.map((r) => (
            <div key={r.id} className="rq__row">
              <span className="rq__id">{r.id}</span>
              <div className="col" style={{ gap: 2, flex: 1, minWidth: 0 }}>
                <span className="rq__title">{r.title}</span>
                <span className="rq__kind">{r.kind}</span>
              </div>
              <window.Pill kind={stateKind[r.state] || "mute"}>{r.state}</window.Pill>
            </div>
          ))}
      </div>
    </div>
  );
}

Object.assign(window, { StPlugins, StAboutNate, StCommunity, StRequests });
