// IndieVertical — scout flow: shortlist dashboard, shared inbox (dev + scout).

function IvScoutDashboard() {
  const { state, api } = useStore();
  const saved = Object.keys(state.shortlist);
  return (
    <div className="pp dir-marquee">
      <IvHeader />
      <div className="app" style={{ flex: 1 }}>
        <IvSidebar items={[
          { label: "My Shortlist", on: true, href: "#/dashboard" },
          { label: "Inbox", href: "#/inbox", dot: ivUnreadCount(state, "scout") > 0 },
        ]} />
        <div className="main">
          <div className="main-h"><h1>My Shortlist</h1></div>
          <p className="reassure">Developers cannot see who has saved their game. Your shortlist is private.</p>
          {saved.length === 0 ? (
            <IvEmptyState
              heading="Your shortlist is empty"
              body="Save games while you browse and they will collect here, with room for your private notes."
              button="Browse games"
              href="#/browse"
            />
          ) : (
            <div className="slist">
              {saved.map((slug) => {
                const g = ivGetGame(state, slug);
                if (!g) return null;
                return (
                  <div key={slug}>
                    <IvGameCard g={g} />
                    <div className="s-note">
                      <div className="n-row">
                        <span className="n-l">Private note</span>
                        <button type="button" className="n-rm" onClick={() => { api.removeShortlist(slug); api.showToast(g.name + " removed from your shortlist"); }}>Remove</button>
                      </div>
                      <textarea
                        className="f-input area"
                        style={{ fontSize: 13 }}
                        placeholder="Why did this one catch your eye?"
                        value={state.shortlist[slug].note}
                        onChange={(e) => api.setNote(slug, e.target.value)}
                      ></textarea>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------- inbox (both roles) ----------
function IvInbox({ threadId }) {
  const { state, api } = useStore();
  const role = state.role;
  const side = role === "dev" ? "dev" : "scout";
  const threads = ivThreadsFor(state, role);
  const live = threads.filter((t) => !t.archived);
  const archived = threads.filter((t) => t.archived);
  const current = threads.find((t) => t.id === threadId) || live[0] || threads[0] || null;
  const [draft, setDraft] = React.useState("");

  React.useEffect(() => { setDraft(""); }, [current && current.id]);
  React.useEffect(() => {
    if (current && current.unreadFor === side) api.markThreadRead(current.id, side);
  }, [current && current.id, current && current.unreadFor, side]);

  const other = (t) => (side === "dev"
    ? { name: t.scoutName, sub: (t.scoutOrg ? t.scoutOrg + " · " : "") + "about " + t.gameName }
    : { name: t.devName, sub: t.gameName });

  const send = () => {
    const text = draft.trim();
    if (!text || !current) return;
    api.sendMessage(current.id, text, side);
    setDraft("");
  };

  return (
    <div className="pp dir-marquee">
      <IvHeader />
      <div className="ibx" style={{ flex: 1 }}>
        <div className="ibx-list">
          <div className="il-h">Inbox</div>
          {threads.length === 0 && (
            <div style={{ padding: "8px 20px 20px" }} className="empty-inline">
              No conversations yet. {side === "scout" ? "Message a developer from any game page." : "When a scout messages you about a game, it lands here."}
            </div>
          )}
          {[...live, ...archived].map((t) => {
            const o = other(t);
            const last = t.messages[t.messages.length - 1];
            return (
              <div key={t.id} className={"thr" + (current && current.id === t.id ? " on" : "")}
                onClick={() => ivGo("#/inbox/" + t.id)}>
                <span className="t-who">{o.name} {t.unreadFor === side && <span className="udot"></span>}{t.archived && <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".05em" }}>Archived</span>}</span>
                <span className="t-game">Re: {t.gameName}</span>
                <span className="t-snip">{last ? last.text : "No messages yet — say hello."}</span>
                {!(current && current.id === t.id) && (
                  <button type="button" className="t-arch" onClick={(e) => { e.stopPropagation(); api.toggleArchive(t.id); }}>
                    {t.archived ? "Restore" : "Archive"}
                  </button>
                )}
              </div>
            );
          })}
        </div>

        {current ? (
          <div className="ibx-view">
            <button type="button" className="ibx-back" onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}>← All conversations</button>
            <div className="ibx-vh">
              <div>
                <div className="vh-who">{other(current).name}</div>
                <div className="vh-sub">{other(current).sub}</div>
              </div>
              {current.game && <a className="vh-link" href={"#/game/" + current.game}>View game page</a>}
            </div>
            <div className="ibx-msgs">
              <div className="notice">We do not verify publishers or review deal terms. Before sharing sensitive details or signing anything, do your own checks.</div>
              {current.messages.length === 0 && (
                <div className="empty-inline" style={{ textAlign: "center" }}>
                  This is the start of your conversation about {current.gameName}. Keep the first message short: who you are, and what caught your eye.
                </div>
              )}
              {current.messages.map((m, i) => {
                const mine = m.from === side;
                const who = mine ? "You" : (m.from === "scout" ? current.scoutName.split(" ")[0] : current.devName);
                return (
                  <div key={i} className={"msg" + (mine ? " out" : "")}>
                    <div className="m-b">{m.text}</div>
                    <div className="m-meta">{who} · {m.date}{mine && m.readDate ? " · Read " + m.readDate.replace(", 2026", "") : ""}</div>
                  </div>
                );
              })}
            </div>
            <div className="compose">
              <div className="c-row">
                <textarea
                  className="f-input"
                  placeholder="Write a reply…"
                  value={draft}
                  onChange={(e) => setDraft(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
                ></textarea>
                <button type="button" className={"btn btn-primary" + (draft.trim() ? "" : " dis")} onClick={send}>Send</button>
              </div>
              <p className="c-note">
                {side === "dev"
                  ? "We will also send you an email when a new message arrives, in case you are not logged in. Scouts reply when they are interested. Silence is not a rejection, and it is not personal."
                  : "We will also send you an email when a new message arrives. Developers see your name and company with every message."}
              </p>
            </div>
          </div>
        ) : (
          <div className="ibx-view" style={{ alignItems: "center", justifyContent: "center", padding: 60 }}>
            <span className="empty-inline">Select a conversation.</span>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { IvScoutDashboard, IvInbox });
