/* ═══════════════════════════════════════════════════════════════
   SignalCard — the heart of FoxBot Pro
   States: active, wait, invalid, executing
   ═══════════════════════════════════════════════════════════════ */

const { useState: useStateSC } = React;

function SignalCard({ signal, onAction }) {
  const isLong = signal.direction === "LONG";
  const dirColor = isLong ? "var(--bull)" : "var(--bear)";
  const state = signal.state;

  return (
    <div className={`signal-card state-${state}`} data-state={state}>
      {state === "wait" && (
        <div className="sig-banner banner-wait">
          <Icon.Clock size={13} />
          <span className="sig-banner-full">{signal.waitReason || "WAIT · attente confirmation"}</span>
          <span className="sig-banner-short">WAIT</span>
        </div>
      )}
      {state === "invalid" && (
        <div className="sig-overlay">
          <div className="sig-overlay-inner">
            <Icon.X size={20} />
            <span>SIGNAL INVALIDÉ</span>
            <small>{signal.note}</small>
          </div>
        </div>
      )}

      {/* HEADER */}
      <div className="sig-head">
        <div className="sig-head-left">
          <PairLogo pair={signal.pair} size={32} />
          <div className="sig-head-info">
            <div className="sig-head-line">
              <span className="sig-symbol">{signal.pair}/USDT</span>
              <DirBadge dir={signal.direction} />
            </div>
            <div className="sig-head-meta">
              <span className={signal.chg24h >= 0 ? "bull" : "bear"} style={{ fontFamily: "var(--font-mono)" }}>
                {fmtPct(signal.chg24h)}
              </span>
              <span className="muted" style={{ fontSize: 11 }}>24h</span>
              <span className="dim">·</span>
              <span className="mono muted" style={{ fontSize: 11 }}>x{signal.leverage}</span>
            </div>
          </div>
        </div>
        <div className="sig-head-right">
          <Sparkline data={signal.sparkline} width={84} height={28} color="auto" />
          <ScoreBadge score={signal.score} />
        </div>
      </div>

      {/* BODY — 2-column data */}
      <div className="sig-body">
        <div className="sig-col">
          <div className="sig-col-label">SIGNAL · TECH</div>
          <DataRow label="RSI" value={signal.rsi.toFixed(1)} bar={signal.rsi / 100} barColor={signal.rsi > 70 ? "bear" : signal.rsi < 30 ? "bull" : "accent"} />
          <DataRow label="MACD" value={
            <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
              <span className={signal.macd.dir === "up" ? "bull" : "bear"}>
                {signal.macd.dir === "up" ? "▲" : "▼"}
              </span>
              <span className="mono">{fmtNum(signal.macd.v, { sign: true, decimals: 4 })}</span>
            </span>
          } />
          <DataRow label="VOL" value={`${signal.volume}%`} bar={Math.min(1, signal.volume / 200)} barColor={signal.volume > 100 ? "warn" : "accent"} hint="vs MA20" />
          <DataRow label="ATR" value={`${signal.atr.toFixed(2)}%`} />
          <DataRow label="BB" value={
            <span className="mono" style={{ fontSize: 11 }}>
              <span className="muted">{fmtNum(signal.bb[0])}</span>
              <span className="dim"> · </span>
              <span>{fmtNum(signal.bb[1])}</span>
              <span className="dim"> · </span>
              <span className="muted">{fmtNum(signal.bb[2])}</span>
            </span>
          } />
        </div>

        <div className="sig-col">
          <div className="sig-col-label">PLAN DE TRADE</div>
          <PlanRow label="ENTRY" value={signal.entry} accent />
          <PlanRow label="SL" value={signal.sl} kind="sl" />
          <PlanRow label="TP1" value={signal.tp1} kind="tp" />
          <PlanRow label="TP2" value={signal.tp2} kind="tp" />
          <div className="sig-rr">
            <span className="caption">R/R</span>
            <span className={`rr-pill ${signal.rr >= 2 ? "rr-premium" : ""}`}>
              <span className="mono">{signal.rr.toFixed(1)}</span>
            </span>
          </div>
        </div>
      </div>

      {/* TRADE TRACK — horizontal visualization */}
      <TradeTrack signal={signal} />

      {/* QUICK PILLS — valeurs uniques par crypto */}
      <div className="sig-pills">
        <div className="sig-pill">
          <span className="caption">Perte max</span>
          <span className="mono bear">−€{(signal.riskEur || 0).toFixed(2)}</span>
        </div>
        <div className="sig-pill">
          <span className="caption">Gain TP1</span>
          <span className="mono bull">+€{(signal.gainEur || 0).toFixed(2)}</span>
        </div>
        <div className="sig-pill">
          <span className="caption">Gain TP2</span>
          <span className="mono bull">+€{(signal.gainTp2Eur || 0).toFixed(2)}</span>
        </div>
        <div className="sig-pill">
          <span className="caption">Position</span>
          <span className="mono">€{signal.notional ? signal.notional.toFixed(0) : (signal.capital * signal.leverage).toFixed(0)}</span>
        </div>
        <div className="sig-pill">
          <span className="caption">Risque</span>
          <RiskBadge signal={signal} size="sm"/>
        </div>
      </div>

      {/* ACTIONS — 2x2 grid */}
      <div className="sig-actions">
        <ActionBtn variant="paper-long"  disabled={state === "invalid" || state === "executing"} onClick={() => onAction?.("paper-long", signal)}>
          <Icon.Edit size={13} /> PAPER LONG
        </ActionBtn>
        <ActionBtn variant="paper-short" disabled={state === "invalid" || state === "executing"} onClick={() => onAction?.("paper-short", signal)}>
          <Icon.Edit size={13} /> PAPER SHORT
        </ActionBtn>
        <ActionBtn variant="real-long"  disabled={state === "invalid"} loading={state === "executing"} onClick={() => onAction?.("real-long", signal)}>
          <Icon.Flash size={13} /> RÉEL LONG
        </ActionBtn>
        <ActionBtn variant="real-short" disabled={state === "invalid"} onClick={() => onAction?.("real-short", signal)}>
          <Icon.Flash size={13} /> RÉEL SHORT
        </ActionBtn>
      </div>
    </div>
  );
}

function DataRow({ label, value, bar, barColor = "accent", hint }) {
  return (
    <div className="data-row">
      <span className="data-label">{label}</span>
      <div className="data-mid">
        {bar !== undefined && (
          <div className={`gauge ${barColor === "bear" ? "bear" : barColor === "bull" ? "bull" : barColor === "warn" ? "warn" : ""}`}>
            <div className="gauge-fill" style={{ width: `${Math.min(100, bar * 100)}%` }}></div>
          </div>
        )}
        {hint && <span className="data-hint">{hint}</span>}
      </div>
      <span className="data-value mono">{value}</span>
    </div>
  );
}

function PlanRow({ label, value, kind, accent }) {
  let cls = "plan-value mono";
  if (kind === "sl") cls += " bear";
  else if (kind === "tp") cls += " bull";
  else if (accent) cls += " primary";
  return (
    <div className="plan-row">
      <span className="plan-label caption">{label}</span>
      <span className={cls}>{fmtNum(value)}</span>
    </div>
  );
}

/* ─── Trade track (horizontal SL → ENTRY → TP1 → TP2) ─── */
function TradeTrack({ signal }) {
  const isLong = signal.direction === "LONG";
  const { sl, entry, tp1, tp2 } = signal;
  // For LONG: SL < entry < TP1 < TP2.  For SHORT: SL > entry > TP1 > TP2.
  const points = isLong ? [sl, entry, tp1, tp2] : [tp2, tp1, entry, sl];
  const min = Math.min(...points);
  const max = Math.max(...points);
  const range = max - min || 1;
  const pos = (v) => ((v - min) / range) * 100;

  // For LONG: red zone left of entry, green right.
  // For SHORT: red zone right of entry, green left.
  const entryPos = pos(entry);

  return (
    <div className="track-wrap">
      <div className="track">
        {/* zones */}
        {isLong ? (
          <>
            <div className="track-zone zone-loss" style={{ left: 0, width: `${entryPos}%` }}></div>
            <div className="track-zone zone-win" style={{ left: `${entryPos}%`, width: `${100 - entryPos}%` }}></div>
          </>
        ) : (
          <>
            <div className="track-zone zone-win" style={{ left: 0, width: `${entryPos}%` }}></div>
            <div className="track-zone zone-loss" style={{ left: `${entryPos}%`, width: `${100 - entryPos}%` }}></div>
          </>
        )}

        {/* baseline */}
        <div className="track-line"></div>

        {/* markers */}
        <TrackMarker pos={pos(sl)}  label="SL"  value={sl}  color="var(--bear)" align="bottom"/>
        <TrackMarker pos={pos(entry)} label="ENTRY" value={entry} color="var(--accent-400)" big align="top"/>
        <TrackMarker pos={pos(tp1)} label="TP1" value={tp1} color="var(--bull)" align="bottom"/>
        <TrackMarker pos={pos(tp2)} label="TP2" value={tp2} color="var(--bull)" align="top"/>
      </div>
    </div>
  );
}
function TrackMarker({ pos, label, value, color, big, align = "bottom" }) {
  return (
    <div className="track-marker" style={{ left: `${pos}%` }}>
      <div className={`tm-dot ${big ? "big" : ""}`} style={{ background: color, boxShadow: `0 0 10px ${color}` }}></div>
      <div className="tm-label" style={{ color, [align === "top" ? "bottom" : "top"]: "calc(100% + 4px)" }}>
        <span className="caption" style={{ color, fontSize: 10 }}>{label}</span>
        <span className="mono" style={{ fontSize: 11, color: "var(--text-primary)" }}>{fmtNum(value)}</span>
      </div>
    </div>
  );
}

/* ─── Action button (paper/real long/short) ─── */
function ActionBtn({ children, variant, onClick, disabled, loading }) {
  return (
    <button
      className={`act-btn act-${variant} ${loading ? "loading" : ""}`}
      onClick={onClick}
      disabled={disabled || loading}
    >
      <span className="act-content">
        {loading ? <span className="spinner"></span> : children}
      </span>
      <span className="ripple-host"></span>
    </button>
  );
}

Object.assign(window, { SignalCard });
