/* global React, AURA_DATA, Icon, Spark, EquityChart */
const D2 = window.AURA_DATA;
const { useState, useEffect, useMemo } = React;

function Dashboard({ state }) {
  const { botStatus, activeAccount, openTrades, balance, equity, dayPnL } = state;
  const [perf, setPerf] = useState(null);
  const [signals, setSignals] = useState([]);
  const [sigQuality, setSigQuality] = useState(null);
  const [confirmStart, setConfirmStart] = useState(false);
  const [confirmStop, setConfirmStop] = useState(false);
  const [toast, setToast] = useState(null);
  const [actionLoading, setActionLoading] = useState(false);

  const botActive = botStatus ? botStatus.bot_active : false;
  const accountId = activeAccount ? activeAccount.id : null;

  useEffect(() => {
    if (!accountId) return;
    window.api.performance(accountId, 60).then(setPerf).catch(() => {});
    window.api.signals(accountId, 20).then(setSignals).catch(() => {});
    window.api.signalQuality(accountId, 60).then(setSigQuality).catch(() => {});

    // Poll signals + bot status every 30 s so the feed stays live
    const poll = setInterval(() => {
      window.api.signals(accountId, 20).then(setSignals).catch(() => {});
      window.api.botStatus(accountId).then((s) => { if (s) state.setBotStatus(s); }).catch(() => {});
    }, 30000);
    return () => clearInterval(poll);
  }, [accountId]);

  const equityCurve = useMemo(() => D2.generateEquityCurve(perf ? perf.equity_curve : []), [perf]);
  const pnlSpark = useMemo(() => D2.generateSpark(perf ? perf.equity_curve : [], 24), [perf]);

  const showToast = (msg, type = "success") => {
    setToast({ msg, type });
    setTimeout(() => setToast(null), 2400);
  };

  const startBot = async () => {
    if (!accountId) return;
    setActionLoading(true);
    try {
      await window.api.startBot(accountId);
      showToast("Bot started — scanning markets");
      setConfirmStart(false);
      const s = await window.api.botStatus(accountId);
      if (s) state.setBotStatus(s);
    } catch (err) {
      showToast(err.message || "Failed to start bot", "error");
    } finally {
      setActionLoading(false);
    }
  };

  const stopBot = async () => {
    if (!accountId) return;
    setActionLoading(true);
    try {
      await window.api.stopBot(accountId);
      showToast("Stop signal sent — open positions held", "error");
      setConfirmStop(false);
      const s = await window.api.botStatus(accountId);
      if (s) state.setBotStatus(s);
    } catch (err) {
      showToast(err.message || "Failed to stop bot", "error");
    } finally {
      setActionLoading(false);
    }
  };

  const lastCycle = botStatus && botStatus.last_heartbeat
    ? Math.round((Date.now() - D2.parseUTC(botStatus.last_heartbeat).getTime()) / 1000)
    : null;
  // bot_active can be stale in DB if the worker crashed without calling the finish endpoint
  const botStale = botStatus && botStatus.bot_active && lastCycle != null && lastCycle > 180;

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Dashboard</h1>
          <div className="page-subtitle">
            {activeAccount ? `Live · ${activeAccount.nickname || activeAccount.login} · ${activeAccount.server}` : "No account selected"}
          </div>
        </div>
        <div style={{ marginLeft: "auto" }} className="row">
          <button className="btn ghost" onClick={() => window.location.reload()}><span>{Icon.refresh}</span>Refresh</button>
          <button className="btn" onClick={() => { /* account selector */ }}>{Icon.acct} {activeAccount ? activeAccount.nickname || activeAccount.login : "Select account"}</button>
        </div>
      </div>

      <div className="page-content col">
        <div className="banner warn">
          <span style={{ width: 14, height: 14, color: "var(--amber)" }}>{Icon.alert}</span>
          <span>Trading involves substantial risk of loss. Past performance does not guarantee future results.</span>
        </div>

        {/* Stale bot warning */}
        {botStale && (
          <div className="banner warn">
            <span style={{ width: 14, height: 14, color: "var(--amber)" }}>{Icon.alert}</span>
            <span>
              <strong>Bot worker appears offline</strong> — last heartbeat was {Math.round(lastCycle / 60)} min ago.
              Click <strong>Start Trading</strong> to restart it, or check the AURA-Worker service on the VPS.
            </span>
          </div>
        )}

        {/* Bot control */}
        <div className="bot-control">
          <div className={`bot-status ${botActive && !botStale ? "" : "off"}`}>
            <div className="lamp"><div className="core"></div></div>
            <div className="meta">
              <div className="label">Bot Status</div>
              <div className="name">{botActive && !botStale ? "ACTIVE" : botStale ? "STALE" : "IDLE"}<span className="pill neutral">v1.0</span></div>
              <div className="acct">
                {activeAccount ? `Account #${activeAccount.login} · ${activeAccount.leverage || "1:?"}` : "No account"}
              </div>
            </div>
          </div>
          <div style={{ width: 1, background: "var(--line)", margin: "0 18px" }} />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,auto)", gap: 24, alignItems: "center" }}>
            <div>
              <div className="mono" style={{ fontSize: 10, color: "var(--text-2)", textTransform: "uppercase", letterSpacing: ".14em" }}>Strategy</div>
              <div style={{ fontSize: 13, fontWeight: 500, marginTop: 4 }}>Gold Momentum · EMA 8/21 · M15</div>
            </div>
            <div>
              <div className="mono" style={{ fontSize: 10, color: "var(--text-2)", textTransform: "uppercase", letterSpacing: ".14em" }}>Spread Gate</div>
              <div className="mono" style={{ fontSize: 13, marginTop: 4 }}>
                {botStatus ? `${botStatus.spread != null ? botStatus.spread.toFixed(1) : "—"} pips` : "—"}
              </div>
            </div>
            <div>
              <div className="mono" style={{ fontSize: 10, color: "var(--text-2)", textTransform: "uppercase", letterSpacing: ".14em" }}>Last Cycle</div>
              <div className="mono" style={{ fontSize: 13, marginTop: 4, color: lastCycle != null && lastCycle < 120 ? "var(--green)" : lastCycle != null && lastCycle > 180 ? "var(--red)" : "var(--text-2)" }}>
                {lastCycle != null ? `● ${lastCycle < 60 ? lastCycle + "s" : Math.round(lastCycle/60) + "m"} ago` : botActive ? "● starting…" : "—"}
              </div>
            </div>
          </div>
          <div style={{ marginLeft: "auto", paddingLeft: 24 }} className="row">
            {!botActive ? (
              <button className="btn primary" onClick={() => setConfirmStart(true)} disabled={!activeAccount || actionLoading}>
                {Icon.play} Start Trading
              </button>
            ) : (
              <button className="btn danger" onClick={() => setConfirmStop(true)} disabled={actionLoading}>
                {Icon.stop} Stop Trading
              </button>
            )}
          </div>
        </div>

        {/* Stats */}
        <div className="stat-grid">
          <div className="stat accent">
            <div className="stat-label">Account Balance {Icon.dollar}</div>
            <div className="stat-value"><span className="currency">$</span>{balance != null ? balance.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : "—"}</div>
            <div className="stat-meta">
              <span>Equity ${equity != null ? equity.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : "—"}</span>
            </div>
          </div>
          <div className={`stat ${dayPnL >= 0 ? "pos" : "neg"}`}>
            <div className="stat-label">Today's P&L {Icon.activity}</div>
            <div className={`stat-value ${dayPnL >= 0 ? "pos" : "neg"}`}>{D2.fmtSigned(dayPnL)}</div>
            <div className="stat-meta">
              <span>{openTrades.length} open · Unrealized</span>
            </div>
          </div>
          <div className="stat">
            <div className="stat-label">Win Rate · 30D {Icon.target}</div>
            <div className="stat-value">{perf ? perf.win_rate.toFixed(1) : "—"}<span className="currency" style={{ fontSize: 18 }}>%</span></div>
            <div className="stat-meta">
              <span>PF {perf ? perf.profit_factor.toFixed(2) : "—"}</span>
              <span style={{ color: "var(--text-2)" }}>{perf ? perf.total_trades : "—"} trades</span>
            </div>
          </div>
          <div className="stat">
            <div className="stat-label">Open Positions {Icon.zap}</div>
            <div className="stat-value">{openTrades.length}<span className="currency" style={{ fontSize: 14, marginLeft: 6 }}>/ 5 max</span></div>
            <div className="stat-meta">
              <span>Unrealized {D2.fmtSigned(openTrades.reduce((a, b) => a + (b.pnl || 0), 0))}</span>
            </div>
          </div>
        </div>

        {/* Equity chart + Strategy telemetry */}
        <div className="grid-2-1">
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title"><span className="live-dot"></span>Performance · Last 60 Days</div>
            </div>
            <div style={{ padding: "10px 8px" }}>
              <EquityChart data={equityCurve} height={280} />
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", borderTop: "1px solid var(--line)" }}>
              {[
                { k: "Net P&L", v: perf ? D2.fmtUSD(perf.net_pnl) : "—", c: perf && perf.net_pnl >= 0 ? "pos" : "neg" },
                { k: "Max Drawdown", v: perf ? `-${perf.max_drawdown_pct.toFixed(2)}%` : "—", c: "neg" },
                { k: "Avg Win", v: perf ? D2.fmtUSD(perf.avg_win) : "—", c: "pos" },
                { k: "Avg Loss", v: perf ? D2.fmtUSD(-perf.avg_loss) : "—", c: "neg" },
              ].map((m) => (
                <div key={m.k} style={{ padding: "12px 14px", borderRight: "1px solid var(--line)" }}>
                  <div className="mono" style={{ fontSize: 10, color: "var(--text-2)", textTransform: "uppercase", letterSpacing: ".14em" }}>{m.k}</div>
                  <div className={`mono ${m.c || ""}`} style={{ fontSize: 18, marginTop: 4, fontWeight: 600 }}>{m.v}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Strategy Telemetry</div>
              <span className="pill neutral">live</span>
            </div>
            <div className="kv"><span className="k">ATR (M15)</span><span className="v">{botStatus && botStatus.atr != null ? `${botStatus.atr.toFixed(2)} pts` : "—"}</span></div>
            <div className="kv"><span className="k">Spread</span><span className="v" style={{ color: botStatus && botStatus.spread != null && botStatus.spread <= 2 ? "var(--green)" : "var(--amber)" }}>{botStatus && botStatus.spread != null ? `● ${botStatus.spread.toFixed(1)} pips` : "—"}</span></div>
            <div className="kv"><span className="k">Loss Streak</span><span className="v">{botStatus ? `${botStatus.loss_streak} / 4` : "—"}</span></div>
            <div className="kv"><span className="k">Daily P&L</span><span className={`v ${botStatus && botStatus.daily_pnl >= 0 ? "pos" : "neg"}`}>{botStatus ? D2.fmtSigned(botStatus.daily_pnl) : "—"}</span></div>
            <div className="kv"><span className="k">Circuit Breaker</span><span className="v" style={{ color: botStatus && botStatus.circuit_broken ? "var(--red)" : "var(--green)" }}>{botStatus ? (botStatus.circuit_broken ? "● TRIPPED" : "● OK") : "—"}</span></div>
            <div className="kv"><span className="k">Cycle Latency</span><span className="v" style={{ color: "var(--green)" }}>{botStatus && botStatus.cycle_latency_ms ? `${botStatus.cycle_latency_ms}ms` : "—"}</span></div>
            <div className="kv"><span className="k">Account Status</span><span className="v" style={{ color: activeAccount && activeAccount.status === "connected" ? "var(--green)" : "var(--text-2)" }}>{activeAccount ? `● ${activeAccount.status}` : "—"}</span></div>
          </div>
        </div>

        {/* Signal Quality Analysis */}
        {sigQuality && (
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Signal Quality · Last 60 Days</div>
              <span className="pill neutral">{sigQuality.total_signals} signals</span>
            </div>
            <div style={{ padding: "12px 14px", display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(120px, 1fr))", gap: 8 }}>
              {Object.entries(sigQuality.action_counts || {}).map(([action, count]) => (
                <div key={action} style={{ background: "var(--bg-2)", borderRadius: 6, padding: "8px 10px" }}>
                  <div className="mono" style={{ fontSize: 9, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".1em" }}>{action.replace(/_/g, " ")}</div>
                  <div className="mono" style={{ fontSize: 20, fontWeight: 700, marginTop: 2 }}>{count}</div>
                </div>
              ))}
            </div>
            {sigQuality.by_direction && sigQuality.by_direction.length > 0 && (
              <>
                <div style={{ borderTop: "1px solid var(--line)", padding: "10px 14px 4px", fontSize: 10, color: "var(--text-2)", textTransform: "uppercase", letterSpacing: ".12em", fontFamily: "var(--font-mono)" }}>
                  Trade Outcomes by Bucket
                </div>
                <table className="tbl">
                  <thead>
                    <tr>
                      <th>Bucket</th><th>Group</th><th className="num">Trades</th><th className="num">Win %</th><th className="num">PF</th><th className="num">Avg P&L</th><th className="num">Net P&L</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[
                      ...( sigQuality.by_direction || []).map(r => ({ ...r, group: "Direction" })),
                      ...( sigQuality.by_session || []).map(r => ({ ...r, group: "Session" })),
                      ...( sigQuality.by_rsi_bucket || []).map(r => ({ ...r, group: "RSI" })),
                      ...( sigQuality.by_spread_bucket || []).map(r => ({ ...r, group: "Spread" })),
                    ].map((row, i) => (
                      <tr key={i}>
                        <td style={{ color: "var(--text-2)", fontFamily: "var(--font-mono)", fontSize: 11 }}>{row.bucket}</td>
                        <td><span className="pill neutral" style={{ fontSize: 9 }}>{row.group}</span></td>
                        <td className="num">{row.count}</td>
                        <td className={`num ${row.win_rate >= 50 ? "pos" : "neg"}`}>{row.win_rate.toFixed(1)}%</td>
                        <td className={`num ${row.profit_factor >= 1 ? "pos" : "neg"}`}>{row.profit_factor.toFixed(2)}</td>
                        <td className={`num ${row.avg_pnl >= 0 ? "pos" : "neg"}`}>{D2.fmtSigned(row.avg_pnl)}</td>
                        <td className={`num ${row.net_pnl >= 0 ? "pos" : "neg"}`}>{D2.fmtSigned(row.net_pnl)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </>
            )}
            {(!sigQuality.by_direction || sigQuality.by_direction.length === 0) && (
              <div style={{ padding: "20px 14px", textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>
                No executed trades yet — analysis will appear once trades have P&L data
              </div>
            )}
          </div>
        )}

        {/* Open positions + Signal feed */}
        <div className="grid-2-1">
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title"><span className="live-dot"></span>Open Positions</div>
              <button className="btn ghost sm" onClick={() => window.api.openTrades(accountId).then(state.setOpenTrades)}>{Icon.refresh}</button>
            </div>
            {openTrades.length === 0 ? (
              <div style={{ padding: "32px 14px", textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>
                No open positions
              </div>
            ) : (
              <table className="tbl">
                <thead><tr><th>Ticket</th><th>Dir</th><th className="num">Entry</th><th className="num">SL / TP</th><th className="num">Vol</th><th className="num">P&L</th><th>Duration</th></tr></thead>
                <tbody>
                  {openTrades.map((p) => (
                    <tr key={p.ticket}>
                      <td style={{ color: "var(--text-3)" }}>#{p.ticket}</td>
                      <td><span className={`pill ${p.direction === "BUY" ? "buy" : "sell"}`}>{p.direction}</span></td>
                      <td className="num">{p.entry_price.toFixed(2)}</td>
                      <td className="num" style={{ color: "var(--text-3)", fontSize: 11 }}>{p.sl.toFixed(2)} / {p.tp.toFixed(2)}</td>
                      <td className="num">{p.volume.toFixed(2)}</td>
                      <td className={`num ${(p.pnl || 0) >= 0 ? "pos" : "neg"}`} style={{ fontWeight: 600 }}>{D2.fmtSigned(p.pnl || 0)}</td>
                      <td className="mono" style={{ color: "var(--text-2)" }}>{D2.fmtDuration(p.open_time)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title"><span className="live-dot"></span>Recent Signals</div>
              <span className="pill neutral" style={{ fontSize: 9 }}>auto-refresh 30s</span>
            </div>
            <div style={{ maxHeight: 360, overflowY: "auto" }}>
              {signals.length === 0 ? (
                <div style={{ padding: "32px 14px", textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>
                  {botStale ? "Bot offline — no signals received" : "No signals yet — bot will log activity here"}
                </div>
              ) : (() => {
                const interesting = signals.filter(s => s.action !== "no_signal");
                const idle = signals.filter(s => s.action === "no_signal");
                return (
                  <>
                    {interesting.length === 0 && idle.length > 0 && (
                      <div style={{ padding: "8px 14px", fontSize: 10, color: "var(--text-3)", fontFamily: "var(--font-mono)", borderBottom: "1px solid var(--line)" }}>
                        {idle.length} idle cycles — EMA8/21 trending without crossover · last {D2.fmtDateTime(idle[0].created_at)}
                      </div>
                    )}
                    {interesting.slice(0, 10).map((s, i) => (
                      <div key={s.id || i} className="feed-item">
                        <span className="feed-time">{D2.fmtDateTime(s.created_at)}</span>
                        <span className="feed-msg" style={{ fontSize: 11, lineHeight: 1.4 }}>{s.reasoning}</span>
                        <span className={`feed-amt pill ${s.direction === "BUY" ? "buy" : s.direction === "SELL" ? "sell" : "neutral"}`} style={{ fontSize: 9 }}>{s.direction || s.action}</span>
                      </div>
                    ))}
                    {interesting.length === 0 && (
                      <div style={{ padding: "8px 14px 4px" }}>
                        {idle.slice(0, 3).map((s, i) => (
                          <div key={s.id || i} className="feed-item" style={{ opacity: 0.5 }}>
                            <span className="feed-time">{D2.fmtDateTime(s.created_at)}</span>
                            <span className="feed-msg" style={{ fontSize: 10, color: "var(--text-3)" }}>{s.reasoning}</span>
                          </div>
                        ))}
                      </div>
                    )}
                  </>
                );
              })()}
            </div>
          </div>
        </div>
      </div>

      {confirmStart && (
        <div className="modal-backdrop" onClick={() => setConfirmStart(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <h3>Start the bot?</h3>
            <p>The bot will begin scanning markets and may open XAUUSD positions per your configured strategy.</p>
            <div className="modal-actions">
              <button className="btn ghost" onClick={() => setConfirmStart(false)}>Cancel</button>
              <button className="btn primary" onClick={startBot} disabled={actionLoading}>Start Trading</button>
            </div>
          </div>
        </div>
      )}
      {confirmStop && (
        <div className="modal-backdrop" onClick={() => setConfirmStop(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <h3>Stop the bot?</h3>
            <p>New trades will be paused. Open positions will remain — close them manually from Active Trades.</p>
            <div className="modal-actions">
              <button className="btn ghost" onClick={() => setConfirmStop(false)}>Cancel</button>
              <button className="btn danger" onClick={stopBot} disabled={actionLoading}>Stop Trading</button>
            </div>
          </div>
        </div>
      )}
      {toast && <div className={`toast ${toast.type}`}>{toast.msg}</div>}
    </>
  );
}

window.Dashboard = Dashboard;
