/* X Market Screener (M18) — watchlist + a feed of watched accounts' posts
   scored by engagement velocity, flagging exceptional performers and a
   suggested action. Needs the X read API (elevated) — the feed here is a
   clearly-labelled SIMULATED stand-in. */
(function () {
  const S = window.CroprStore;
  const nf = (n) => Number(n || 0).toLocaleString("en-GB");
  const ACTION = {
    react: { label: "React", icon: "heart", color: "#F04438" },
    share: { label: "Share", icon: "repeat-2", color: "#12B76A" },
    comment: { label: "Comment", icon: "message-circle", color: "#38BDF8" },
  };

  function ScreenerView({ watch, feed, onToast, onGotoReplies }) {
    const [sort, setSort] = React.useState("trend");
    const [handle, setHandle] = React.useState("");
    const items = feed.slice().sort((a, b) => sort === "trend" ? b.trendScore - a.trendScore : b.impressions - a.impressions);

    // Live mode: pull the watched handles' real posts + engagement via the
    // workspace's connected X account. Offline: the store's simulated feed stands in.
    const API = window.LeapAPI;
    const live = !!(API && API.configured());
    const orgId = () => { try { const c = S.getActiveClient && S.getActiveClient(); return c && c._orgId ? c._orgId : null; } catch (e) { return null; } };
    const [loading, setLoading] = React.useState(false);
    const [liveErr, setLiveErr] = React.useState("");
    const refreshLive = React.useCallback(async () => {
      const org = orgId();
      const handles = S.getWatchAccounts().map((a) => a.handle);
      if (!live || !org) return;
      if (!handles.length) { S.setScreenerFeed([]); return; }
      setLoading(true); setLiveErr("");
      try {
        const r = await API.social.screener(org, handles);
        S.setScreenerFeed((r && r.items) || []);
        if (r && r.skipped && r.skipped.length) onToast("Couldn't read " + r.skipped.join(", ") + " — check the handle(s)", "error");
      } catch (e) {
        setLiveErr((e && e.message) || "Live screener failed");
      } finally { setLoading(false); }
    }, [live]);
    // Re-fetch on mount and whenever the watchlist size changes (add/remove).
    React.useEffect(() => { if (live) refreshLive(); }, [live, watch.length]);

    return (
      <div style={{ maxWidth: "var(--page-w)", margin: "0 auto", display: "grid", gridTemplateColumns: "300px minmax(0,1fr)", gap: 20, alignItems: "start" }} className="pulse-grid">
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card pad={18}>
            <SectionTitle icon="eye">Watchlist</SectionTitle>
            <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
              <TextInput value={handle} onChange={setHandle} placeholder="@account" onKeyDown={(e) => { if (e.key === "Enter") { S.addWatch(handle); setHandle(""); } }} />
              <Button variant="secondary" icon="plus" onClick={() => { if (handle.trim()) { S.addWatch(handle); setHandle(""); onToast("Added to watchlist"); } }} />
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {watch.map((a) => (
                <div key={a.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 10px", borderRadius: 10, background: "var(--bg-subtle)" }}>
                  <Avatar color="#38BDF8" initials={a.handle.replace("@", "").slice(0, 2).toUpperCase()} size={24} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 700 }}>{a.handle}</div>
                    {a.notes && <div style={{ fontSize: 10.5, color: "var(--fg3)" }}>{a.notes}</div>}
                  </div>
                  <button onClick={() => S.removeWatch(a.id)} style={{ border: 0, background: "none", cursor: "pointer" }}><Icon name="x" size={14} color="var(--fg3)" /></button>
                </div>
              ))}
              {watch.length === 0 && <div style={{ fontSize: 12, color: "var(--fg3)" }}>Add the X accounts you want to watch.</div>}
            </div>
          </Card>
          {live && !liveErr && (
            <Card pad={16} style={{ background: "var(--success-bg, #E7F6EC)", border: "1px solid #A9DDBB" }}>
              <div style={{ fontSize: 12, color: "#146C43", lineHeight: 1.5, display: "flex", gap: 8 }}><Icon name="radio" size={15} color="#12B76A" /><span><b>Live.</b> Real posts &amp; engagement pulled from watched handles via your connected X account.</span></div>
            </Card>
          )}
          {live && liveErr && (
            <Card pad={16} style={{ background: "var(--warning-bg)", border: "1px solid #F7CE9A" }}>
              <div style={{ fontSize: 12, color: "#8A5A12", lineHeight: 1.5, display: "flex", gap: 8 }}><Icon name="triangle-alert" size={15} color="#B25E09" /><span>{liveErr.indexOf("Connect an X") >= 0 ? "Connect an X account under Clients → Channels to run the live screener." : liveErr}</span></div>
            </Card>
          )}
          {!live && (
            <Card pad={16} style={{ background: "var(--warning-bg)", border: "1px solid #F7CE9A" }}>
              <div style={{ fontSize: 12, color: "#8A5A12", lineHeight: 1.5, display: "flex", gap: 8 }}><Icon name="flask-conical" size={15} color="#B25E09" /><span>Feed is simulated (offline demo). Live scoring runs automatically in live mode with a connected X account.</span></div>
            </Card>
          )}
        </div>

        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <SectionTitle icon="radar">Screener feed · {items.length}</SectionTitle>
            <div style={{ flex: 1 }} />
            <Segmented value={sort} onChange={setSort} options={[{ value: "trend", label: "Trending", icon: "trending-up" }, { value: "performance", label: "Top performers", icon: "flame" }]} />
            <Button size="sm" variant="secondary" icon="refresh-cw" disabled={loading} onClick={() => { if (live) { refreshLive().then(() => onToast("Feed refreshed")); } else { S.refreshScreenerFeed(); onToast("Feed refreshed (simulated)"); } }}>{loading ? "Refreshing…" : "Refresh"}</Button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {items.map((it) => {
              const act = ACTION[it.suggestedAction];
              return (
                <Card key={it.id} pad={16}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                    <Avatar color="#38BDF8" initials={it.account.replace("@", "").slice(0, 2).toUpperCase()} size={26} />
                    <span style={{ fontSize: 13.5, fontWeight: 700 }}>{it.account}</span>
                    {it.performedExceptionally && <Badge color="#B25E09" bg="var(--warning-bg)" dot>Exceptional</Badge>}
                    <div style={{ flex: 1 }} />
                    <Badge color="#3F3AB4" bg="var(--accent-weak)">trend {it.trendScore}</Badge>
                  </div>
                  <div style={{ fontSize: 13.5, color: "var(--fg1)", lineHeight: 1.45, marginBottom: 10 }}>{it.text}</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
                    <span style={{ fontSize: 12, color: "var(--fg3)" }}><Icon name="heart" size={13} style={{ verticalAlign: "-2px" }} /> {nf(it.likes)}</span>
                    <span style={{ fontSize: 12, color: "var(--fg3)" }}><Icon name="repeat-2" size={13} style={{ verticalAlign: "-2px" }} /> {nf(it.reposts)}</span>
                    <span style={{ fontSize: 12, color: "var(--fg3)" }}><Icon name="bar-chart-2" size={13} style={{ verticalAlign: "-2px" }} /> {nf(it.impressions)}</span>
                    <div style={{ flex: 1 }} />
                    <span style={{ fontSize: 11, color: "var(--fg3)" }}>suggested</span>
                    {it.suggestedAction === "comment"
                      ? <Button size="sm" variant="primary" icon={act.icon} onClick={onGotoReplies}>Comment →</Button>
                      : <Badge color={act.color} bg={act.color + "18"} dot>{act.label}</Badge>}
                    <a href={it.url} target="_blank" rel="noreferrer" style={{ fontSize: 12 }}>open ↗</a>
                  </div>
                </Card>
              );
            })}
            {items.length === 0 && <Card pad={40} style={{ textAlign: "center", color: "var(--fg3)" }}>Add accounts to build the feed.</Card>}
          </div>
        </div>
      </div>
    );
  }
  window.ScreenerView = ScreenerView;
})();
