/* ═══════════════════════════════════════════════════════════════
   TRADING screen — cockpit positions actives
   Chart lightweight par position + actions rapides + KPIs live
   ═══════════════════════════════════════════════════════════════ */

const { useEffect: useEffectT, useRef: useRefT, useState: useStateT, useMemo: useMemoT } = React;
const TF_BAR_T = { M1:"1m", M5:"5m", M15:"15m", H1:"1H", H4:"4H" };

function TradingScreen() {
  const store = window.useStore ? window.useStore() : {};
  const positions = store.POSITIONS || [];
  const [filter, setFilter] = useStateT("all");

  const filtered = positions.filter(p => {
    if (filter === "all")    return true;
    if (filter === "paper")  return !p.isReal;
    if (filter === "real")   return p.isReal;
    if (filter === "long")   return p.direction === "LONG";
    if (filter === "short")  return p.direction === "SHORT";
    return true;
  });

  // KPIs live
  const totalPnl   = positions.reduce((s, p) => s + (p.pnlEur || 0), 0);
  const longCount  = positions.filter(p => p.direction === "LONG").length;
  const shortCount = positions.filter(p => p.direction === "SHORT").length;
  const capital    = store.STATUS?.capital || 200;
  const expoSum    = positions.reduce((s, p) => s + (p.entry * (p.qty || 1)), 0);
  const expoPct    = capital > 0 ? (expoSum / (capital * 10)) * 100 : 0;
  const now        = Date.now();
  const avgDur     = positions.length === 0 ? 0
                   : positions.reduce((s, p) => s + (p.raw?.entry_ts_ms ? (now - p.raw.entry_ts_ms) : 0), 0) / positions.length;

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h2>Trading Center <span className="mono muted" style={{ fontSize:14, fontWeight:400, marginLeft:8 }}>{positions.length} actives</span></h2>
          <div className="sub mono">Cockpit · gestion positions ouvertes · WS live 300ms</div>
        </div>
        <div className="chips" style={{ flex:"none" }}>
          {[
            { id:"all",   l:"Toutes",  n: positions.length },
            { id:"paper", l:"PAPER",   n: positions.filter(p => !p.isReal).length },
            { id:"real",  l:"RÉEL",    n: positions.filter(p =>  p.isReal).length },
            { id:"long",  l:"LONG",    n: longCount },
            { id:"short", l:"SHORT",   n: shortCount },
          ].map(c => (
            <div key={c.id} className={`chip ${filter===c.id?"active":""}`} onClick={()=>setFilter(c.id)}>
              {c.l} <span className="count">{c.n}</span>
            </div>
          ))}
        </div>
      </div>

      {/* KPIs LIVE */}
      <div className="kpi-grid" style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit, minmax(200px,1fr))", gap:16 }}>
        <div className="card pad kpi-card">
          <div className="kpi-label"><span className="caption">P&L OUVERT</span></div>
          <div className="kpi-main">
            <span className="mono" style={{ fontSize:28, fontWeight:600, color: totalPnl >= 0 ? "var(--bull)":"var(--bear)", letterSpacing:"-0.03em" }}>
              {totalPnl >= 0 ? "+" : ""}{totalPnl.toFixed(2)}€
            </span>
          </div>
          <div className="kpi-foot muted" style={{ fontSize:11 }}>non réalisé · live</div>
        </div>
        <div className="card pad kpi-card">
          <div className="kpi-label"><span className="caption">POSITIONS</span></div>
          <div className="kpi-main">
            <span className="mono primary" style={{ fontSize:28, fontWeight:600 }}>{positions.length}</span>
          </div>
          <div className="kpi-foot muted" style={{ fontSize:11 }}>
            <span className="bull">▲ {longCount} LONG</span> · <span className="bear">▼ {shortCount} SHORT</span>
          </div>
        </div>
        <div className="card pad kpi-card">
          <div className="kpi-label"><span className="caption">EXPOSITION</span></div>
          <div className="kpi-main">
            <span className="mono primary" style={{ fontSize:28, fontWeight:600 }}>{expoPct.toFixed(0)}%</span>
          </div>
          <div className="kpi-foot muted" style={{ fontSize:11 }}>capital engagé · {expoSum.toFixed(0)}€</div>
        </div>
        <div className="card pad kpi-card">
          <div className="kpi-label"><span className="caption">TEMPS MOYEN</span></div>
          <div className="kpi-main">
            <span className="mono primary" style={{ fontSize:28, fontWeight:600 }}>{fmtDuration(avgDur)}</span>
          </div>
          <div className="kpi-foot muted" style={{ fontSize:11 }}>durée ouverte moyenne</div>
        </div>
      </div>

      {/* POSITIONS */}
      {filtered.length === 0 ? (
        <div className="card pad" style={{ display:"grid", placeItems:"center", padding:60, gap:16, textAlign:"center" }}>
          <div style={{ width:64, height:64, borderRadius:"50%", background:"var(--accent-soft)", display:"grid", placeItems:"center" }}>
            <Icon.TrendUp size={28} style={{ color:"var(--accent-400)" }}/>
          </div>
          <div>
            <h3 style={{ margin:0, fontSize:18, color:"var(--text-primary)" }}>Aucune position active</h3>
            <p className="muted" style={{ fontSize:13, marginTop:8 }}>
              {filter === "all" ? "Aucun trade ouvert pour l'instant." : `Aucune position dans le filtre "${filter}".`}
            </p>
          </div>
          <button className="btn primary" onClick={()=>window.location.hash="#/signaux"}>
            <Icon.Zap size={13}/> Aller voir les Signaux
          </button>
        </div>
      ) : (
        <div style={{ display:"flex", flexDirection:"column", gap:16 }}>
          {filtered.map(p => <TradingPositionCard key={p.id} position={p}/>)}
        </div>
      )}
    </div>
  );
}

/* ─── Position card avec chart embarqué + actions ───────────────── */
function TradingPositionCard({ position: p }) {
  const containerRef = useRefT(null);
  const seriesRef    = useRefT(null);
  const [tf, setTf]  = useStateT("M15");
  const [candles, setCandles] = useStateT([]);
  const store        = window.useStore ? window.useStore() : {};
  const livePx       = (store.PRICES && store.PRICES[p.pair]) || p.current;
  const KEY          = new URLSearchParams(location.search).get("key");
  const [now, setNow] = useStateT(Date.now());
  useEffectT(() => { const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, []);

  const fullPair = (p.pair + "/USDT:USDT");
  const duration = p.raw?.entry_ts_ms ? (now - p.raw.entry_ts_ms) : 0;

  // % distances
  const isLong  = p.direction === "LONG";
  const slDist  = p.sl  ? ((livePx - p.sl)  / livePx * 100 * (isLong ? 1 : -1)) : 0;
  const tp1Dist = p.tp1 ? ((p.tp1 - livePx) / livePx * 100 * (isLong ? 1 : -1)) : 0;
  const tp2Dist = p.tp2 ? ((p.tp2 - livePx) / livePx * 100 * (isLong ? 1 : -1)) : 0;
  // attention : slDist négative en LONG si prix proche du SL (à corriger)
  // formule directe : pct distance from livePx to target
  const dist = (target) => target ? ((target - livePx) / livePx * 100) : 0;
  const slPct  = dist(p.sl);
  const tp1Pct = dist(p.tp1);
  const tp2Pct = dist(p.tp2);

  // Fetch candles
  useEffectT(() => {
    const bar = TF_BAR_T[tf] || "15m";
    fetch(`/api/candles?pair=${encodeURIComponent(fullPair)}&bar=${bar}&limit=120`, { credentials: "include" })
      .then(r => r.json())
      .then(j => {
        const arr = (j.candles || []).map(c => ({
          time: Math.floor(c.t / 1000),
          open: c.open, high: c.high, low: c.low, close: c.close,
        }));
        setCandles(arr);
      }).catch(() => {});
  }, [tf, p.pair]);

  // Chart init
  useEffectT(() => {
    if (!containerRef.current || !window.LightweightCharts || candles.length < 2) return;
    const { createChart } = window.LightweightCharts;
    const chart = createChart(containerRef.current, {
      width: containerRef.current.clientWidth,
      height: 260,
      layout: { background:{ type:"solid", color:"transparent" }, textColor:"#6B678F", fontFamily:"Geist Mono, monospace" },
      grid: { vertLines:{ color:"#1F1F3A" }, horzLines:{ color:"#1F1F3A" } },
      crosshair: { mode:0 },
      rightPriceScale: { borderColor:"#2A2A4D", textColor:"#6B678F" },
      timeScale: { borderColor:"#2A2A4D", timeVisible:true, secondsVisible:false },
    });
    const cs = chart.addCandlestickSeries({
      upColor:"#10B981", downColor:"#EF4444",
      wickUpColor:"#10B981", wickDownColor:"#EF4444",
      borderVisible:false,
    });
    cs.setData(candles);
    seriesRef.current = cs;

    // Lignes ENTRY / SL / TP1 / TP2
    if (p.entry) cs.createPriceLine({ price:p.entry, color:"#A855F7", lineWidth:2, lineStyle:0, title:"ENTRY", axisLabelVisible:true });
    if (p.sl)    cs.createPriceLine({ price:p.sl,    color:"#EF4444", lineWidth:1, lineStyle:2, title:"SL",    axisLabelVisible:true });
    if (p.tp1)   cs.createPriceLine({ price:p.tp1,   color:"#10B981", lineWidth:1, lineStyle:2, title:"TP1",   axisLabelVisible:true });
    if (p.tp2)   cs.createPriceLine({ price:p.tp2,   color:"#10B981", lineWidth:1, lineStyle:2, title:"TP2",   axisLabelVisible:true });

    // Marker entrée
    if (p.raw?.entry_ts_ms) {
      const entrySec = Math.floor(p.raw.entry_ts_ms / 1000);
      const closeCandle = candles.find(c => c.time >= entrySec) || candles[candles.length - 1];
      if (closeCandle) {
        cs.setMarkers([{
          time: closeCandle.time,
          position: isLong ? "belowBar" : "aboveBar",
          color: isLong ? "#10B981" : "#EF4444",
          shape: isLong ? "arrowUp" : "arrowDown",
          text: `${p.direction} @${fmtNum(p.entry)}`,
        }]);
      }
    }

    chart.timeScale().fitContent();
    const ro = new ResizeObserver(() => {
      if (containerRef.current) chart.applyOptions({ width: containerRef.current.clientWidth, height: 260 });
    });
    ro.observe(containerRef.current);
    return () => { ro.disconnect(); seriesRef.current = null; chart.remove(); };
  }, [candles, tf]);

  // Live tick → update dernière bougie
  useEffectT(() => {
    if (!livePx || !seriesRef.current || candles.length === 0) return;
    const last = candles[candles.length - 1];
    seriesRef.current.update({
      time:  last.time,
      open:  last.open,
      high:  Math.max(last.high, livePx),
      low:   Math.min(last.low,  livePx),
      close: livePx,
    });
  }, [livePx]);

  // Actions
  async function closeAll() {
    if (!confirm(`Fermer 100% ${p.pair} ${p.direction} ?`)) return;
    await window.fbClosePos(p);
    emitToast({ type:"success", msg:`Position ${p.pair} fermée` });
  }
  async function closeHalf() {
    if (!p.isReal) {
      emitToast({ type:"warn", msg:"Clôture partielle dispo uniquement sur positions RÉELLES" });
      return;
    }
    if (!confirm(`Fermer 50% de ${p.pair} ${p.direction} ?`)) return;
    try {
      await fetch(`/api/close_real_partial/${p.raw.instId}/50`, { method:"POST", credentials:"include" });
      emitToast({ type:"success", msg:"50% fermé" });
    } catch (e) { emitToast({ type:"error", msg:e.message }); }
  }
  async function moveBreakEven() {
    if (p.isReal) {
      emitToast({ type:"warn", msg:"Break-even auto dispo uniquement sur PAPER pour l'instant" });
      return;
    }
    try {
      const r = await fetch(`/api/move_sl_be/${p.id}`, { method:"POST", credentials:"include" }).then(r => r.json());
      emitToast({ type: r.ok?"success":"error", msg: r.ok?`SL → BE @${r.new_trail_sl}` : (r.msg||"erreur") });
    } catch (e) { emitToast({ type:"error", msg:e.message }); }
  }

  const pnlUp = p.pnlEur >= 0;
  const pnlColor = pnlUp ? "var(--bull)" : "var(--bear)";

  return (
    <div className="card" style={{ overflow:"hidden" }}>
      {/* HEADER */}
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"14px 18px", borderBottom:"1px solid var(--border-subtle)", flexWrap:"wrap", gap:12 }}>
        <div style={{ display:"flex", alignItems:"center", gap:12, flexWrap:"wrap" }}>
          <PairLogo pair={p.pair} size={32}/>
          <div style={{ display:"flex", flexDirection:"column", gap:2 }}>
            <div style={{ display:"flex", alignItems:"center", gap:8 }}>
              <span style={{ fontSize:15, fontWeight:600, color:"var(--text-primary)" }}>{p.pair}/USDT</span>
              <DirBadge dir={p.direction}/>
              <span className="mono" style={{ padding:"2px 8px", borderRadius:"var(--radius-full)", background:"var(--bg-surface)", color:"var(--warn)", border:"1px solid rgba(245,158,11,0.3)", fontSize:11, fontWeight:600 }}>
                x{p.lev}
              </span>
              <span className="mono" style={{ padding:"2px 8px", borderRadius:"var(--radius-full)", background:p.isReal?"var(--accent-soft)":"var(--bg-surface)", color:p.isReal?"var(--accent-400)":"var(--info)", border: p.isReal?"1px solid rgba(168,85,247,0.4)":"1px solid var(--border-base)", fontSize:11, fontWeight:600 }}>
                {p.isReal ? "RÉEL" : "PAPER"}
              </span>
            </div>
            <div className="muted mono" style={{ fontSize:11 }}>
              Entrée @{fmtNum(p.entry)} · ouvert depuis {fmtDuration(duration)}
            </div>
          </div>
        </div>
        <div style={{ display:"flex", flexDirection:"column", alignItems:"flex-end", gap:2 }}>
          <span className="mono" style={{ fontSize:28, fontWeight:600, color:pnlColor, letterSpacing:"-0.03em", textShadow:`0 0 12px ${pnlUp?"var(--bull-glow)":"var(--bear-glow)"}` }}>
            {pnlUp ? "+" : ""}{p.pnlEur.toFixed(2)}€
          </span>
          <span className="mono" style={{ fontSize:12, color:pnlColor, opacity:0.85 }}>
            {pnlUp ? "+" : ""}{p.pnlPct.toFixed(2)}%
          </span>
        </div>
      </div>

      {/* TF selector + chart */}
      <div style={{ display:"flex", gap:4, padding:"10px 18px", borderBottom:"1px solid var(--border-subtle)" }}>
        {Object.keys(TF_BAR_T).map(t => (
          <button key={t} className={`btn sm ${tf===t?"primary":"ghost"}`} onClick={()=>setTf(t)} style={{ padding:"4px 10px", fontSize:11 }}>{t}</button>
        ))}
      </div>
      <div ref={containerRef} style={{ width:"100%", height:260 }}></div>

      {/* INFOS LIVE */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit, minmax(140px,1fr))", gap:0, borderTop:"1px solid var(--border-subtle)", borderBottom:"1px solid var(--border-subtle)" }}>
        <InfoCell label="PRIX ACTUEL" val={fmtNum(livePx)} cls="primary"/>
        <InfoCell label="DISTANCE SL"
          val={`${slPct >= 0 ? "+" : ""}${slPct.toFixed(2)}%`}
          cls={Math.abs(slPct) < 0.3 ? "bear" : isLong ? (slPct < 0 ? "bear" : "muted") : (slPct > 0 ? "bear" : "muted")}/>
        <InfoCell label="DISTANCE TP1"
          val={`${tp1Pct >= 0 ? "+" : ""}${tp1Pct.toFixed(2)}%`}
          cls={Math.abs(tp1Pct) < 0.3 ? "bull" : isLong ? (tp1Pct > 0 ? "bull" : "muted") : (tp1Pct < 0 ? "bull" : "muted")}/>
        <InfoCell label="DISTANCE TP2"
          val={`${tp2Pct >= 0 ? "+" : ""}${tp2Pct.toFixed(2)}%`}
          cls={isLong ? (tp2Pct > 0 ? "bull" : "muted") : (tp2Pct < 0 ? "bull" : "muted")}/>
        <InfoCell label="DURÉE" val={fmtDuration(duration)} cls="primary"/>
      </div>

      {/* ACTIONS */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit, minmax(160px,1fr))", gap:8, padding:14 }}>
        <button className="btn" style={{ background:"var(--bear)", color:"white", border:"1px solid var(--bear)" }} onClick={closeAll}>
          <Icon.X size={13}/> FERMER 100%
        </button>
        <button className="btn ghost" onClick={closeHalf} disabled={!p.isReal} title={p.isReal ? "" : "Réel uniquement"}>
          <Icon.X size={13}/> FERMER 50%
        </button>
        <button className="btn ghost" onClick={moveBreakEven} disabled={p.isReal} title={p.isReal ? "Paper uniquement" : ""}>
          <Icon.Shield size={13}/> BREAK-EVEN
        </button>
        <button className="btn ghost" onClick={()=>{ window.location.hash="#/charts"; emitToast({ type:"info", msg:`Naviguer vers ${p.pair} sur Charts` }); }}>
          <Icon.Chart size={13}/> OUVRIR CHART
        </button>
      </div>
    </div>
  );
}

function InfoCell({ label, val, cls }) {
  return (
    <div style={{ padding:"12px 16px", borderRight:"1px solid var(--border-subtle)", display:"flex", flexDirection:"column", gap:4 }}>
      <span className="caption">{label}</span>
      <span className={`mono ${cls || ""}`} style={{ fontSize:14, fontWeight:500 }}>{val}</span>
    </div>
  );
}

function fmtDuration(ms) {
  if (!ms || ms <= 0) return "—";
  const s = Math.floor(ms / 1000);
  if (s < 60)      return `${s}s`;
  if (s < 3600)    return `${Math.floor(s/60)}m ${s%60}s`;
  if (s < 86400)   return `${Math.floor(s/3600)}h ${Math.floor((s%3600)/60)}m`;
  return `${Math.floor(s/86400)}j ${Math.floor((s%86400)/3600)}h`;
}

Object.assign(window, { TradingScreen });
