/* ═══════════════════════════════════════════════════════════════
   JOURNAL screen — trade timeline + stats
   ═══════════════════════════════════════════════════════════════ */

function JournalScreen() {
  const store    = window.useStore ? window.useStore() : (window.MOCK || {});
  const JOURNAL  = Array.isArray(store.JOURNAL) ? store.JOURNAL : [];
  const wins     = JOURNAL.filter(j => j && j.result === "win");
  const losses   = JOURNAL.filter(j => j && j.result === "loss");
  const totalPnl = JOURNAL.reduce((acc, j) => acc + (Number(j && j.pnlEur) || 0), 0);
  const cap      = Number(store.STATUS && store.STATUS.capital) > 0 ? Number(store.STATUS.capital) : 200;
  const pnlPct   = (isFinite(totalPnl) && cap > 0) ? (totalPnl / cap) * 100 : 0;

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h2>Journal</h2>
          <div className="sub mono">Historique des trades · {JOURNAL.length} entrées · 30 derniers jours</div>
        </div>
        <div style={{ display:"flex", gap:8 }}>
          <button className="btn ghost"><Icon.Filter size={13}/> Filtres</button>
          <button className="btn ghost"><Icon.Download size={13}/> Exporter PDF</button>
          <button className="btn primary"><Icon.Plus size={13}/> Note manuelle</button>
        </div>
      </div>

      <div className="journal-stats">
        <StatBlock label="P&L PÉRIODE" value={<PnLDisplay value={totalPnl} pct={pnlPct} variant="lg" />} />
        <StatBlock label="WIN RATE"
          value={
            <div style={{ display:"flex", flexDirection:"column", gap:4 }}>
              <span className="mono primary" style={{ fontSize:18, fontWeight:600 }}>{wins.length + losses.length > 0 ? ((wins.length / (wins.length+losses.length))*100).toFixed(0) : 0}%</span>
              <span className="mono muted" style={{ fontSize:11 }}>{wins.length}W · {losses.length}L</span>
            </div>
          }
        />
        {(() => {
          // Best pair par PnL cumulé
          const byPair = {};
          JOURNAL.forEach(j => { if (j && j.pair) byPair[j.pair] = (byPair[j.pair] || 0) + (j.pnlEur || 0); });
          const bestPair = Object.entries(byPair).sort((a,b)=>b[1]-a[1])[0];
          return (
            <StatBlock label="MEILLEURE PAIRE"
              value={
                <div style={{ display:"flex", flexDirection:"column", gap:4 }}>
                  <span className="mono primary" style={{ fontSize:18, fontWeight:600 }}>{bestPair ? bestPair[0] : "—"}</span>
                  <span className={`mono ${bestPair && bestPair[1]>=0 ? "bull":"bear"}`} style={{ fontSize:11 }}>{bestPair ? (bestPair[1]>=0?"+":"")+bestPair[1].toFixed(2)+"€" : "—"}</span>
                </div>
              }
            />
          );
        })()}
        <StatBlock label="TRADES TOTAL"
          value={
            <div style={{ display:"flex", flexDirection:"column", gap:4 }}>
              <span className="mono primary" style={{ fontSize:18, fontWeight:600 }}>{JOURNAL.length}</span>
              <span className="mono muted" style={{ fontSize:11 }}>{JOURNAL.filter(j=>j.result==="open").length} open</span>
            </div>
          }
        />
      </div>

      <div className="chips">
        {["Tous","Wins","Losses","Open","LONG","SHORT"].map((t,i) => (
          <div key={t} className={`chip ${i===0?"active":""}`}>{t}</div>
        ))}
      </div>

      <div className="journal-timeline">
        {JOURNAL.length === 0 ? (
          <div className="card pad" style={{ display:"grid", placeItems:"center", padding:60, gap:12, textAlign:"center" }}>
            <Icon.Book size={28} style={{ color:"var(--text-dim)" }}/>
            <h3 style={{ margin:0, fontSize:16, color:"var(--text-primary)" }}>Aucun trade dans le journal</h3>
            <p className="muted" style={{ fontSize:12 }}>L'historique apparaîtra ici dès qu'un trade sera clôturé.</p>
          </div>
        ) : (
          JOURNAL.map(j => j && <JournalCard key={j.id || Math.random()} entry={j}/>)
        )}
      </div>
    </div>
  );
}

function StatBlock({ label, value }) {
  return (
    <div className="card pad stat-block">
      <span className="caption">{label}</span>
      <div className="stat-val">{value}</div>
    </div>
  );
}

function JournalCard({ entry }) {
  if (!entry) return null;
  const isOpen = entry.result === "open";
  const isWin  = entry.result === "win";
  const resultColor = isOpen ? "var(--info)" : isWin ? "var(--bull)" : "var(--bear)";
  const pnlEur = Number(entry.pnlEur) || 0;
  const pnlPct = Number(entry.pnlPct) || 0;
  const direction = entry.direction || "LONG";

  return (
    <div className={`jcard jcard-${entry.result}`}>
      <div className="jcard-rail" style={{ background: resultColor }}></div>
      <div className="jcard-time">
        <span className="mono" style={{ fontSize:12, fontWeight:500, color:"var(--text-primary)" }}>{((entry.date || "").split("·")[1] || "").trim() || "—"}</span>
        <span className="caption">{((entry.date || "").split("·")[0] || "").trim() || "—"}</span>
      </div>
      <div className="jcard-body">
        <div className="jcard-head">
          <PairLogo pair={entry.pair} size={28}/>
          <div style={{ display:"flex", flexDirection:"column", gap:2 }}>
            <div style={{ display:"flex", alignItems:"center", gap:8 }}>
              <span style={{ fontSize:14, fontWeight:600, color:"var(--text-primary)" }}>{entry.pair}/USDT</span>
              <DirBadge dir={direction}/>
              <span className={`jres jres-${entry.result}`}>
                {isOpen ? "OPEN" : isWin ? "WIN" : "LOSS"}
              </span>
            </div>
            <div style={{ display:"flex", alignItems:"center", gap:8, fontSize:11 }}>
              <span className="muted">{entry.duration}</span>
              {entry.scoreIn ? (<>
                <span className="dim">·</span>
                <span className="muted">Score entrée <span className="mono primary">{entry.scoreIn}</span></span>
                {entry.scoreOut && entry.scoreOut !== entry.scoreIn && (
                  <>
                    <Icon.ChevronRight size={10} className="dim"/>
                    <span className="muted">sortie <span className={`mono ${entry.scoreOut < entry.scoreIn ? "bear":"bull"}`}>{entry.scoreOut}</span></span>
                  </>
                )}
              </>) : null}
            </div>
          </div>
          <div className="jcard-pnl">
            <span className="mono" style={{ fontSize:20, fontWeight:600, color: pnlEur >= 0 ? "var(--bull)":"var(--bear)" }}>
              {pnlEur >= 0 ? "+":"−"}€{Math.abs(pnlEur).toFixed(2)}
            </span>
            <span className="mono" style={{ fontSize:11, color: pnlEur >= 0 ? "var(--bull)":"var(--bear)", opacity:0.75 }}>
              {fmtPct(pnlPct)}
            </span>
          </div>
        </div>

        <div className="jcard-grid">
          <JTick label="ENTRY" value={entry.entry} color="var(--accent-400)"/>
          <JTick label="SL" value={entry.sl} color="var(--bear)"/>
          <JTick label="TP1" value={entry.tp1} color="var(--bull)"/>
          <JTick label="TP2" value={entry.tp2} color="var(--bull)"/>
          <JTick label="EXIT" value={entry.exit} color={isOpen?"var(--info)":"var(--text-primary)"}/>
        </div>

        {entry.notes && <p className="jcard-notes">{entry.notes}</p>}

        {(entry.tags && entry.tags.length > 0) && (
          <div className="jcard-foot">
            <div className="jtag-row">
              {entry.tags.map(t => <span key={t} className="jtag">{t}</span>)}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function JTick({ label, value, color }) {
  return (
    <div className="jtick">
      <span className="caption" style={{ color }}>{label}</span>
      <span className="mono" style={{ fontSize:12, fontWeight:500, color:"var(--text-primary)" }}>{value ? fmtNum(value) : "—"}</span>
    </div>
  );
}

Object.assign(window, { JournalScreen });
