// ==== Экраны: Обзор · Трейдеры · Карточка трейдера ==========
(function (UI) {
    'use strict';
    const M = UI.M, esc = UI.esc, usd = UI.usd, pct = UI.pct;

    // ------------------------------------------------ Обзор
    let dashState = { series: 'pnlByDay', range: 'all' };
    const RANGES = [['7d', '7д', 7], ['30d', '30д', 30], ['90d', '90д', 90], ['all', 'Всё', Infinity]];

    window.dashSet = (k, v) => { dashState[k] = v; UI.render(); };

    UI.route('dashboard', () => {
        const t = M.totals, s = M.system;
        const series = M[dashState.series];
        const n = RANGES.find(r => r[0] === dashState.range)[2];
        const vals = series.usd.slice(-n), labels = series.labels.slice(-n);
        const rangeSum = vals.reduce((a, b) => a + b, 0);

        const active = M.traders.filter(x => x.trades > 0);
        const top = [...active].sort((a, b) => b.netPnl - a.netPnl).slice(0, 5);
        const worst = [...active].sort((a, b) => a.netPnl - b.netPnl).slice(0, 5);
        const miniTrader = x => `<a class="kpi" href="#/trader/${x.id}" style="text-decoration:none;color:inherit;min-width:150px">
            <div class="k-label" style="text-transform:none;letter-spacing:0;font-size:12.5px;display:flex;gap:6px;align-items:center">${UI.gradeBadge(x.grade)} <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(x.label)}</span></div>
            <div class="k-value ${UI.pnlCls(x.netPnl)}">${usd(x.netPnl, true)}</div>
            <div style="height:28px;margin-top:4px">${UI.spark(x.spark, 130, 28)}</div></a>`;

        const posMini = M.positions.slice().sort((a, b) => Math.abs(b.pnlUsd) - Math.abs(a.pnlUsd)).slice(0, 4).map(p => `
            <a class="row-card" href="#/positions" style="text-decoration:none;color:inherit">
                <span class="heat" style="background:${p.pnlUsd >= 0 ? 'var(--up)' : 'var(--down)'}"></span>
                <div class="rc-main">
                    <div class="rc-title mono">${esc(p.symbol)} ${UI.sideBadge(p.side)} <span class="muted small">×${p.leverage}</span></div>
                    <div class="rc-sub">${esc(M.traderLabel(p.walletId))} · ${usd(p.sizeUsd)}</div>
                </div>
                <div class="rc-right"><div class="rc-num ${UI.pnlCls(p.pnlUsd)}">${usd(p.pnlUsd, true)}</div>
                <div class="rc-num-sub ${UI.pnlCls(p.pnlPct)}">${pct(p.pnlPct)}</div></div></a>`).join('');

        const feed = M.signals.slice(0, 8).map(sg => `
            <div class="row-card" style="cursor:default">
                <div class="rc-main"><div class="rc-title mono" style="font-size:14px">${esc(sg.symbol)} ${UI.sideBadge(sg.side)} ${UI.modeBadge(sg.mode)}</div>
                <div class="rc-sub">${esc(M.traderLabel(sg.walletId))} · размер ${sg.size}</div></div>
                <div class="rc-right rc-num-sub">${UI.relTime(sg.at)}</div></div>`).join('');

        const body = `
        <section class="hero">
            <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:10px">
                <div>
                    <div class="h-label">Капитал портфеля</div>
                    <div class="h-value">${Math.floor(t.balance).toLocaleString('ru-RU')}<small>.${(t.balance % 1).toFixed(2).slice(2)} $</small></div>
                </div>
                <span class="chip ${s.cronOk ? 'up' : 'down'}" style="cursor:default"><span class="pulse"></span> бот ${s.botStatus}</span>
            </div>
            <div class="h-chips">
                <span class="chip ${UI.pnlCls(t.netPnl) === 'up-t' ? 'up' : 'down'}" style="cursor:default">Net ${usd(t.netPnl, true)}</span>
                <span class="chip ${UI.pnlCls(t.unrealized) === 'up-t' ? 'up' : 'down'}" style="cursor:default">uPnL ${usd(t.unrealized, true)}</span>
                <span class="chip info" style="cursor:default">в позициях ${usd(t.posSize)}</span>
            </div>
            <div class="h-chart">${UI.areaChart(M.equity.values, null, 96, { noAxis: true })}</div>
        </section>

        <div class="kpi-strip">
            <div class="kpi"><div class="k-label">Win rate</div><div class="k-value">${t.winrate}%</div><div class="k-sub">${t.wins}W / ${t.losses}L</div></div>
            <div class="kpi"><div class="k-label">Сделки</div><div class="k-value">${UI.num(t.trades)}</div><div class="k-sub">сигналов ${UI.num(t.signals)}</div></div>
            <div class="kpi"><div class="k-label">Комиссии</div><div class="k-value">${usd(t.fees)}</div><div class="k-sub">за всё время</div></div>
            <div class="kpi"><div class="k-label">Копируются</div><div class="k-value">${t.enabled}</div><div class="k-sub">из ${M.traders.length} трейдеров</div></div>
            <div class="kpi"><div class="k-label">Сигналы сегодня</div><div class="k-value">${s.signalsToday}</div><div class="k-sub">тик ${s.cronLastTickSec}с назад</div></div>
        </div>

        <div class="cols2">
        <section class="card">
            <h2 class="card-title">PnL по периодам <span class="spacer"></span>
                <span class="mono small ${UI.pnlCls(rangeSum)}">${usd(rangeSum, true)}</span></h2>
            <div style="display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:10px">
                <div class="seg">${[['pnlByDay', 'Дни'], ['pnlByWeek', 'Недели'], ['pnlByMonth', 'Месяцы']].map(([k, l]) =>
                    `<button class="${dashState.series === k ? 'on' : ''}" onclick="dashSet('series','${k}')">${l}</button>`).join('')}</div>
                <div class="seg">${RANGES.map(([k, l]) =>
                    `<button class="${dashState.range === k ? 'on' : ''}" onclick="dashSet('range','${k}')">${l}</button>`).join('')}</div>
            </div>
            ${UI.barChart(vals, labels, 165)}
        </section>

        <section class="card flat">
            <h2 class="card-title">Топ трейдеров <span class="spacer"></span><a href="#/traders" class="small">все ›</a></h2>
            <div class="kpi-strip">${top.map(miniTrader).join('')}</div>
            <h2 class="card-title" style="margin-top:6px">Аутсайдеры</h2>
            <div class="kpi-strip">${worst.map(miniTrader).join('')}</div>
        </section>

        <section class="card flat">
            <h2 class="card-title">Открытые позиции <span class="spacer"></span><a href="#/positions" class="small">все ${M.positions.length} ›</a></h2>
            ${posMini}
        </section>

        <section class="card flat">
            <h2 class="card-title">Последняя активность <span class="spacer"></span><a href="#/journal" class="small">журнал ›</a></h2>
            ${feed}
        </section>
        </div>`;

        return UI.shell({ title: 'Обзор', sub: 'обновлено ' + M.system.lastRun, body });
    });

    // ------------------------------------------------ Трейдеры
    let trState = { q: '', status: 'all', onlyEnabled: false, minRating: 0, sort: 'default' };
    window.trSet = (k, v) => { trState[k] = v; UI.render(); };
    window.trSearch = v => {
        trState.q = v;
        const list = UI.$('#tr-list'); if (list) list.innerHTML = tradersListHtml();
    };

    const TR_SORTS = [
        ['default', 'По умолчанию'], ['rating', 'Рейтинг ↓'], ['pnl_desc', 'Net PnL ↓'], ['pnl_asc', 'Net PnL ↑'],
        ['balance', 'Баланс ↓'], ['roi', 'ROI ↓'], ['winrate', 'Win rate ↓'], ['trades', 'Сделки ↓'], ['name', 'А–Я'],
    ];
    function filteredTraders() {
        let list = M.traders.filter(t =>
            (trState.status === 'all' || t.status === trState.status) &&
            (!trState.onlyEnabled || t.enabled) &&
            t.rating >= trState.minRating &&
            (!trState.q || (t.label + ' ' + t.address).toLowerCase().includes(trState.q.toLowerCase())));
        const s = trState.sort;
        const by = f => list.sort((a, b) => f(b) - f(a));
        if (s === 'rating') by(t => t.rating);
        else if (s === 'pnl_desc') by(t => t.netPnl);
        else if (s === 'pnl_asc') list.sort((a, b) => a.netPnl - b.netPnl);
        else if (s === 'balance') by(t => t.balance);
        else if (s === 'roi') by(t => t.roi);
        else if (s === 'winrate') by(t => t.winrate);
        else if (s === 'trades') by(t => t.trades);
        else if (s === 'name') list.sort((a, b) => a.label.localeCompare(b.label, 'ru'));
        return list;
    }
    function traderCard(t) {
        return `<a class="row-card" href="#/trader/${t.id}" style="text-decoration:none;color:inherit">
            <div class="rc-spark">${UI.spark(t.spark, 140, 60)}</div>
            <div class="rc-main">
                <div class="rc-title">${esc(t.label)} ${UI.gradeBadge(t.grade)} ${t.enabled ? '' : '<span class="badge b-off">off</span>'}</div>
                <div class="rc-sub">${UI.statusBadge(t.status)} ${UI.stars(t.rating)} <span class="addr">${UI.shortAddr(t.address)}</span> ${UI.hdLink(t.address)}</div>
                <div class="rc-sub">${t.tags.map(UI.tagPill).join(' ')}</div>
            </div>
            <div class="rc-right" style="position:relative;z-index:2">
                <div class="rc-num ${UI.pnlCls(t.netPnl)}">${usd(t.netPnl, true)}</div>
                <div class="rc-num-sub">${pct(t.roi)} · WR ${t.winrate}%</div>
                <div class="rc-num-sub">${t.trades} сделок</div>
            </div></a>`;
    }
    function tradersTable(list) {
        const th = (l, d, a, c) => UI.thSort(l, trState.sort, "trSet.bind(null,'sort')", d, a, c);
        return `<section class="card table-card"><table class="dtable"><thead><tr>
            ${th('Трейдер', 'name')}<th>Статус</th>${th('Рейтинг', 'rating')}<th>Score</th>
            ${th('Баланс', 'balance', null, 'num')}${th('Net PnL', 'pnl_desc', 'pnl_asc', 'num')}
            ${th('ROI', 'roi', null, 'num')}${th('WR', 'winrate', null, 'num')}${th('Сделки', 'trades', null, 'num')}
            <th>PnL 14д</th><th></th></tr></thead><tbody>
            ${list.map(t => `<tr data-href="#/trader/${t.id}">
                <td><div class="cell-main">${esc(t.label)} ${t.enabled ? '' : '<span class="badge b-off">off</span>'}</div>
                    <div class="cell-sub"><span class="addr">${UI.shortAddr(t.address)}</span> ${t.tags.map(UI.tagPill).join(' ')}</div></td>
                <td>${UI.statusBadge(t.status)}</td>
                <td>${UI.stars(t.rating)}</td>
                <td>${UI.gradeBadge(t.grade)} ${t.score != null ? `<span class="mono small muted">${t.score}</span>` : ''}</td>
                <td class="num">${usd(t.balance)}</td>
                <td class="num ${UI.pnlCls(t.netPnl)}"><b>${usd(t.netPnl, true)}</b></td>
                <td class="num ${UI.pnlCls(t.roi)}">${pct(t.roi)}</td>
                <td class="num">${t.winrate}%</td>
                <td class="num">${t.trades}</td>
                <td><div class="spark-cell">${UI.spark(t.spark, 120, 34)}</div></td>
                <td>${UI.hdLink(t.address)}</td></tr>`).join('')}
        </tbody></table></section>`;
    }
    function tradersListHtml() {
        const list = filteredTraders();
        if (!list.length) return `<div class="empty"><div class="e-ico">🛰</div>Никого не нашлось — измените фильтры или запрос</div>`;
        return `<div class="small muted" style="margin:2px 2px 10px">${list.length} из ${M.traders.length} трейдеров</div>`
            + (UI.isDesktop() ? tradersTable(list) : list.map(traderCard).join(''));
    }
    window.trFilterSheet = () => {
        UI.openSheet('Фильтры и сортировка', `
            <div class="field"><label>Статус</label>
                <div class="chip-row" style="flex-wrap:wrap">${['all', 'ACTIVE', 'TEST', 'WATCH', 'ARCHIVE'].map(s =>
                    `<span class="chip ${trState.status === s ? 'on' : ''}" onclick="trSet('status','${s}');trFilterSheet()">${s === 'all' ? 'Все' : s}</span>`).join('')}</div></div>
            <div class="field"><label>Минимальный рейтинг</label>
                <div class="chip-row">${[0, 1, 2, 3, 4, 5].map(r =>
                    `<span class="chip ${trState.minRating === r ? 'on' : ''}" onclick="trSet('minRating',${r});trFilterSheet()">${r === 0 ? 'любой' : r + '★'}</span>`).join('')}</div></div>
            <label class="check"><input type="checkbox" ${trState.onlyEnabled ? 'checked' : ''}
                onchange="trSet('onlyEnabled',this.checked);trFilterSheet()"> Только с включённым копированием</label>
            <div class="field" style="margin-top:12px"><label>Сортировка</label>
                <select onchange="trSet('sort',this.value)">${TR_SORTS.map(([k, l]) =>
                    `<option value="${k}" ${trState.sort === k ? 'selected' : ''}>${l}</option>`).join('')}</select></div>
            <button class="btn btn-primary btn-block" onclick="UI.closeSheet()">Показать</button>`);
    };
    window.trAddSheet = () => {
        UI.openSheet('Добавить трейдера', `
            <div class="field"><label>Адрес (0x…)</label><input type="text" placeholder="0x0000…0000"></div>
            <div class="field"><label>Название</label><input type="text" placeholder="Например, Trader Alpha"></div>
            <div class="field"><label>Заметки</label><textarea placeholder="Откуда взяли, чем интересен"></textarea></div>
            <button class="btn btn-primary btn-block" onclick="UI.stub();UI.closeSheet()">Добавить в наблюдение</button>
            <div class="hint" style="text-align:center;margin-top:8px">Новый трейдер получает статус WATCH — копирование выключено</div>`);
    };

    UI.route('traders', () => {
        const body = `
            <div class="search-bar">${UI.ICONS.search}<input type="text" placeholder="Имя или адрес…" value="${esc(trState.q)}" oninput="trSearch(this.value)"></div>
            <div class="chip-row">
                <span class="chip ${trState.status !== 'all' || trState.minRating > 0 || trState.onlyEnabled ? 'on' : ''}" onclick="trFilterSheet()">${'⚙'} Фильтры</span>
                <span class="chip" onclick="trFilterSheet()">Сортировка: ${TR_SORTS.find(s => s[0] === trState.sort)[1]}</span>
            </div>
            <div id="tr-list">${tradersListHtml()}</div>`;
        return UI.shell({
            title: 'Трейдеры', body,
            actions: `<button class="icon-btn" onclick="trFilterSheet()" aria-label="Фильтры">${UI.ICONS.filter}</button>`,
            fab: `<button class="fab" onclick="trAddSheet()" aria-label="Добавить трейдера">${UI.ICONS.plus}</button>`,
        });
    });

    // ------------------------------------------------ Карточка трейдера
    UI.route('trader', id => {
        const t = M.trader(id);
        if (!t) return UI.shell({ title: 'Трейдер не найден', back: '#/traders', body: '<div class="empty">Нет такого трейдера</div>' });
        const pos = M.positions.filter(p => p.walletId === id);
        const watch = M.watching.filter(w => w.walletId === id);
        const trades = M.trades.filter(x => x.walletId === id);
        const sigs = M.signals.filter(x => x.walletId === id);

        const kpi = (l, v, cls = '', sub = '') => `<div class="kpi"><div class="k-label">${l}</div><div class="k-value ${cls}">${v}</div>${sub ? `<div class="k-sub">${sub}</div>` : ''}</div>`;

        const scoreCard = t.scoreBreakdown ? `
            <section class="card"><h2 class="card-title">Автоскоринг <span class="spacer"></span>
                <span class="mono">${t.score}/100</span> ${UI.gradeBadge(t.grade)}</h2>
                ${Object.entries({ winrate: 'Win rate', roi: 'ROI', drawdown: 'Просадка', activity: 'Активность' }).map(([k, l]) => {
                    const b = t.scoreBreakdown[k];
                    return `<div style="margin-bottom:11px">
                        <div style="display:flex;justify-content:space-between;font-size:12.5px;margin-bottom:5px">
                        <span class="muted">${l} · <span class="mono">${esc(b.value)}</span></span><span class="mono">${b.score}/${b.max}</span></div>
                        <div class="score-bar"><i style="width:${b.score / b.max * 100}%"></i></div></div>`;
                }).join('')}
            </section>` : `
            <section class="card"><h2 class="card-title">Автоскоринг</h2>
                <div class="muted small">${esc(t.scoreReason || 'Недостаточно данных для оценки')}</div></section>`;

        const overview = `
            <div class="kpi-grid">
                ${kpi('Баланс', usd(t.balance))}
                ${kpi('Net PnL', usd(t.netPnl, true), UI.pnlCls(t.netPnl), 'gross ' + usd(t.grossPnl, true))}
                ${kpi('ROI', pct(t.roi), UI.pnlCls(t.roi), 'ср. на сделку ' + pct(t.avgRoi))}
                ${kpi('Win rate', t.winrate + '%')}
                ${kpi('Просадка', pct(t.maxDd), 'down-t', 'MtM ' + pct(t.mtmDd))}
                ${kpi('Сделки', t.trades, '', 'сигналов ' + t.signals)}
                ${kpi('Комиссии', usd(t.fees))}
                ${kpi('Слиппедж', (t.slippage * 100).toFixed(2) + '%')}
                ${kpi('Молчит', t.daysSilent + ' дн', t.daysSilent > 14 ? 'down-t' : '')}
            </div>
            <div class="cols2" style="margin-top:12px">
            <section class="card span2"><h2 class="card-title">Дневной PnL за 14 дней</h2>
                ${UI.barChart(t.spark, null, 130)}</section>
            ${scoreCard}
            <section class="card"><h2 class="card-title">Паспорт</h2>
                <div class="stat-pairs" style="grid-template-columns:1fr">
                    <div class="sp"><span class="muted">Адрес</span><b class="addr">${UI.shortAddr(t.address)} ${UI.hdLink(t.address)}</b></div>
                    <div class="sp"><span class="muted">Источник</span><b>${esc(t.source || '—')}</b></div>
                    <div class="sp"><span class="muted">Теги</span><b>${t.tags.length ? t.tags.map(UI.tagPill).join(' ') : '—'}</b></div>
                    ${t.archiveReason ? `<div class="sp"><span class="muted">Причина архива</span><b>${esc(t.archiveReason)}</b></div>` : ''}
                </div>
                ${t.notes ? `<p class="small" style="margin:10px 0 0;color:var(--mut)">${esc(t.notes)}</p>` : ''}
            </section>
            </div>`;

        const posPane = (pos.length || watch.length) ? `
            ${pos.length ? (UI.isDesktop() ? window.__posTable(pos, true) : pos.map(p => window.__posCard(p, true)).join('')) : ''}
            ${watch.length ? `<h2 class="card-title" style="margin-top:14px">Watching — ждём просадку</h2>` + watch.map(w => window.__watchCard(w, true)).join('') : ''}`
            : `<div class="empty"><div class="e-ico">💤</div>Открытых позиций нет</div>`;

        const tradesPane = !trades.length ? `<div class="empty"><div class="e-ico">📭</div>Закрытых сделок ещё нет</div>`
            : UI.isDesktop() ? window.__tradesTable(trades, true) : trades.map(x => window.__tradeCard(x, true)).join('');
        const sigsPane = !sigs.length ? `<div class="empty"><div class="e-ico">📡</div>Сигналов не было</div>`
            : UI.isDesktop() ? window.__signalsTable(sigs, true) : sigs.map(x => window.__signalCard(x, true)).join('');

        const ov = t.overrides || {};
        const settingsPane = `
            <section class="card">
                <div class="switch-row"><div><div class="sw-label">Копирование</div>
                    <div class="sw-sub">Бот повторяет сделки этого трейдера</div></div>
                    <label class="switch"><input type="checkbox" ${t.enabled ? 'checked' : ''} onchange="UI.stub();this.checked=!this.checked"><span class="tr"></span></label></div>
            </section>
            <section class="card"><h2 class="card-title">Профиль</h2>
                <div class="field"><label>Название</label><input type="text" value="${esc(t.label)}"></div>
                <div class="field"><label>Адрес</label><input type="text" value="${esc(t.address)}" disabled style="opacity:.55"></div>
                <div class="field-grid">
                    <div class="field"><label>Статус</label><select>${['WATCH', 'TEST', 'ACTIVE', 'ARCHIVE'].map(s => `<option ${t.status === s ? 'selected' : ''}>${s}</option>`).join('')}</select></div>
                    <div class="field"><label>Рейтинг</label><select>${[0, 1, 2, 3, 4, 5].map(r => `<option ${t.rating === r ? 'selected' : ''}>${r}</option>`).join('')}</select></div>
                </div>
                <div class="field"><label>Источник</label><input type="text" value="${esc(t.source || '')}"></div>
                <div class="field"><label>Причина архивации</label><input type="text" value="${esc(t.archiveReason || '')}" placeholder="Заполняется при статусе ARCHIVE"></div>
                <div class="field"><label>Теги</label>
                    <div class="chip-row" style="flex-wrap:wrap">${M.availableTags.map(tag =>
                        `<span class="chip ${t.tags.includes(tag) ? 'on' : ''}" onclick="this.classList.toggle('on')">${esc(tag)}</span>`).join('')}</div></div>
                <div class="field"><label>Заметки</label><textarea>${esc(t.notes || '')}</textarea></div>
                <button class="btn btn-primary btn-block" onclick="UI.stub()">Сохранить профиль</button>
            </section>
            <section class="card"><h2 class="card-title">Торговые overrides</h2>
                <div class="hint" style="margin:-6px 0 12px">Пустое поле = глобальная настройка</div>
                <div class="field-grid">
                    <div class="field"><label>scale_factor</label><input type="number" step="0.01" value="${ov.scale_factor ?? ''}" placeholder="${M.settings.scale_factor}"></div>
                    <div class="field"><label>cooldown, сек</label><input type="number" value="${ov.cooldown_seconds ?? ''}" placeholder="${M.settings.cooldown_seconds}"></div>
                    <div class="field"><label>Опрос, мин</label><input type="number" value="${ov.poll_interval_minutes ?? ''}" placeholder="${M.settings.poll_interval_minutes}"></div>
                    <div class="field"><label>default_leverage</label><input type="number" value="${ov.default_leverage ?? ''}" placeholder="${M.settings.default_leverage}"></div>
                    <div class="field"><label>min_notional_usd</label><input type="number" value="${ov.min_notional_usd ?? ''}" placeholder="${M.settings.position_min_usd}"></div>
                    <div class="field"><label>virtual_balance</label><input type="number" value="${ov.virtual_balance ?? ''}" placeholder="${M.settings.virtual_balance}"></div>
                </div>
                <div class="field"><label>allowed_symbols</label><input type="text" value="${esc((ov.allowed_symbols || []).join(', '))}" placeholder="${esc(M.settings.allowed_symbols)}"></div>
                <div class="field"><label>sizing_mode</label><select>
                    <option value="">— глобальный (${M.settings.sizing_mode}) —</option>
                    <option ${ov.sizing_mode === 'percent_balance' ? 'selected' : ''} value="percent_balance">percent_balance</option>
                    <option ${ov.sizing_mode === 'fixed' ? 'selected' : ''} value="fixed">fixed</option></select></div>
                <div class="switch-row"><div class="sw-label">Уведомления в Telegram</div>
                    <label class="switch"><input type="checkbox" ${ov.telegram_notify ? 'checked' : ''}><span class="tr"></span></label></div>
                <div class="switch-row"><div><div class="sw-label">Отложенный вход по просадке</div>
                    <div class="sw-sub">Вход после отката от цены трейдера</div></div>
                    <label class="switch"><input type="checkbox" ${ov.copy_after_drawdown_enabled ? 'checked' : ''}><span class="tr"></span></label></div>
                <div class="field-grid">
                    <div class="field"><label>Порог просадки, %</label><input type="number" step="0.5" value="${ov.copy_after_drawdown_pct ?? ''}" placeholder="${M.settings.copy_after_drawdown_pct}"></div>
                    <div class="field"><label>TTL ожидания, ч (0=∞)</label><input type="number" value="${ov.watch_ttl_hours ?? ''}" placeholder="0"></div>
                </div>
                <button class="btn btn-primary btn-block" onclick="UI.stub()">Сохранить overrides</button>
            </section>
            <section class="card"><h2 class="card-title">Исполнение и прямая торговля</h2>
                <div class="field-grid">
                    <div class="field"><label>execution_mode</label><select>
                        <option value="">— глобальный —</option>
                        <option ${ov.execution_mode === 'webhook' ? 'selected' : ''}>webhook</option>
                        <option ${ov.execution_mode === 'direct' ? 'selected' : ''}>direct</option></select></div>
                    <div class="field"><label>hl_margin_mode</label><select>
                        <option value="">— глобальный —</option>
                        <option ${ov.hl_margin_mode === 'cross' ? 'selected' : ''}>cross</option>
                        <option ${ov.hl_margin_mode === 'isolated' ? 'selected' : ''}>isolated</option></select></div>
                </div>
                <div class="field"><label>hl_subaccount</label><input type="text" value="${esc(ov.hl_subaccount || '')}" placeholder="0x…"></div>
                <hr class="divider">
                <div class="switch-row"><div class="sw-label">Stop Loss</div><label class="switch"><input type="checkbox" ${ov.sl_enabled ? 'checked' : ''}><span class="tr"></span></label></div>
                <div class="field-grid">
                    <div class="field"><label>SL тип</label><select><option>percent</option><option>price</option></select></div>
                    <div class="field"><label>SL значение</label><input type="number" step="0.1" placeholder="напр. 5"></div>
                </div>
                <div class="switch-row"><div class="sw-label">Take Profit</div><label class="switch"><input type="checkbox" ${ov.tp_enabled ? 'checked' : ''}><span class="tr"></span></label></div>
                <div class="field-grid">
                    <div class="field"><label>TP тип</label><select><option>percent</option><option>price</option></select></div>
                    <div class="field"><label>TP значение</label><input type="number" step="0.1" placeholder="напр. 12"></div>
                </div>
                <div class="switch-row"><div><div class="sw-label">Сетка (grid)</div><div class="sw-sub">Разбить вход на серию лимиток</div></div>
                    <label class="switch"><input type="checkbox" ${ov.grid_enabled ? 'checked' : ''}><span class="tr"></span></label></div>
                <div class="field-grid">
                    <div class="field"><label>Ордеров / шаг %</label><input type="text" placeholder="3 / 0.8"></div>
                    <div class="field"><label>Распределение объёма</label><select><option>равномерно</option><option>пирамида вверх</option><option>пирамида вниз</option></select></div>
                </div>
                <button class="btn btn-primary btn-block" onclick="UI.stub()">Сохранить</button>
            </section>
            <section class="card danger-card"><h2 class="card-title">Опасная зона</h2>
                <div class="btn-row">
                    <button class="btn btn-danger" onclick="UI.stub()">Сбросить state</button>
                    <button class="btn btn-danger" onclick="UI.stub()">Удалить трейдера</button>
                </div>
                <div class="hint" style="margin-top:10px">Сброс закрывает виртуальные позиции и обнуляет статистику. Удаление необратимо.</div>
            </section>`;

        const logPane = `
            <section class="card"><h2 class="card-title">Новая запись</h2>
                <div class="field"><textarea placeholder="Что произошло, что поменяли и почему"></textarea></div>
                <button class="btn btn-primary btn-block" onclick="UI.stub()">Добавить</button></section>
            ${t.log.length ? t.log.map(l => `<div class="row-card" style="cursor:default">
                <div class="rc-main"><div style="font-size:14px">${esc(l.note)}</div>
                <div class="rc-sub">${l.at}</div></div></div>`).join('')
                : '<div class="empty"><div class="e-ico">📓</div>Журнал пуст — записывайте решения по трейдеру</div>'}`;

        const body = `
            <div style="display:flex;align-items:center;gap:9px;flex-wrap:wrap;margin-bottom:4px">
                ${UI.statusBadge(t.status)} ${UI.gradeBadge(t.grade)} ${UI.stars(t.rating)}
                <span class="addr">${UI.shortAddr(t.address)}</span> ${UI.hdLink(t.address)}
                <span class="spacer" style="flex:1"></span>
                <label class="switch" title="Копирование"><input type="checkbox" ${t.enabled ? 'checked' : ''} onchange="UI.stub();this.checked=!this.checked"><span class="tr"></span></label>
            </div>
            <div class="tabs">
                <button data-tab="ov" class="on">Обзор</button>
                <button data-tab="pos">Позиции ${pos.length ? `(${pos.length})` : ''}</button>
                <button data-tab="tr">Сделки</button>
                <button data-tab="sig">Сигналы</button>
                <button data-tab="set">Настройки</button>
                <button data-tab="log">Журнал</button>
            </div>
            <div class="tab-pane on" data-pane="ov">${overview}</div>
            <div class="tab-pane" data-pane="pos">${posPane}</div>
            <div class="tab-pane" data-pane="tr">${tradesPane}</div>
            <div class="tab-pane" data-pane="sig">${sigsPane}</div>
            <div class="tab-pane" data-pane="set">${settingsPane}</div>
            <div class="tab-pane" data-pane="log">${logPane}</div>`;

        return UI.shell({ title: t.label, back: '#/traders', body });
    });
})(window.UI);
