/* eslint-disable */
/**
 * Локальные боты API4ATKA (Grid / Smart-DCA / Basket) — desktop вкладка.
 * Эквивалент мобильной BotsScreen, использует уже существующие window.MobileAPI
 * методы (listLocalBots / startLocalBot / stopLocalBot / deleteLocalBot /
 * createLocalBot / loadMarkPrice).
 *
 * Стили — старые из style.css (.card, .section, .tbl, .btn, .pill, .modal),
 * без перебивающих !important. Дизайн — таблица с live uPnL + liq + worst-case.
 *
 * IIFE-wrap чтобы имена не утекали в global scope (Babel-standalone).
 */
(function () {
const { useState, useEffect, useCallback, useMemo, useRef } = React;

const fmt = (n, d = 2) => {
  const v = Number(n);
  if (!isFinite(v)) return "—";
  return v.toLocaleString("ru-RU", { minimumFractionDigits: d, maximumFractionDigits: d });
};
const fmtPx = (n) => {
  const v = Number(n);
  if (!isFinite(v) || v === 0) return "—";
  if (v > 100) return v.toLocaleString("ru-RU", { maximumFractionDigits: 2 });
  if (v > 1)   return v.toLocaleString("ru-RU", { maximumFractionDigits: 4 });
  return v.toPrecision(5);
};
const pnlCls = (v) => (Number(v) >= 0 ? "pos" : "neg");

// ─────────────────────  LocalBotsTab — главный компонент  ─────────────────────
const LocalBotsTab = ({ activeEx }) => {
  const [bots, setBots] = useState([]);
  const [filter, setFilter] = useState("active");   // active | history
  const [loading, setLoading] = useState(true);
  const [createOpen, setCreateOpen] = useState(false);
  const [tick, setTick] = useState(0);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const r = await window.MobileAPI.listLocalBots();
      setBots(Array.isArray(r) ? r : []);
    } catch (e) {
      console.warn("listLocalBots", e);
      setBots([]);
    }
    setLoading(false);
  }, []);

  useEffect(() => { load(); }, [load]);
  // Auto refresh каждые 15 сек чтобы live uPnL обновлялся
  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 15000);
    return () => clearInterval(id);
  }, []);
  useEffect(() => { if (tick > 0) load(); }, [tick, load]);

  const ACTIVE = ["running", "paused", "starting"];
  const active = useMemo(() => bots.filter(b => ACTIVE.includes(b.state)), [bots]);
  const history = useMemo(() => bots.filter(b => !ACTIVE.includes(b.state)), [bots]);
  const list = filter === "active" ? active : history;

  const totals = useMemo(() => {
    let realized = 0, upnl = 0, inv = 0;
    active.forEach(b => {
      realized += Number(b.total_pnl) || 0;
      upnl += Number(b.live?.unrealized_pnl) || 0;
      inv += Number(b.investment_usdt) || 0;
    });
    return { realized, upnl, total: realized + upnl, inv };
  }, [active]);

  const toggleBot = async (b) => {
    try {
      if (b.state === "running") await window.MobileAPI.stopLocalBot(b.id);
      else await window.MobileAPI.startLocalBot(b.id);
      await load();
    } catch (e) { alert("Ошибка: " + (e.message || e)); }
  };
  const removeBot = async (b) => {
    if (!confirm("Удалить бота " + b.symbol + "?")) return;
    try { await window.MobileAPI.deleteLocalBot(b.id); await load(); }
    catch (e) { alert("Ошибка: " + (e.message || e)); }
  };

  return (
    <>
      {/* Summary KPI */}
      <div className="section">
        <div className="stats-grid">
          <div className="stat-card">
            <div className="stat-label">Активных ботов</div>
            <div className="stat-big">{active.length}</div>
            <div className="stat-sub">
              {active.filter(b => b.bot_type === "grid").length} Grid · {active.filter(b => b.bot_type === "dca").length} DCA · {active.filter(b => b.bot_type === "recurring").length} Basket
            </div>
          </div>
          <div className="stat-card">
            <div className="stat-label">Общий PnL</div>
            <div className={"stat-big " + pnlCls(totals.total)}>
              {totals.total >= 0 ? "+" : ""}{fmt(totals.total)}
            </div>
            <div className="stat-sub">realized + unrealized</div>
          </div>
          <div className="stat-card">
            <div className="stat-label">Unrealized</div>
            <div className={"stat-big " + pnlCls(totals.upnl)}>
              {totals.upnl >= 0 ? "+" : ""}{fmt(totals.upnl)}
            </div>
            <div className="stat-sub">по открытым позициям</div>
          </div>
          <div className="stat-card">
            <div className="stat-label">Инвестиции</div>
            <div className="stat-big mono">{fmt(totals.inv, 0)}</div>
            <div className="stat-sub">USDT в активных ботах</div>
          </div>
        </div>
      </div>

      {/* Tabs + Create */}
      <div className="section">
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
          <div className="segmented">
            <button className={filter === "active" ? "active" : ""} onClick={() => setFilter("active")}>
              Активные <span style={{ color: "var(--text-4)", marginLeft: 4 }}>{active.length}</span>
            </button>
            <button className={filter === "history" ? "active" : ""} onClick={() => setFilter("history")}>
              История <span style={{ color: "var(--text-4)", marginLeft: 4 }}>{history.length}</span>
            </button>
          </div>
          <button className="btn" style={{ background: "var(--accent)", color: "white", borderColor: "var(--accent)", padding: "8px 16px", fontWeight: 600 }}
                  onClick={() => setCreateOpen(true)}>
            + Создать бота
          </button>
        </div>
      </div>

      {/* Бот-таблица */}
      <div className="section">
        {loading ? (
          <div className="card" style={{ padding: 24 }}>
            {Array.from({ length: 3 }).map((_, i) => (
              <div key={i} className="skel-bar" style={{ height: 40, marginBottom: 10 }}/>
            ))}
          </div>
        ) : list.length === 0 ? (
          <EmptyCard
            title={filter === "active" ? "Нет активных ботов" : "История пуста"}
            msg={filter === "active"
              ? "Создай Grid / Smart-DCA / Basket-бота — работает на любой бирже."
              : "Остановленные и завершённые боты появятся здесь."}/>
        ) : (
          <div className="card" style={{ overflow: "auto" }}>
            <table className="tbl">
              <thead>
                <tr>
                  <th>Бот</th>
                  <th>Тип</th>
                  <th>Биржа</th>
                  <th>Сторона</th>
                  <th className="num">Инвест.</th>
                  <th className="num">PnL</th>
                  <th className="num">uPnL</th>
                  <th className="num">Liq.</th>
                  <th>Статус</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {list.map(b => {
                  const upnl = b.live?.unrealized_pnl;
                  const realized = Number(b.total_pnl) || 0;
                  const total = (upnl != null ? realized + upnl : realized);
                  return (
                    <tr key={b.id}>
                      <td>
                        <span className="sym">
                          <CoinIcon sym={(b.symbol || "").replace(/USDT$|USDC$|USD$/, "")}/>
                          <span>
                            <div style={{ fontWeight: 600 }}>{b.symbol}</div>
                            <div className="muted" style={{ fontSize: 10 }}>#{b.id}</div>
                          </span>
                        </span>
                      </td>
                      <td><span className="pill neutral">{(b.bot_type || "").toUpperCase()}</span></td>
                      <td><span className="pill neutral">{(b.exchange || "").toUpperCase()}</span></td>
                      <td>
                        {b.direction === "long"
                          ? <span className="pill long">LONG</span>
                          : b.direction === "short"
                            ? <span className="pill short">SHORT</span>
                            : <span className="pill neutral">{(b.direction || "").toUpperCase()}</span>}
                      </td>
                      <td className="num mono">{fmt(b.investment_usdt, 0)}</td>
                      <td className={"num mono " + pnlCls(total)} style={{ fontWeight: 600 }}>
                        {total >= 0 ? "+" : ""}{fmt(total)}
                      </td>
                      <td className={"num mono " + pnlCls(upnl || 0)}>
                        {upnl != null ? ((upnl >= 0 ? "+" : "") + fmt(upnl)) : "—"}
                      </td>
                      <td className="num mono" style={{ color: "var(--short)" }}>
                        {b.live?.liquidation_price > 0 ? fmtPx(b.live.liquidation_price) : "—"}
                      </td>
                      <td>
                        {b.state === "running"
                          ? <span className="pill long">● running</span>
                          : b.state === "paused"
                            ? <span className="pill" style={{ background: "var(--warn-dim)", color: "var(--warn)" }}>paused</span>
                            : b.state === "error"
                              ? <span className="pill short">error</span>
                              : <span className="pill neutral">{b.state}</span>}
                      </td>
                      <td style={{ textAlign: "right", whiteSpace: "nowrap" }}>
                        {ACTIVE.includes(b.state) && (
                          <button className="btn" style={{ padding: "4px 10px", marginRight: 4 }} onClick={() => toggleBot(b)}>
                            {b.state === "running" ? "⏸" : "▶"}
                          </button>
                        )}
                        <button className="btn" style={{ padding: "4px 10px", color: "var(--short)" }} onClick={() => removeBot(b)}>
                          ✕
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {createOpen && (
        <LocalBotCreateModal
          activeEx={activeEx}
          onClose={() => setCreateOpen(false)}
          onCreated={() => { setCreateOpen(false); load(); }}
        />
      )}
    </>
  );
};

// ─────────────────────  Create Modal с live summary  ─────────────────────
const LocalBotCreateModal = ({ activeEx, onClose, onCreated }) => {
  const [type, setType] = useState("grid");
  const [symbol, setSymbol] = useState("");
  const [direction, setDirection] = useState("long");
  const [invest, setInvest] = useState("100");
  const [lev, setLev] = useState("3");

  // Grid
  const [minPx, setMinPx] = useState("");
  const [maxPx, setMaxPx] = useState("");
  const [gridNum, setGridNum] = useState("20");

  // DCA
  const [dcaInit, setDcaInit] = useState("10");
  const [dcaSafety, setDcaSafety] = useState("10");
  const [dcaStep, setDcaStep] = useState("0.5");
  const [dcaMargMult, setDcaMargMult] = useState("1.5");
  const [dcaMaxSafety, setDcaMaxSafety] = useState("8");
  const [dcaTp, setDcaTp] = useState("1.0");

  const [markPx, setMarkPx] = useState(0);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!symbol) { setMarkPx(0); return; }
    (async () => {
      try {
        const p = await window.MobileAPI.loadMarkPrice(activeEx, symbol);
        const px = Number(p) || 0;
        setMarkPx(px);
        if (type === "grid" && (!minPx || !maxPx) && px > 0) {
          setMinPx((px * 0.95).toPrecision(6));
          setMaxPx((px * 1.05).toPrecision(6));
        }
      } catch {}
    })();
  }, [symbol, activeEx, type]);

  const investNum = parseFloat(invest) || 0;
  const levNum = parseInt(lev) || 1;
  const n = parseInt(gridNum) || 0;

  // Grid live calc
  const perLevelMargin = (type === "grid" && n > 0) ? investNum / n : 0;
  const perLevelNotional = perLevelMargin * levNum;
  const totalNotional = investNum * levNum;
  const isLong = direction === "long";
  let bulkLevels = 0;
  if (type === "grid" && minPx && maxPx && n > 1 && markPx > 0) {
    const lo = parseFloat(minPx), hi = parseFloat(maxPx), step = (hi - lo) / n;
    for (let i = 0; i < n; i++) {
      const p = lo + i * step;
      if (isLong ? p > markPx : p < markPx) bulkLevels++;
    }
  }
  const bulkNotional = bulkLevels * perLevelNotional;
  let worstLoss = 0, liq = 0;
  if (type === "grid" && investNum > 0 && markPx > 0 && minPx && maxPx) {
    const lo = parseFloat(minPx), hi = parseFloat(maxPx);
    const avgAccum = isLong ? (lo + markPx) / 2 : (hi + markPx) / 2;
    const maxPos = totalNotional / avgAccum;
    worstLoss = isLong
      ? maxPos * Math.max(0, avgAccum - lo)
      : maxPos * Math.max(0, hi - avgAccum);
    const maint = 0.005;
    liq = isLong
      ? avgAccum * (1 - (1 / levNum - maint))
      : avgAccum * (1 + (1 / levNum - maint));
  }

  // DCA live calc
  let dcaTotalMargin = 0, dcaTotalNotional = 0, dcaAvg = 0, dcaLiq = 0;
  if (type === "dca" && markPx > 0) {
    const im = parseFloat(dcaInit) || 0;
    const sm = parseFloat(dcaSafety) || 0;
    const mm = parseFloat(dcaMargMult) || 1.5;
    const ms = Math.max(0, parseInt(dcaMaxSafety) || 0);
    const ps = parseFloat(dcaStep) || 0;
    dcaTotalMargin = im;
    let totalQty = im * levNum / markPx;
    let avgNum = markPx * totalQty;
    let cumOff = 0;
    for (let i = 1; i <= ms; i++) {
      cumOff += ps;
      const entry = isLong ? markPx * (1 - cumOff / 100) : markPx * (1 + cumOff / 100);
      const margin_i = sm * Math.pow(mm, i - 1);
      const qty_i = entry > 0 ? (margin_i * levNum / entry) : 0;
      dcaTotalMargin += margin_i;
      totalQty += qty_i;
      avgNum += entry * qty_i;
    }
    dcaAvg = totalQty > 0 ? avgNum / totalQty : markPx;
    dcaTotalNotional = dcaTotalMargin * levNum;
    const maint = 0.005;
    dcaLiq = isLong
      ? dcaAvg * (1 - (1 / levNum - maint))
      : dcaAvg * (1 + (1 / levNum - maint));
  }

  const submit = async () => {
    if (busy) return;
    if (!symbol || !investNum) { alert("Заполни символ и инвестицию"); return; }
    setBusy(true);
    try {
      const config = { market: "futures" };
      if (type === "grid") {
        const lo = parseFloat(minPx), hi = parseFloat(maxPx);
        if (!(lo > 0 && hi > lo && n >= 2)) throw new Error("Неверный диапазон");
        config.min_price = lo; config.max_price = hi; config.grid_num = n;
      } else if (type === "dca") {
        config.initial_margin = parseFloat(dcaInit);
        config.safety_margin = parseFloat(dcaSafety);
        config.price_step_pct = parseFloat(dcaStep);
        config.margin_multiplier = parseFloat(dcaMargMult) || 1.5;
        config.max_safety_orders = parseInt(dcaMaxSafety);
        config.tp_per_cycle_pct = parseFloat(dcaTp);
        config.direction = direction;
      }
      await window.MobileAPI.createLocalBot({
        exchange: activeEx,
        symbol: symbol.toUpperCase(),
        bot_type: type,
        direction,
        investment_usdt: investNum,
        leverage: levNum,
        config,
      });
      onCreated();
    } catch (e) {
      alert("Ошибка: " + (e.message || e).slice(0, 200));
      setBusy(false);
    }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 760, maxWidth: "92vw" }}>
        <div className="modal-head">
          <div style={{ fontWeight: 600, fontSize: 14 }}>Создать локального бота</div>
          <button className="icon-btn" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>

          {/* Left — form */}
          <div>
            <div className="field">
              <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Тип бота</label>
              <div className="segmented" style={{ marginTop: 6 }}>
                {[["grid","Grid"], ["dca","Smart-DCA"], ["recurring","Basket"]].map(([k, l]) => (
                  <button key={k} className={type === k ? "active" : ""} onClick={() => setType(k)}>{l}</button>
                ))}
              </div>
            </div>

            <div className="field">
              <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Символ</label>
              <input className="input" value={symbol} onChange={e => setSymbol(e.target.value.toUpperCase())}
                     placeholder="TONUSDT" style={{ marginTop: 4 }}/>
              {markPx > 0 && (
                <div className="muted mono" style={{ fontSize: 11, marginTop: 4 }}>
                  Mark: {fmtPx(markPx)} · биржа: {activeEx?.toUpperCase()}
                </div>
              )}
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              <div className="field">
                <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Направление</label>
                <div className="segmented" style={{ marginTop: 6 }}>
                  {["long", "short", "neutral"].map(d => (
                    <button key={d} className={direction === d ? "active" : ""} onClick={() => setDirection(d)}>{d}</button>
                  ))}
                </div>
              </div>
              <div className="field">
                <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Маржа (USDT)</label>
                <input className="input" value={invest} onChange={e => setInvest(e.target.value)} inputMode="decimal" style={{ marginTop: 4 }}/>
              </div>
            </div>

            <div className="field">
              <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Плечо</label>
              <div style={{ display: "flex", gap: 4, marginTop: 4 }}>
                {[1, 3, 5, 10, 20, 50].map(L => (
                  <button key={L} className="btn"
                          style={{ flex: 1, padding: "6px 0",
                                   background: parseInt(lev) === L ? "var(--accent)" : "",
                                   color: parseInt(lev) === L ? "white" : "",
                                   borderColor: parseInt(lev) === L ? "var(--accent)" : "" }}
                          onClick={() => setLev(String(L))}>{L}x</button>
                ))}
              </div>
            </div>

            {type === "grid" && (
              <>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <div className="field">
                    <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Мин цена</label>
                    <input className="input" value={minPx} onChange={e => setMinPx(e.target.value)} inputMode="decimal" style={{ marginTop: 4 }}/>
                  </div>
                  <div className="field">
                    <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Макс цена</label>
                    <input className="input" value={maxPx} onChange={e => setMaxPx(e.target.value)} inputMode="decimal" style={{ marginTop: 4 }}/>
                  </div>
                </div>
                <div className="field">
                  <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Уровни сетки</label>
                  <input className="input" value={gridNum} onChange={e => setGridNum(e.target.value.replace(/\D/g, ""))} inputMode="numeric" style={{ marginTop: 4 }}/>
                </div>
              </>
            )}

            {type === "dca" && (
              <>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <div className="field">
                    <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Маржа начального</label>
                    <input className="input" value={dcaInit} onChange={e => setDcaInit(e.target.value)} inputMode="decimal" style={{ marginTop: 4 }}/>
                  </div>
                  <div className="field">
                    <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Маржа страховочного</label>
                    <input className="input" value={dcaSafety} onChange={e => setDcaSafety(e.target.value)} inputMode="decimal" style={{ marginTop: 4 }}/>
                  </div>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <div className="field">
                    <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Шаг цены, %</label>
                    <input className="input" value={dcaStep} onChange={e => setDcaStep(e.target.value)} inputMode="decimal" style={{ marginTop: 4 }}/>
                  </div>
                  <div className="field">
                    <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Маржа ×</label>
                    <input className="input" value={dcaMargMult} onChange={e => setDcaMargMult(e.target.value)} inputMode="decimal" style={{ marginTop: 4 }}/>
                  </div>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <div className="field">
                    <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Макс. страховочных</label>
                    <input className="input" value={dcaMaxSafety} onChange={e => setDcaMaxSafety(e.target.value.replace(/\D/g, ""))} inputMode="numeric" style={{ marginTop: 4 }}/>
                  </div>
                  <div className="field">
                    <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>TP за цикл, %</label>
                    <input className="input" value={dcaTp} onChange={e => setDcaTp(e.target.value)} inputMode="decimal" style={{ marginTop: 4 }}/>
                  </div>
                </div>
              </>
            )}
          </div>

          {/* Right — Live summary */}
          <div>
            <label className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em" }}>Расчёт (live)</label>
            <div className="card" style={{ padding: 14, marginTop: 6 }}>
              {type === "grid" && (
                <>
                  <SumRow label="Маржа/уровень" val={fmt(perLevelMargin) + " USDT"}/>
                  <SumRow label="Нотионал/уровень"
                          val={fmt(perLevelNotional) + " USDT"}
                          warn={perLevelNotional < 7.5}/>
                  <SumRow label="Всего нотионал" val={fmt(totalNotional) + " USDT"}/>
                  {bulkNotional > 0 && (
                    <SumRow label="Bulk-buy при старте"
                            val={fmt(bulkNotional, 0) + " USDT (" + bulkLevels + " ур.)"}
                            danger/>
                  )}
                  {worstLoss > 0 && (
                    <SumRow label="Макс. убыток (out-of-range)"
                            val={"−" + fmt(worstLoss, 0) + " USDT"}
                            danger/>
                  )}
                  {liq > 0 && (
                    <SumRow label="Цена ликвидации (~)" val={fmtPx(liq)} danger/>
                  )}
                </>
              )}
              {type === "dca" && (
                <>
                  <SumRow label="Всего маржи" val={fmt(dcaTotalMargin) + " USDT"}/>
                  <SumRow label="Нотионал" val={fmt(dcaTotalNotional) + " USDT"}/>
                  <SumRow label="Средняя вход (worst)" val={fmtPx(dcaAvg)}/>
                  {dcaLiq > 0 && (
                    <SumRow label="Цена ликвидации (~)" val={fmtPx(dcaLiq)} danger/>
                  )}
                </>
              )}
              {type === "recurring" && (
                <div className="muted" style={{ fontSize: 12, padding: 6 }}>
                  Basket: периодическая закупка корзины токенов. Live расчёт пока в мобильной версии.
                </div>
              )}
            </div>

            {type === "grid" && (levNum > 5 || worstLoss > investNum) && (
              <div style={{ marginTop: 10, padding: 12,
                background: "var(--short-bg)",
                border: "1px solid var(--short-dim)",
                borderRadius: 8, fontSize: 11.5, lineHeight: 1.5, color: "var(--short)" }}>
                ⚠ {levNum > 5
                  ? "Плечо " + levNum + "x высокое для Grid — на OKX рекомендуют 1-3x."
                  : "Макс. убыток " + fmt(worstLoss, 0) + " > инвестиций " + fmt(investNum, 0) + ". Снизь плечо."}
              </div>
            )}
          </div>
        </div>

        <div className="modal-foot">
          <div></div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn" onClick={onClose}>Отмена</button>
            <button className="btn"
                    style={{ background: "var(--accent)", color: "white", borderColor: "var(--accent)", padding: "8px 18px" }}
                    onClick={submit} disabled={busy || !symbol || !investNum}>
              {busy ? "..." : "Создать бота"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

const SumRow = ({ label, val, warn, danger }) => (
  <div style={{ display: "flex", justifyContent: "space-between", padding: "6px 0",
                borderBottom: "1px solid var(--border)", fontSize: 12 }}>
    <span className="muted">{label}</span>
    <span className={"mono " + (danger ? "neg" : warn ? "" : "")}
          style={{ fontWeight: 600, color: warn ? "var(--warn)" : undefined }}>
      {val}{warn ? " ⚠" : ""}
    </span>
  </div>
);

// Регистрация — старый App импортирует через window.LocalBotsTab
window.LocalBotsTab = LocalBotsTab;

})();
