// ==== Экраны: Позиции · Журнал · Аналитика ===================
(function (UI) {
    'use strict';
    const M = UI.M, esc = UI.esc, usd = UI.usd, pct = UI.pct;

    // ---- переиспользуемые карточки (нужны и в карточке трейдера) ----
    window.__posCard = function (p, hideTrader) {
        const heat = Math.min(100, Math.abs(p.pnlPct) * 2);
        return `<div class="row-card" style="cursor:default">
            <span class="heat" style="background:${p.pnlUsd >= 0 ? 'var(--up)' : 'var(--down)'}"></span>
            <div class="heat-bg" style="background:linear-gradient(90deg,${p.pnlUsd >= 0 ? 'var(--up)' : 'var(--down)'} ,transparent ${heat}%)"></div>
            <div class="rc-main" style="position:relative">
                <div class="rc-title mono">${esc(p.symbol)} ${UI.tvLink(p.symbol)} ${UI.sideBadge(p.side)} <span class="muted small">×${p.leverage}</span></div>
                ${hideTrader ? '' : `<div class="rc-sub"><a href="#/trader/${p.walletId}" onclick="event.stopPropagation()">${esc(M.traderLabel(p.walletId))}</a></div>`}
                <div class="rc-sub mono">вход ${UI.price(p.entry)} <span class="mut-t">(трейдер ${UI.price(p.traderEntry)})</span> → ${UI.price(p.current)}</div>
                <div class="rc-sub">${usd(p.sizeUsd)} · открыта ${UI.age(p.ageMin)} назад</div>
            </div>
            <div class="rc-right" style="position:relative">
                <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></div>`;
    };
    window.__watchCard = function (w, hideTrader) {
        return `<div class="row-card" style="cursor:default;border-style:dashed">
            <span class="heat" style="background:var(--brand)"></span>
            <div class="rc-main">
                <div class="rc-title mono">${esc(w.symbol)} ${UI.tvLink(w.symbol)} ${UI.sideBadge(w.side)} <span class="muted small">×${w.leverage}</span></div>
                ${hideTrader ? '' : `<div class="rc-sub"><a href="#/trader/${w.walletId}" onclick="event.stopPropagation()">${esc(M.traderLabel(w.walletId))}</a></div>`}
                <div class="rc-sub mono">цена трейдера ${UI.price(w.traderEntry)} · ждём просадку ${w.targetPct}%</div>
                <div class="rc-sub">наблюдаем ${w.ageH} ч ${w.ageM} м</div>
            </div>
            <button class="btn btn-sm" onclick="UI.stub()">Снять</button></div>`;
    };
    window.__tradeCard = function (x, hideTrader) {
        return `<div class="row-card" style="cursor:default">
            <span class="heat" style="background:${x.net >= 0 ? 'var(--up)' : 'var(--down)'}"></span>
            <div class="rc-main">
                <div class="rc-title mono">${esc(x.symbol)} ${UI.tvLink(x.symbol)} ${UI.sideBadge(x.side)} ${UI.reasonBadge(x.reason)}</div>
                ${hideTrader ? '' : `<div class="rc-sub"><a href="#/trader/${x.walletId}" onclick="event.stopPropagation()">${esc(M.traderLabel(x.walletId))}</a></div>`}
                <div class="rc-sub mono">${UI.price(x.entry)} → ${UI.price(x.exit)} · ${usd(x.sizeUsd)}</div>
                <div class="rc-sub mono">слиппедж ${(x.slippage * 100).toFixed(1)}% · fees ${usd(x.fees)} · gross <span class="${UI.pnlCls(x.gross)}">${usd(x.gross, true)}</span></div>
            </div>
            <div class="rc-right">
                <div class="rc-num ${UI.pnlCls(x.net)}">${usd(x.net, true)}</div>
                <div class="rc-num-sub">${x.closedAt.slice(5, 16)}</div>
            </div></div>`;
    };
    window.__signalCard = function (s, hideTrader) {
        return `<div class="row-card" style="cursor:default">
            <div class="rc-main">
                <div class="rc-title mono">${esc(s.symbol)} ${UI.sideBadge(s.side)} ${UI.modeBadge(s.mode)}</div>
                ${hideTrader ? '' : `<div class="rc-sub"><a href="#/trader/${s.walletId}" onclick="event.stopPropagation()">${esc(M.traderLabel(s.walletId))}</a></div>`}
                <div class="rc-sub mono">размер ${s.size}</div>
            </div>
            <div class="rc-right"><div class="rc-num-sub">${UI.relTime(s.at)}</div>
            <div class="rc-num-sub">${s.at.slice(5, 16)}</div></div></div>`;
    };

    // ---- табличные варианты (десктоп) -------------------------
    window.__posTable = function (list, hideTrader, sortable) {
        const th = (l, d, a, c) => sortable ? UI.thSort(l, posSort, 'posSetSort', d, a, c) : `<th class="${c || ''}">${l}</th>`;
        return `<section class="card table-card"><table class="dtable"><thead><tr>
            ${th('Символ', 'symbol')}<th>Сторона</th>${hideTrader ? '' : '<th>Трейдер</th>'}
            ${th('Размер', 'size', null, 'num')}<th class="num">Плечо</th>
            <th class="num">Вход</th><th class="num">Вход трейдера</th><th class="num">Текущая</th>
            ${th('uPnL', 'pnl_desc', 'pnl_asc', 'num')}<th class="num">uPnL %</th>
            ${th('Открыта', 'fresh', 'old')}</tr></thead><tbody>
            ${list.map(p => `<tr>
                <td><span class="cell-main mono">${esc(p.symbol)}</span> ${UI.tvLink(p.symbol)}</td>
                <td>${UI.sideBadge(p.side)}</td>
                ${hideTrader ? '' : `<td><a href="#/trader/${p.walletId}">${esc(M.traderLabel(p.walletId))}</a></td>`}
                <td class="num">${usd(p.sizeUsd)}</td><td class="num">×${p.leverage}</td>
                <td class="num">${UI.price(p.entry)}</td><td class="num mut-t">${UI.price(p.traderEntry)}</td><td class="num">${UI.price(p.current)}</td>
                <td class="num ${UI.pnlCls(p.pnlUsd)}"><b>${usd(p.pnlUsd, true)}</b></td>
                <td class="num ${UI.pnlCls(p.pnlPct)}">${pct(p.pnlPct)}</td>
                <td class="num">${UI.age(p.ageMin)} назад</td></tr>`).join('')}
        </tbody></table></section>`;
    };
    window.__tradesTable = function (list, hideTrader, sortable) {
        const th = (l, d, a, c) => sortable ? UI.thSort(l, jState.tSort, "jSet.bind(null,'tSort')", d, a, c) : `<th class="${c || ''}">${l}</th>`;
        return `<section class="card table-card"><table class="dtable"><thead><tr>
            ${th('Дата', 'fresh', 'old')}${hideTrader ? '' : '<th>Трейдер</th>'}
            <th>Символ</th><th>Сторона</th><th class="num">Вход → Выход</th>
            ${th('Размер', 'size', null, 'num')}<th class="num">Слип.</th><th class="num">Fees</th>
            ${th('Gross', 'gross', null, 'num')}${th('Net', 'net_desc', 'net_asc', 'num')}<th>Причина</th></tr></thead><tbody>
            ${list.map(x => `<tr>
                <td class="num">${x.closedAt.slice(2, 16)}</td>
                ${hideTrader ? '' : `<td><a href="#/trader/${x.walletId}">${esc(M.traderLabel(x.walletId))}</a></td>`}
                <td><span class="cell-main mono">${esc(x.symbol)}</span> ${UI.tvLink(x.symbol)}</td>
                <td>${UI.sideBadge(x.side)}</td>
                <td class="num">${UI.price(x.entry)} → ${UI.price(x.exit)}</td>
                <td class="num">${usd(x.sizeUsd)}</td>
                <td class="num">${(x.slippage * 100).toFixed(1)}%</td>
                <td class="num">${usd(x.fees)}</td>
                <td class="num ${UI.pnlCls(x.gross)}">${usd(x.gross, true)}</td>
                <td class="num ${UI.pnlCls(x.net)}"><b>${usd(x.net, true)}</b></td>
                <td>${UI.reasonBadge(x.reason) || '<span class="muted small">signal</span>'}</td></tr>`).join('')}
        </tbody></table></section>`;
    };
    window.__signalsTable = function (list, hideTrader, sortable) {
        const th = (l, d, a, c) => sortable ? UI.thSort(l, jState.sSort, "jSet.bind(null,'sSort')", d, a, c) : `<th class="${c || ''}">${l}</th>`;
        return `<section class="card table-card"><table class="dtable"><thead><tr>
            ${th('Время', 'fresh', 'old')}${hideTrader ? '' : '<th>Трейдер</th>'}
            <th>Символ</th><th>Сторона</th>${th('Размер', 'size', null, 'num')}<th>Режим</th></tr></thead><tbody>
            ${list.map(s => `<tr>
                <td class="num">${s.at.slice(2, 16)} <span class="muted small">· ${UI.relTime(s.at)}</span></td>
                ${hideTrader ? '' : `<td><a href="#/trader/${s.walletId}">${esc(M.traderLabel(s.walletId))}</a></td>`}
                <td><span class="cell-main mono">${esc(s.symbol)}</span></td>
                <td>${UI.sideBadge(s.side)}</td>
                <td class="num">${s.size}</td>
                <td>${UI.modeBadge(s.mode)}</td></tr>`).join('')}
        </tbody></table></section>`;
    };

    // ------------------------------------------------ Позиции
    let posSort = 'pnl_desc';
    window.posSetSort = v => { posSort = v; UI.render(); };
    const POS_SORTS = [['pnl_desc', 'uPnL ↓'], ['pnl_asc', 'uPnL ↑'], ['size', 'Размер ↓'], ['fresh', 'Открыта (свежие)'], ['old', 'Открыта (старые)'], ['symbol', 'Символ A–Я']];

    UI.route('positions', () => {
        const list = M.positions.slice().sort((a, b) => {
            if (posSort === 'pnl_desc') return b.pnlUsd - a.pnlUsd;
            if (posSort === 'pnl_asc') return a.pnlUsd - b.pnlUsd;
            if (posSort === 'size') return b.sizeUsd - a.sizeUsd;
            if (posSort === 'fresh') return a.ageMin - b.ageMin;
            if (posSort === 'old') return b.ageMin - a.ageMin;
            return a.symbol.localeCompare(b.symbol);
        });
        const upnl = list.reduce((s, p) => s + p.pnlUsd, 0);
        const size = list.reduce((s, p) => s + p.sizeUsd, 0);

        const body = `
            <div class="tabs">
                <button data-tab="open" class="on">Открытые (${M.positions.length})</button>
                <button data-tab="watch">Watching (${M.watching.length})</button>
            </div>
            <div class="tab-pane on" data-pane="open">
                <div class="kpi-grid" style="margin-bottom:12px">
                    <div class="kpi"><div class="k-label">Суммарный uPnL</div><div class="k-value ${UI.pnlCls(upnl)}">${usd(upnl, true)}</div></div>
                    <div class="kpi"><div class="k-label">В позициях</div><div class="k-value">${usd(size)}</div></div>
                </div>
                ${UI.isDesktop() ? '' : `<div class="chip-row">${POS_SORTS.map(([k, l]) =>
                    `<span class="chip ${posSort === k ? 'on' : ''}" onclick="posSetSort('${k}')">${l}</span>`).join('')}</div>`}
                ${!list.length ? '<div class="empty"><div class="e-ico">💤</div>Открытых позиций нет</div>'
                    : UI.isDesktop() ? window.__posTable(list, false, true) : list.map(p => window.__posCard(p)).join('')}
            </div>
            <div class="tab-pane" data-pane="watch">
                <div class="hint" style="margin-bottom:12px">Отложенный вход: бот ждёт просадку цены от входа трейдера и заходит дешевле.</div>
                ${M.watching.length ? M.watching.map(w => window.__watchCard(w)).join('') : '<div class="empty"><div class="e-ico">👀</div>Ничего не наблюдаем</div>'}
            </div>`;
        return UI.shell({ title: 'Позиции', body });
    });

    // ------------------------------------------------ Журнал
    let jState = { range: 'all', tSort: 'fresh', sSort: 'fresh' };
    window.jSet = (k, v) => { jState[k] = v; UI.render(); };
    window.jExportCSV = () => {
        const rows = [['Дата', 'Трейдер', 'Символ', 'Сторона', 'Вход', 'Выход', 'Размер USD', 'Слиппедж', 'Fees', 'Gross', 'Net', 'Причина']];
        jTrades().forEach(x => rows.push([x.closedAt, M.traderLabel(x.walletId), x.symbol, x.side, x.entry, x.exit, x.sizeUsd, x.slippage, x.fees, x.gross, x.net, x.reason]));
        UI.downloadCSV('trades.csv', rows);
    };
    function inRange(dateStr) {
        if (jState.range === 'all') return true;
        const days = { '7d': 7, '30d': 30, '90d': 90 }[jState.range];
        return (Date.now() - new Date(dateStr.replace(' ', 'T')).getTime()) / 86400000 <= days;
    }
    function jTrades() {
        const l = M.trades.filter(x => inRange(x.closedAt));
        return l.sort((a, b) => {
            if (jState.tSort === 'fresh') return b.closedAt.localeCompare(a.closedAt);
            if (jState.tSort === 'old') return a.closedAt.localeCompare(b.closedAt);
            if (jState.tSort === 'net_desc') return b.net - a.net;
            if (jState.tSort === 'net_asc') return a.net - b.net;
            if (jState.tSort === 'size') return b.sizeUsd - a.sizeUsd;
            return b.gross - a.gross;
        });
    }
    UI.route('journal', () => {
        const trades = jTrades();
        const sigs = M.signals.filter(x => inRange(x.at)).sort((a, b) =>
            jState.sSort === 'old' ? a.at.localeCompare(b.at) : jState.sSort === 'size' ? b.size - a.size : b.at.localeCompare(a.at));
        const net = trades.reduce((s, x) => s + x.net, 0);

        const body = `
            <div class="chip-row">${[['7d', '7д'], ['30d', '30д'], ['90d', '90д'], ['all', 'Всё']].map(([k, l]) =>
                `<span class="chip ${jState.range === k ? 'on' : ''}" onclick="jSet('range','${k}')">${l}</span>`).join('')}</div>
            <div class="tabs" style="top:62px">
                <button data-tab="tr" class="on">Сделки (${trades.length})</button>
                <button data-tab="sig">Сигналы (${sigs.length})</button>
            </div>
            <div class="tab-pane on" data-pane="tr">
                <div style="display:flex;gap:9px;align-items:center;margin-bottom:11px">
                    <div class="kpi" style="flex:1"><div class="k-label">Net за период</div><div class="k-value ${UI.pnlCls(net)}">${usd(net, true)}</div></div>
                    <button class="btn" onclick="jExportCSV()">${UI.ICONS.download} CSV</button>
                </div>
                ${UI.isDesktop() ? '' : `<div class="chip-row">${[['fresh', 'Дата (свежие)'], ['old', 'Дата (старые)'], ['net_desc', 'Net ↓'], ['net_asc', 'Net ↑'], ['size', 'Размер ↓'], ['gross', 'Gross ↓']].map(([k, l]) =>
                    `<span class="chip ${jState.tSort === k ? 'on' : ''}" onclick="jSet('tSort','${k}')">${l}</span>`).join('')}</div>`}
                ${!trades.length ? '<div class="empty"><div class="e-ico">📭</div>За период сделок нет</div>'
                    : UI.isDesktop() ? window.__tradesTable(trades, false, true) : trades.map(x => window.__tradeCard(x)).join('')}
            </div>
            <div class="tab-pane" data-pane="sig">
                ${UI.isDesktop() ? '' : `<div class="chip-row">${[['fresh', 'Время (свежие)'], ['old', 'Время (старые)'], ['size', 'Размер ↓']].map(([k, l]) =>
                    `<span class="chip ${jState.sSort === k ? 'on' : ''}" onclick="jSet('sSort','${k}')">${l}</span>`).join('')}</div>`}
                ${!sigs.length ? '<div class="empty"><div class="e-ico">📡</div>За период сигналов нет</div>'
                    : UI.isDesktop() ? window.__signalsTable(sigs, false, true) : sigs.map(x => window.__signalCard(x)).join('')}
            </div>`;
        return UI.shell({ title: 'Журнал', body });
    });

    // ------------------------------------------------ Аналитика
    let aRange = 'all';
    window.aSetRange = v => { aRange = v; UI.render(); };
    UI.route('analytics', () => {
        const n = { '7d': 7, '30d': 30, '90d': 90, all: Infinity }[aRange];
        const eq = M.equity.values.slice(-n), eqL = M.equity.labels.slice(-n);
        const dd = M.equity.drawdown.slice(-n);
        const t = M.totals;
        const minDd = Math.min(...dd);

        const symRows = M.bySymbol.map(s => ({
            label: s.symbol, labelHtml: `${esc(s.symbol)}`,
            value: s.net, valueText: usd(s.net, true),
        }));
        const distRows = M.pnlDistribution.map(d => ({ label: d.label, value: d.count, valueText: d.count + '' }));
        const holdRows = M.holdingByWeekday.labels.map((l, i) => ({ label: l, value: M.holdingByWeekday.values[i], valueText: M.holdingByWeekday.values[i] + ' ч' }));

        const body = `
            <div class="chip-row">${[['7d', '7д'], ['30d', '30д'], ['90d', '90д'], ['all', 'Всё']].map(([k, l]) =>
                `<span class="chip ${aRange === k ? 'on' : ''}" onclick="aSetRange('${k}')">${l}</span>`).join('')}</div>
            <div class="kpi-strip">
                <div class="kpi"><div class="k-label">Net PnL</div><div class="k-value ${UI.pnlCls(t.netPnl)}">${usd(t.netPnl, true)}</div></div>
                <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 down-t">${usd(minDd)}</div></div>
                <div class="kpi"><div class="k-label">Комиссии</div><div class="k-value">${usd(t.fees)}</div></div>
            </div>
            <div class="cols2">
            <section class="card span2"><h2 class="card-title">Кривая капитала — накопительный Net PnL, $</h2>
                ${UI.areaChart(eq, eqL, 185, { color: 'var(--brand)', zero: false })}</section>
            <section class="card span2"><h2 class="card-title">Просадка от пика, $</h2>
                ${UI.areaChart(dd, eqL, 130, { color: 'var(--down)' })}</section>
            <section class="card"><h2 class="card-title">Net PnL по инструментам (топ-8), $</h2>
                ${UI.hBars(symRows)}</section>
            <section class="card"><h2 class="card-title">Детализация по инструментам</h2>
                ${M.bySymbol.map(s => `<div class="row-card" style="cursor:default">
                    <div class="rc-main"><div class="rc-title mono">${esc(s.symbol)} ${UI.tvLink(s.symbol)}</div>
                    <div class="rc-sub">${s.trades} сделок · WR ${s.winrate}%</div></div>
                    <div class="rc-right"><div class="rc-num ${UI.pnlCls(s.net)}">${usd(s.net, true)}</div></div></div>`).join('')}</section>
            <section class="card"><h2 class="card-title">Распределение сделок по ROI</h2>
                ${UI.hBars(distRows, { neutral: true })}</section>
            <section class="card"><h2 class="card-title">Среднее время удержания по дням закрытия, ч</h2>
                ${UI.hBars(holdRows, { neutral: true })}</section>
            </div>`;
        return UI.shell({ title: 'Аналитика', body });
    });
})(window.UI);
