// ─────────────────────────────────────────────────────────────────────────
// Meridian — Recommendations / Signals (wired to /api/recommendations)
// ─────────────────────────────────────────────────────────────────────────
function Recommendations({ theme, onOpenStock, onOpenHermes, store }) {
  const [filter, setFilter] = useState("all");
  const data = store.data;

  const signals = useMemo(() => {
    if (!data) return [];
    const posByKey = {};
    data.positions.forEach((p) => { if (p.ticker) posByKey[p.ticker.toUpperCase()] = p; if (p.isin) posByKey[p.isin.toUpperCase()] = p; });
    return data.recs.map((r) => {
      const pos = posByKey[(r.sym || "").toUpperCase()] || posByKey[(r.isin || "").toUpperCase()];
      return {
        t: r.sym, isin: r.isin, name: r.name || r.sym,
        sector: pos ? pos.sector : "—",
        signal: API.map.labelToSignal(r.label),
        label: r.label,
        conviction: API.map.convictionFromScore(r.score),
        score: r.score,
        aaqs: pos ? pos.aaqs : null,
        fvGap: pos ? pos.fvGap : null,
        price: pos ? pos.price : null,
        fair: pos ? pos.fair : null,
        inPortfolio: !!pos,
        why: r.label_reason,
        invalidators: r.invalidators || [],
        tax: r.tax_context,
      };
    }).sort((a, b) => ({ buy: 0, hold: 1, sell: 2 }[a.signal] - { buy: 0, hold: 1, sell: 2 }[b.signal]) || ((b.fvGap || 0) - (a.fvGap || 0)));
  }, [data]);

  const items = signals.filter((s) => filter === "all" || s.signal === filter);
  const counts = {
    all: signals.length,
    buy: signals.filter(s=>s.signal==="buy").length,
    hold: signals.filter(s=>s.signal==="hold").length,
    sell: signals.filter(s=>s.signal==="sell").length,
  };
  const convColor = { High: "var(--sage-700)", Medium: "var(--fg-2)", Low: "var(--fg-3)" };

  return (
    <div className="rise">
      <PageHeader title="Recommendations" subtitle="Every holding scored on quality and value, with a clear call and the reasoning behind it."
        actions={<button className="btn btn-sm" onClick={onOpenHermes}><Icon name="sparkles" size={13} /> Ask Hermes</button>} />

      {store.loading ? (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(360px, 1fr))", gap: 14 }}>{[0,1,2,3].map(i => <SkelCard key={i} lines={3} />)}</div>
      ) : store.error ? (
        <Card><EmptyState icon="cloud-off" title="Couldn't load recommendations" body={store.error.message} action={<button className="btn btn-sm" onClick={store.reload}>Retry</button>} /></Card>
      ) : signals.length === 0 ? (
        <Card><EmptyState icon="git-fork" title="No recommendations yet" body="The engine builds calls after a portfolio refresh. Run a refresh from the top bar, then check back." /></Card>
      ) : (
      <>
      {/* signal summary */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12, marginBottom: 18 }}>
        {[["buy", "Buy"], ["hold", "Hold"], ["sell", "Sell"]].map(([k, label]) => (
          <button key={k} onClick={() => setFilter(filter === k ? "all" : k)} className="card card-hover" style={{ textAlign: "left", cursor: "pointer", borderColor: filter === k ? `var(--${k}-accent)` : "var(--border-1)", padding: 16 }}>
            <Row justify="space-between" align="center">
              <span className={"badge badge-" + k} style={{ fontSize: 12, padding: "3px 11px" }}>{label}</span>
              <span className="mono" style={{ fontSize: 24, fontWeight: 600 }}>{counts[k]}</span>
            </Row>
            <div className="muted" style={{ fontSize: 12, marginTop: 8 }}>
              {k === "buy" ? "below fair value · quality intact" : k === "hold" ? "fairly valued · let it compound" : "ahead of fair value · consider trimming"}
            </div>
          </button>
        ))}
      </div>

      <Row justify="space-between" wrap style={{ gap: 12, marginBottom: 16 }}>
        <div className="segmented">
          {[["all", "All"], ["buy", "Buy"], ["hold", "Hold"], ["sell", "Sell"]].map(([k, l]) => (
            <button key={k} className={filter === k ? "active" : ""} onClick={() => setFilter(k)}>{l} <span className="mono" style={{ opacity: 0.6 }}>{counts[k]}</span></button>
          ))}
        </div>
        <span className="muted" style={{ fontSize: 12.5 }}>Sorted by signal, then fair-value gap</span>
      </Row>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(360px, 1fr))", gap: 14 }}>
        {items.map((s) => (
          <div key={s.t} className="card" style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            <Row justify="space-between" align="flex-start">
              <button onClick={() => s.inPortfolio && onOpenStock(s.t)} style={{ background: "none", border: 0, padding: 0, textAlign: "left", cursor: s.inPortfolio ? "pointer" : "default" }}>
                <Row gap={8} align="center">
                  <span style={{ fontWeight: 600, fontSize: 16, letterSpacing: "-0.01em" }}>{s.name}</span>
                  {s.inPortfolio ? <span className="badge badge-signal" style={{ fontSize: 10 }}>Held</span> : <span className="chip chip-tinted" style={{ fontSize: 10 }}>Watchlist</span>}
                </Row>
                <div className="mono muted" style={{ fontSize: 11.5, marginTop: 2 }}>{s.t} · {s.sector}</div>
              </button>
              <SignalBadge signal={s.signal} size="lg" />
            </Row>

            {/* metrics */}
            <Row gap={0} style={{ marginTop: 14, marginBottom: 12, borderRadius: "var(--radius-3)", background: "var(--bg-sunken)", overflow: "hidden" }}>
              <div style={{ flex: 1, padding: "10px 12px" }}>
                <div className="kpi-label" style={{ fontSize: 10 }}>AAQS</div>
                <div className="mono" style={{ fontSize: 16, fontWeight: 600, color: aaqsColor(s.aaqs), marginTop: 2 }}>{s.aaqs != null ? fmt.num(s.aaqs) : "—"}</div>
              </div>
              <div style={{ width: 1, background: "var(--border-1)" }} />
              <div style={{ flex: 1, padding: "10px 12px" }}>
                <div className="kpi-label" style={{ fontSize: 10 }}>vs fair value</div>
                <div className="mono" style={{ fontSize: 16, fontWeight: 600, color: s.fvGap == null ? "var(--fg-3)" : s.fvGap >= 0 ? "var(--pos-fg)" : "var(--neg-fg)", marginTop: 2 }}>{s.fvGap != null ? fmt.sPct(s.fvGap) : "—"}</div>
              </div>
              <div style={{ width: 1, background: "var(--border-1)" }} />
              <div style={{ flex: 1, padding: "10px 12px" }}>
                <div className="kpi-label" style={{ fontSize: 10 }}>Conviction</div>
                <div style={{ fontSize: 14, fontWeight: 600, color: convColor[s.conviction], marginTop: 3 }}>{s.conviction}</div>
              </div>
            </Row>

            <Row gap={8} align="flex-start" style={{ flex: 1 }}>
              <Icon name="quote" size={13} style={{ color: "var(--fg-3)", marginTop: 3, flexShrink: 0 }} />
              <p style={{ fontSize: 13, lineHeight: 1.55, margin: 0, color: "var(--fg-1)" }}>{s.why}</p>
            </Row>

            <Row gap={8} style={{ marginTop: 14 }}>
              {s.inPortfolio && <button className="btn btn-sm" style={{ flex: 1 }} onClick={() => onOpenStock(s.t)}><Icon name="bar-chart-3" size={13} /> Details</button>}
              <button className="btn btn-sm" style={{ flex: 1 }} onClick={onOpenHermes}><Icon name="sparkles" size={13} /> Ask Hermes</button>
            </Row>
          </div>
        ))}
      </div>
      </>
      )}
    </div>
  );
}
window.Recommendations = Recommendations;
