/* ============================================================
   Dinasty Control — Set Evaluator
   Ranking 144 set berdasarkan performa 7 hari. Data-driven:
   saran parameter diambil dari peer terbaik (strategi sama, EMA/SMA beda).
   ============================================================ */

const SEV_COLOR = { ok: "var(--pos)", warn: "var(--warn)", bad: "var(--neg)", info: "var(--muted)" };
const SEV_LABEL = { ok: "OK", warn: "REVIEW", bad: "FIX", info: "DATA?" };

function PfBadge({ pf, trades }) {
  if (trades === 0) return <span style={{ color: "var(--dim)", fontSize: 11 }}>—</span>;
  const col = pf >= 1.5 ? "var(--pos)" : pf >= 1.0 ? "var(--warn)" : "var(--neg)";
  return <span className="mono" style={{ color: col, fontSize: 12, fontWeight: 600 }}>{pf === 99 ? "∞" : pf.toFixed(2)}</span>;
}

function SevPill({ severity }) {
  const col = SEV_COLOR[severity] || "var(--muted)";
  const lbl = SEV_LABEL[severity] || severity;
  return (
    <span style={{
      display: "inline-block", fontFamily: "var(--mono)", fontSize: 9.5, fontWeight: 700,
      letterSpacing: ".05em", padding: "2px 6px", borderRadius: 3,
      color: col, background: col + "22", border: `1px solid ${col}55`,
    }}>{lbl}</span>
  );
}

function SuggestionBlock({ suggestion }) {
  if (!suggestion || Object.keys(suggestion).length === 0) return null;
  const peer = suggestion._peer_ref;
  const params = Object.entries(suggestion).filter(([k]) => k !== "_peer_ref");
  return (
    <div style={{ marginTop: 10, background: "rgba(236,186,90,.07)", border: "1px solid rgba(236,186,90,.25)", borderRadius: 6, padding: "10px 13px" }}>
      {peer && (
        <div style={{ fontSize: 11, color: "var(--accent)", marginBottom: 6, fontWeight: 600 }}>
          ◆ Referensi peer: <span className="mono">{peer}</span>
        </div>
      )}
      <div style={{ fontSize: 10.5, color: "var(--muted)", marginBottom: 4, letterSpacing: ".05em", textTransform: "uppercase", fontWeight: 600 }}>
        Saran perubahan parameter
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
        {params.map(([k, v]) => (
          <div key={k} style={{ display: "flex", gap: 12, alignItems: "baseline" }}>
            <span className="mono" style={{ fontSize: 11.5, color: "var(--text)", minWidth: 220 }}>{k}</span>
            <span className="mono" style={{ fontSize: 11.5, color: "var(--warn)" }}>{v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function SetRow({ item, rank, expanded, onToggle }) {
  const sev = item.severity || "ok";
  const sevCol = SEV_COLOR[sev];
  const netCol = item.net >= 0 ? "var(--pos)" : "var(--neg)";
  const trIcon = item.trail ? "✓" : "—";

  return (
    <>
      <tr
        className={`mrow clickable${expanded ? " selrow" : ""}`}
        onClick={onToggle}
        style={{ cursor: "pointer" }}
      >
        <td className="sticky-c mono" style={{ fontSize: 11, color: "var(--dim)", paddingLeft: 14 }}>{rank}</td>
        <td className="mono" style={{ fontSize: 11.5, color: sevCol, fontWeight: 600 }}>{item.set_id}</td>
        <td style={{ fontSize: 11 }}>VPS{item.vps}</td>
        <td className="mono" style={{ fontSize: 11 }}>A{String(item.account_no).padStart(2,"0")}</td>
        <td style={{ fontSize: 11 }}>{item.entry}</td>
        <td style={{ fontSize: 11 }}>{item.dir_mode}</td>
        <td>
          <span style={{ fontSize: 10.5, fontWeight: 600, color: item.direction === "BUY" ? "var(--pos)" : "var(--neg)" }}>
            {item.direction}
          </span>
        </td>
        <td style={{ fontSize: 11, color: "var(--muted)" }}>{item.style} {trIcon}</td>
        <td className="mono" style={{ fontSize: 11 }}>{item.trades}</td>
        <td className="mono" style={{ fontSize: 11, color: item.winrate >= 50 ? "var(--pos)" : item.winrate >= 35 ? "var(--warn)" : "var(--neg)" }}>
          {item.trades > 0 ? item.winrate + "%" : "—"}
        </td>
        <td><PfBadge pf={item.pf} trades={item.trades} /></td>
        <td className="mono" style={{ fontSize: 12, fontWeight: 600, color: netCol }}>
          {item.trades > 0 ? (item.net >= 0 ? "+" : "") + item.net.toFixed(1) : "—"}
        </td>
        <td><SevPill severity={sev} /></td>
      </tr>
      {expanded && (
        <tr style={{ background: "rgba(8,44,34,.8)" }}>
          <td colSpan={13} style={{ padding: "12px 16px 14px 40px", borderBottom: "1px solid var(--border)" }}>
            <div style={{ fontSize: 12.5, color: "var(--text)", lineHeight: 1.55, marginBottom: 8 }}>
              {item.diagnosa}
            </div>
            <div style={{ fontSize: 11, color: "var(--dim)", fontFamily: "var(--mono)", marginBottom: 4 }}>
              EMA200=200 · EMA60={item.ema60} · Cross {item.fast}/{item.slow} · SL {item.sl_mult}×ATR · RR {item.rr}
            </div>
            <SuggestionBlock suggestion={item.suggestion} />
          </td>
        </tr>
      )}
    </>
  );
}

function SetEval() {
  const { useState: us, useEffect: ue } = React;
  const [data, setData] = us(null);
  const [err, setErr] = us(null);
  const [loading, setLoading] = us(true);
  const [expanded, setExpanded] = us(null);
  const [sortBy, setSortBy] = us("net");
  const [filterSev, setFilterSev] = us("all");
  const [search, setSearch] = us("");

  ue(() => {
    setLoading(true);
    fetch("/api/set-eval")
      .then(r => r.json())
      .then(d => { setData(d); setLoading(false); })
      .catch(e => { setErr(String(e)); setLoading(false); });
  }, []);

  if (loading) return <div className="placeholder"><p>Memuat evaluasi set...</p></div>;
  if (err) return <div className="placeholder"><p style={{ color: "var(--neg)" }}>Error: {err}</p></div>;
  if (!data) return null;

  const sets = data.sets || [];
  const asOf = data.as_of ? data.as_of.slice(0, 16).replace("T", " ") + " UTC" : "";

  // Stats ringkas
  const active = sets.filter(s => s.trades >= 3);
  const bad = sets.filter(s => s.severity === "bad").length;
  const warn = sets.filter(s => s.severity === "warn").length;
  const totalNet = sets.reduce((a, s) => a + (s.net || 0), 0);

  // Filter + sort
  let visible = sets;
  if (filterSev !== "all") visible = visible.filter(s => s.severity === filterSev);
  if (search.trim()) {
    const q = search.trim().toLowerCase();
    visible = visible.filter(s =>
      s.set_id.toLowerCase().includes(q) ||
      s.entry.toLowerCase().includes(q) ||
      s.direction.toLowerCase().includes(q) ||
      s.style.toLowerCase().includes(q)
    );
  }
  if (sortBy === "net") visible = [...visible].sort((a, b) => (a.net || 0) - (b.net || 0));
  else if (sortBy === "pf") visible = [...visible].sort((a, b) => (a.pf || 0) - (b.pf || 0));
  else if (sortBy === "trades") visible = [...visible].sort((a, b) => (b.trades || 0) - (a.trades || 0));

  const toggle = (id) => setExpanded(prev => prev === id ? null : id);

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", overflow: "hidden" }}>
      {/* Header strip */}
      <div style={{ padding: "14px 18px 0", flexShrink: 0 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
          <div>
            <span style={{ fontWeight: 700, fontSize: 15, letterSpacing: ".04em" }}>Set Evaluator</span>
            <span style={{ color: "var(--dim)", fontSize: 11, marginLeft: 12, fontFamily: "var(--mono)" }}>7 hari terakhir · {asOf}</span>
          </div>
          <button
            onClick={() => { setLoading(true); fetch("/api/set-eval").then(r=>r.json()).then(d=>{setData(d);setLoading(false);}).catch(e=>{setErr(String(e));setLoading(false);}); }}
            style={{ background: "none", border: "1px solid var(--border)", color: "var(--muted)", borderRadius: 5, padding: "4px 10px", cursor: "pointer", fontSize: 11 }}
          >↺ Refresh</button>
        </div>

        {/* Summary chips */}
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 12 }}>
          {[
            { label: "Set aktif", val: active.length, col: "var(--text)" },
            { label: "FIX", val: bad, col: "var(--neg)" },
            { label: "REVIEW", val: warn, col: "var(--warn)" },
            { label: "Net 7d (USC)", val: (totalNet >= 0 ? "+" : "") + totalNet.toFixed(1), col: totalNet >= 0 ? "var(--pos)" : "var(--neg)" },
          ].map(c => (
            <div key={c.label} style={{ background: "var(--panel)", border: "1px solid var(--border)", borderRadius: 6, padding: "7px 13px" }}>
              <div style={{ fontSize: 9.5, color: "var(--muted)", letterSpacing: ".08em", textTransform: "uppercase", fontWeight: 600 }}>{c.label}</div>
              <div className="mono" style={{ fontSize: 15, fontWeight: 700, color: c.col }}>{c.val}</div>
            </div>
          ))}
        </div>

        {/* Filter toolbar */}
        <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 10, flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 4 }}>
            {["all","bad","warn","ok","info"].map(s => (
              <button key={s} onClick={() => setFilterSev(s)} style={{
                background: filterSev === s ? "rgba(236,186,90,.15)" : "none",
                border: filterSev === s ? "1px solid rgba(236,186,90,.5)" : "1px solid var(--border)",
                color: filterSev === s ? "var(--accent)" : "var(--muted)",
                borderRadius: 4, padding: "3px 9px", cursor: "pointer", fontSize: 11,
              }}>
                {s === "all" ? "Semua" : SEV_LABEL[s] || s}
              </button>
            ))}
          </div>
          <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
            <span style={{ fontSize: 10.5, color: "var(--dim)" }}>Sort:</span>
            {[["net","P/L"],["pf","PF"],["trades","Trade"]].map(([k,l]) => (
              <button key={k} onClick={() => setSortBy(k)} style={{
                background: sortBy === k ? "rgba(236,186,90,.12)" : "none",
                border: sortBy === k ? "1px solid rgba(236,186,90,.4)" : "1px solid var(--border)",
                color: sortBy === k ? "var(--accent)" : "var(--muted)",
                borderRadius: 4, padding: "3px 8px", cursor: "pointer", fontSize: 11,
              }}>{l}</button>
            ))}
          </div>
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder="Cari set ID / entry / direction…"
            style={{
              background: "var(--panel-2)", border: "1px solid var(--border)", borderRadius: 4,
              color: "var(--text)", fontSize: 11.5, padding: "4px 10px", outline: "none", minWidth: 200,
            }}
          />
        </div>
      </div>

      {/* Table */}
      <div style={{ flex: 1, overflowY: "auto", padding: "0 18px 18px" }}>
        {visible.length === 0 ? (
          <div className="placeholder" style={{ marginTop: 40 }}>
            <p>Tidak ada set yang sesuai filter. Coba ubah filter atau tunggu data lebih banyak.</p>
          </div>
        ) : (
          <table className="mtable" style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead>
              <tr>
                {["#","Set ID","VPS","Akun","Entry","Mode","Dir","Style","Trade","WR","PF","Net USC","Status"].map(h => (
                  <th key={h} style={{ fontSize: 9.5, letterSpacing: ".07em", color: "var(--muted)", fontWeight: 600,
                    textTransform: "uppercase", padding: "7px 8px", borderBottom: "1px solid var(--border)",
                    textAlign: "left", whiteSpace: "nowrap", position: "sticky", top: 0,
                    background: "var(--bg)", zIndex: 2 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {visible.map((item, idx) => (
                <SetRow
                  key={item.set_id}
                  item={item}
                  rank={item.rank || idx + 1}
                  expanded={expanded === item.set_id}
                  onToggle={() => toggle(item.set_id)}
                />
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
