/* ═══════════════════════════════════════════════════════════════
   FOXBOT PRO — MOBILE DASHBOARD
   Hero P&L · KPI 2x2 · Positions snap · Signaux · Activité
   ═══════════════════════════════════════════════════════════════ */

const { useState: useStateMD, useEffect: useEffectMD, useRef: useRefMD, useMemo: useMemoMD } = React;

function MobileDashboard({ onAction, onRoute }) {
  const { KPI, POSITIONS, ACTIVITY, EQUITY, SIGNALS } = window.MOCK;
  const top3 = useMemoMD(() =>
    [...SIGNALS].filter(s => s.state === "active").sort((a, b) => b.score - a.score).slice(0, 3),
    [SIGNALS]
  );

  return (
    <div className="m-page">
      {/* ─── Hero P&L ─── */}
      <MHero kpi={KPI} positions={POSITIONS.length} sparkData={EQUITY.slice(-40).map(p => p.v)}/>

      {/* ─── KPI Grid 2x2 ─── */}
      <div className="m-kpi-grid">
        <MKpi
          label="WIN RATE"
          value={<><span>{KPI.winRate.val.toFixed(1)}</span><span className="unit">%</span></>}
          foot={
            <>
              <div className="m-kpi-mini-bar bull"><span style={{ width: KPI.winRate.val + "%" }}></span></div>
              <span>{KPI.winRate.wins}W·{KPI.winRate.losses}L</span>
            </>
          }
        />
        <MKpi
          label="TRADES JOUR"
          value={<><span>{KPI.trades.d}</span><span className="unit">/ jour</span></>}
          foot={
            <span>7J <span className="primary">{KPI.trades.w}</span> · 30J <span className="primary">{KPI.trades.m}</span></span>
          }
          sparkline={makeWaveSpark(KPI.trades.w)}
        />
        <MKpi
          label="DRAWDOWN"
          value={<><span className="bear">{fmtPct(KPI.drawdown.current)}</span></>}
          foot={
            <>
              <div className="m-kpi-mini-bar bear"><span style={{ width: (Math.abs(KPI.drawdown.current) / 15 * 100) + "%" }}></span></div>
              <span style={{ whiteSpace: "nowrap" }}>max {fmtPct(KPI.drawdown.max)}</span>
            </>
          }
        />
        <MKpi
          label="POSITIONS"
          value={<><span>{POSITIONS.length}</span><span className="unit">actives</span></>}
          foot={
            <span>Exposition <span className="primary">€2 420</span></span>
          }
          stack={POSITIONS.slice(0, 3).map(p => p.pair)}
        />
      </div>

      {/* ─── Positions actives (horizontal snap) ─── */}
      {POSITIONS.length > 0 && (
        <section>
          <div className="m-section-head" style={{ padding: "0 0 8px" }}>
            <h2>Positions <span className="m-count">{POSITIONS.length}</span></h2>
            <button className="m-see-all" onClick={() => { HAPTIC.tap(); onRoute && onRoute("trading"); }}>Gérer →</button>
          </div>
          <MPositionsScroll positions={POSITIONS}/>
        </section>
      )}

      {/* ─── Top opportunités ─── */}
      <section>
        <div className="m-section-head">
          <h2>Opportunités</h2>
          <button className="m-see-all" onClick={() => { HAPTIC.tap(); onRoute && onRoute("signaux"); }}>Voir tout</button>
        </div>
        <div className="m-sig-stack">
          {top3.map(s => <MSignalRow key={s.id} signal={s} onAction={onAction}/>)}
        </div>
      </section>

      {/* ─── Activité ─── */}
      <section>
        <div className="m-section-head">
          <h2>Activité</h2>
          <span className="m-count" style={{ fontSize: 10 }}>1H</span>
        </div>
        <div style={{ background: "var(--bg-elevated)", border: "1px solid var(--border-subtle)", borderRadius: "var(--m-radius-card-sm)", padding: "4px 14px" }}>
          {ACTIVITY.slice(0, 5).map((a, i) => <MActivityRow key={i} item={a}/>)}
        </div>
      </section>
    </div>
  );
}

/* ─── Hero P&L card ─── */
function MHero({ kpi, positions, sparkData }) {
  const animated = useCountUp(kpi.pnlTotal.eur, 1100);
  const animPct  = useCountUp(kpi.pnlTotal.pct, 1100);
  const up = kpi.pnlTotal.eur >= 0;
  const sparkPath = useMemoMD(() => {
    if (!sparkData || sparkData.length < 2) return "";
    const min = Math.min(...sparkData), max = Math.max(...sparkData);
    const range = max - min || 1;
    const w = 380, h = 60;
    return sparkData.map((v, i) => {
      const x = (i / (sparkData.length - 1)) * w;
      const y = h - 4 - ((v - min) / range) * (h - 8);
      return (i === 0 ? "M" : "L") + x.toFixed(1) + "," + y.toFixed(1);
    }).join(" ");
  }, [sparkData]);

  return (
    <div className="m-hero m-tap">
      <div className="m-hero-label-row">
        <span className="m-hero-label">P&L Total · 30J</span>
        <span className="m-live-dot-wrap">
          <span className="live-dot"></span> LIVE
        </span>
      </div>
      <div className={`m-hero-value ${up ? "" : "bear"}`}>
        <span className="cur">€</span>
        {up ? "+" : "−"}{Math.abs(animated).toLocaleString("fr-FR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
      </div>
      <div className="m-hero-meta">
        <span className={`m-pill ${up ? "bull" : "bear"}`}>
          {up ? <Icon.TrendUp size={11}/> : <Icon.TrendDown size={11}/>}
          {fmtPct(animPct)}
        </span>
        <span className="m-pill accent">
          <Icon.Activity size={11}/> {positions} positions
        </span>
        <MBalancePill/>
      </div>

      {/* background sparkline */}
      <svg viewBox="0 0 380 60" preserveAspectRatio="none"
        style={{
          position: "absolute", left: 0, right: 0, bottom: 0,
          width: "100%", height: 70, opacity: 0.35, pointerEvents: "none",
        }}>
        <defs>
          <linearGradient id="m-hero-grad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={up ? "#10B981" : "#EF4444"} stopOpacity="0.5"/>
            <stop offset="100%" stopColor={up ? "#10B981" : "#EF4444"} stopOpacity="0"/>
          </linearGradient>
        </defs>
        <path d={sparkPath + ` L380,60 L0,60 Z`} fill="url(#m-hero-grad)"/>
        <path d={sparkPath} stroke={up ? "#10B981" : "#EF4444"} strokeWidth="1.4" fill="none" strokeLinecap="round"/>
      </svg>
    </div>
  );
}

/* ─── KPI tile ─── */
function MKpi({ label, value, foot, sparkline, stack }) {
  return (
    <div className="m-kpi">
      <span className="m-kpi-label">{label}</span>
      <div className="m-kpi-value">{value}</div>
      {sparkline && (
        <div style={{ marginTop: 2, marginBottom: -2 }}>
          <svg viewBox="0 0 120 16" preserveAspectRatio="none" width="100%" height="14" style={{ display: "block" }}>
            <path d={sparkline} stroke="var(--accent-400)" strokeWidth="1.3" fill="none" strokeLinecap="round"/>
          </svg>
        </div>
      )}
      {stack && (
        <div style={{ display: "flex", marginTop: 2 }}>
          {stack.map((s, i) => (
            <span key={i} style={{
              width: 18, height: 18, borderRadius: "50%",
              background: "var(--bg-base)",
              border: "1.5px solid var(--bg-elevated)",
              fontFamily: "var(--font-mono)",
              fontSize: 8, fontWeight: 600, color: "var(--text-muted)",
              display: "grid", placeItems: "center",
              marginLeft: i === 0 ? 0 : -6,
            }}>{s.slice(0, 1)}</span>
          ))}
        </div>
      )}
      <div className="m-kpi-foot">{foot}</div>
    </div>
  );
}

/* ─── Solde live (USDC réel ou capital paper selon mode) ─── */
function MBalancePill() {
  const store = window.useStore ? window.useStore() : (window.MOCK || {});
  const st    = store.STATUS || {};
  const mode  = store.MODE || "PAPER";
  const isLive = mode === "LIVE";
  const value  = isLive ? Number(st.usdc || 0) : Number(st.capital || 200);
  const animVal = useCountUp(value, 600, isLive ? 2 : 0);
  return (
    <span className="m-pill" style={{ marginLeft: "auto" }}>
      <span style={{ color: "var(--text-muted)", marginRight: 4 }}>{isLive ? "Solde" : "Capital"}</span>
      <b className="mono" style={{ color: "var(--text-primary)", fontWeight: 600 }}>
        {isLive
          ? "$" + animVal.toFixed(2)
          : "€" + Math.round(animVal)}
      </b>
    </span>
  );
}

function makeWaveSpark(seed) {
  const pts = [];
  for (let i = 0; i < 12; i++) {
    pts.push(8 + Math.sin(i * 0.7 + seed * 0.1) * 4 + Math.cos(i * 0.4) * 2);
  }
  return pts.map((y, i) => (i === 0 ? "M" : "L") + (i * 10) + "," + y.toFixed(1)).join(" ");
}

/* ─── Positions horizontal scroll ─── */
function MPositionsScroll({ positions }) {
  const [active, setActive] = useStateMD(0);
  const ref = useRefMD(null);
  useEffectMD(() => {
    const el = ref.current; if (!el) return;
    const onScroll = () => {
      const cards = el.querySelectorAll(".m-pos-card");
      const center = el.scrollLeft + el.clientWidth / 2;
      let best = 0, bestDist = Infinity;
      cards.forEach((c, i) => {
        const cx = c.offsetLeft + c.offsetWidth / 2;
        const d = Math.abs(cx - center);
        if (d < bestDist) { bestDist = d; best = i; }
      });
      setActive(best);
    };
    el.addEventListener("scroll", onScroll, { passive: true });
    return () => el.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <div className="m-pos-scroll-wrap">
      <div className="m-pos-scroll m-scrollable" ref={ref}>
        {positions.map(p => <MPositionCard key={p.id} p={p}/>)}
      </div>
      {positions.length > 1 && (
        <div className="m-pos-dots">
          {positions.map((_, i) => <span key={i} className={i === active ? "active" : ""}></span>)}
        </div>
      )}
    </div>
  );
}

function MPositionCard({ p }) {
  const animPnl = useCountUp(p.pnlEur);
  const animPct = useCountUp(p.pnlPct);
  const up = p.pnlEur >= 0;
  const sparkData = useMemoMD(() => {
    // synthesize a short live shape from entry → current
    const out = [];
    const start = p.entry, end = p.current;
    for (let i = 0; i < 24; i++) {
      const t = i / 23;
      const wobble = Math.sin(i * 0.8 + p.id.charCodeAt(1)) * (Math.abs(end - start) * 0.4);
      out.push(start + (end - start) * t + wobble);
    }
    return out;
  }, [p.entry, p.current, p.id]);

  return (
    <div className={`m-pos-card ${up ? "" : "bear"}`}>
      <span className="rail"></span>
      <div className="m-pos-head">
        <PairLogo pair={p.pair} size={26}/>
        <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.1, flex: 1, minWidth: 0 }}>
          <span className="sym">{p.pair}/USDT</span>
          <span style={{ fontSize: 11, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>
            {p.direction} · ouvert {p.opened}
          </span>
        </div>
        <span className="lev">×{p.lev}</span>
      </div>

      <div className={`m-pos-pnl ${up ? "bull" : "bear"}`}>
        {up ? "+" : "−"}€{Math.abs(animPnl).toFixed(2)}
        <span className="pct">{fmtPct(animPct)}</span>
      </div>

      <div className="m-pos-chart">
        <MiniLiveSpark data={sparkData} up={up}/>
      </div>

      <div className="m-pos-meta">
        <div>
          <div className="k">Entry</div>
          <div className="v">{fmtNum(p.entry)}</div>
        </div>
        <div>
          <div className="k">SL</div>
          <div className="v bear">{fmtNum(p.sl)}</div>
        </div>
        <div>
          <div className="k">TP1</div>
          <div className="v bull">{fmtNum(p.tp1)}</div>
        </div>
      </div>
    </div>
  );
}

function MiniLiveSpark({ data, up }) {
  const path = useMemoMD(() => {
    if (!data || data.length < 2) return "";
    const min = Math.min(...data), max = Math.max(...data);
    const range = max - min || 1;
    const w = 300, h = 56;
    return data.map((v, i) => {
      const x = (i / (data.length - 1)) * w;
      const y = h - 3 - ((v - min) / range) * (h - 6);
      return (i === 0 ? "M" : "L") + x.toFixed(1) + "," + y.toFixed(1);
    }).join(" ");
  }, [data]);
  const c = up ? "#10B981" : "#EF4444";
  const id = useMemoMD(() => "msp-" + Math.random().toString(36).slice(2, 8), []);
  return (
    <svg viewBox="0 0 300 56" preserveAspectRatio="none" width="100%" height="56" style={{ display: "block" }}>
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={c} stopOpacity="0.32"/>
          <stop offset="100%" stopColor={c} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={path + " L300,56 L0,56 Z"} fill={`url(#${id})`}/>
      <path d={path} stroke={c} strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

/* ─── Compact signal row ─── */
function MSignalRow({ signal, onAction }) {
  const up = signal.direction === "LONG";
  return (
    <div className="m-sig-row" onClick={() => { HAPTIC.tap(); onAction && onAction("preview", signal); }}>
      <PairLogo pair={signal.pair} size={32}/>
      <div className="sym-name">
        <b>{signal.pair}/USDT</b>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 1 }}>
          <DirBadge dir={signal.direction}/>
          <span className="note">{signal.note}</span>
        </div>
      </div>
      <div className="sig-side">
        <ScoreBadge score={signal.score}/>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: up ? "var(--bull)" : "var(--bear)" }}>
          {fmtPct(signal.chg24h)}
        </span>
      </div>
    </div>
  );
}

/* ─── Activity row ─── */
function MActivityRow({ item }) {
  const iconMap = {
    "trend-up":   Icon.TrendUp,
    "trend-down": Icon.TrendDown,
    "zap":        Icon.Zap,
    "shield":     Icon.Shield,
    "x":          Icon.X,
  };
  const Ic = iconMap[item.icon] || Icon.Dot;
  return (
    <div className="m-act-row">
      <div className={`m-act-dot ${item.color}`}>
        <Ic size={14}/>
      </div>
      <div className="m-act-text">
        <div className="title">{item.title}</div>
        <div className="desc">{item.desc}</div>
      </div>
      <span className="time">{item.t}</span>
    </div>
  );
}

Object.assign(window, { MobileDashboard });
