// End-of-window Holdings card. Two parts:
//
//   1. Top strip — three KPI tiles (Total Portfolio / Cash on Hold /
//      Equity Value) sitting next to a small donut that visualises
//      the cash vs equity split.
//
//   2. Bottom table — one row per stock still held on the end-date,
//      with avg buy price, current price, absolute profit, profit %.
//
// Theme parity is the brief: this should look indistinguishable from
// the Trades-table card already on the dashboard. Same `.card` shell,
// same header layout, same Th sort + Hint pattern, same `.mono`
// numerics, same up/down colour tokens.

function HoldingsCard({ summary }) {
    const positions = summary.positions || [];
    const totalValue = summary.totalValue || 0;
    const equityValue = summary.equityValue || 0;
    const cashOnHold = (summary.portfolio && summary.portfolio.cashBalance != null
        ? Number(summary.portfolio.cashBalance.amount ?? summary.portfolio.cashBalance)
        : Math.max(0, totalValue - equityValue));

    const [sortBy, setSortBy] = React.useState({ key: 'value', dir: 'desc' });

    // Normalise once. Each row carries the bits the table needs;
    // derived fields (value, profit, profit%) are pre-computed here so
    // the sort comparator stays trivial.
    const rows = React.useMemo(() => positions.map((p, i) => {
        const qty = Number(p.quantity);
        const avg = Number(p.averagePrice);
        const cur = Number(p.currentPrice);
        const value = qty * cur;
        return {
            id: `${p.symbol}-${i}`,
            symbol: p.symbol,
            companyName: p.companyName,
            upstoxUrl: p.upstoxUrl,
            qty,
            avg,
            cur,
            value,
            profit: typeof p.profit === 'number' ? p.profit : (cur - avg) * qty,
            profitPct: typeof p.profitPercentage === 'number'
                ? p.profitPercentage
                : (avg > 0 ? (cur / avg - 1) * 100 : 0),
        };
    }), [positions]);

    const sorted = React.useMemo(() => {
        const copy = rows.slice();
        const dir = sortBy.dir === 'asc' ? 1 : -1;
        copy.sort((a, b) => {
            const k = sortBy.key;
            if (k === 'stock') return a.symbol.localeCompare(b.symbol) * dir;
            if (k === 'profitPct') return (a.profitPct - b.profitPct) * dir;
            // numeric default (value, profit, qty, avg, cur)
            return ((a[k] ?? 0) - (b[k] ?? 0)) * dir;
        });
        return copy;
    }, [rows, sortBy]);

    const toggleSort = (key) => {
        setSortBy((prev) => prev.key === key
            ? { key, dir: prev.dir === 'asc' ? 'desc' : 'asc' }
            : { key, dir: 'desc' });
    };

    const Th = ({ col, label, align = 'left', hint }) => (
        <th style={{ textAlign: align, cursor: 'pointer', userSelect: 'none' }} onClick={() => toggleSort(col)}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                {label}
                {sortBy.key === col && (
                    <span style={{ color: 'var(--text-2)', fontSize: 9 }}>
                        {sortBy.dir === 'asc' ? '▲' : '▼'}
                    </span>
                )}
                {hint && (
                    <span onClick={(e) => e.stopPropagation()}>
                        <UI.Hint width={300}>{hint}</UI.Hint>
                    </span>
                )}
            </span>
        </th>
    );

    return (
        <div className="card" style={{ padding: 0, overflow: 'hidden', marginTop: 22 }}>
            {/* ── Top strip: three KPI tiles + donut ────────────────────── */}
            <div style={{
                padding: '20px 24px',
                display: 'grid',
                gridTemplateColumns: '1fr 1fr 1fr 220px',
                gap: 14,
                alignItems: 'stretch',
                borderBottom: '1px solid var(--border)',
            }}>
                <UI.KPITile label="Total portfolio"
                    value={UI.fmtINR(totalValue, { compact: true })}
                    delta="Cash + equity"
                    hint={<>
                        <strong>Total Portfolio</strong> — what the account is worth on the
                        end-date: <code>cash on hold + equity value</code>. Same number as
                        the headline above the chart.
                    </>} />
                <UI.KPITile label="Cash on hold"
                    value={UI.fmtINR(cashOnHold, { compact: true })}
                    delta="Un-deployed"
                    hint={<>
                        <strong>Cash on Hold</strong> — un-deployed cash sitting in the
                        simulated account on the end-date. Includes proceeds from sells the
                        strategy hasn't yet redeployed.
                    </>} />
                <UI.KPITile label="Equity value"
                    value={UI.fmtINR(equityValue, { compact: true })}
                    delta={`${rows.length} ${rows.length === 1 ? 'stock' : 'stocks'} held`}
                    highlight={equityValue > 0}
                    hint={<>
                        <strong>Equity Value</strong> — mark-to-market value of every open
                        lot on the end-date (sum of <code>qty × close price</code>). The
                        table below itemises which stocks make this up.
                    </>} />

                <SplitDonut equityValue={equityValue} cashOnHold={cashOnHold} />
            </div>

            {/* ── Holdings table ───────────────────────────────────────── */}
            <div style={{ padding: '18px 20px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
                <div>
                    <div style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-0.01em' }}>Holdings on end-date</div>
                    <div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 3 }}>
                        {rows.length} {rows.length === 1 ? 'position' : 'positions'} marked-to-market
                    </div>
                </div>
            </div>

            {rows.length === 0 ? (
                <div className="empty" style={{ borderTop: '1px solid var(--border)', padding: '40px 20px' }}>
                    No open positions on end-date — strategy fully exited.
                </div>
            ) : (
                <div style={{ maxHeight: 460, overflow: 'auto', borderTop: '1px solid var(--border)' }}>
                    <table className="table">
                        <thead>
                            <tr>
                                <Th col="stock" label="Stock" />
                                <Th col="qty" label="Qty" align="right" />
                                <Th col="avg" label="Avg buy" align="right" />
                                <Th col="cur" label="Current" align="right" />
                                <Th col="value" label="Market value" align="right" />
                                <Th col="profit" label="P&amp;L" align="right"
                                    hint={<>
                                        <strong>Unrealised P&amp;L</strong> — open-position profit if you sold
                                        every lot at the end-date close: <code>(current − avg buy) × qty</code>.
                                        Excludes taxes/brokerage.
                                    </>} />
                                <Th col="profitPct" label="P&amp;L %" align="right"
                                    hint={<>
                                        <strong>Profit %</strong> — relative gain on cost basis:{' '}
                                        <code>(current / avg buy − 1) × 100</code>. Treats the position like a
                                        single buy at the average cost — doesn't care when individual lots were
                                        purchased.
                                    </>} />
                            </tr>
                        </thead>
                        <tbody>
                            {sorted.map((r) => (
                                <tr key={r.id}>
                                    <td>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                                            <div style={{
                                                width: 28, height: 28, borderRadius: 6,
                                                background: 'var(--surface-2)',
                                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                                fontSize: 10, fontWeight: 600, color: 'var(--text-2)',
                                                fontFamily: 'var(--font-mono)',
                                                flex: 'none',
                                            }}>
                                                {(r.symbol || '').slice(0, 2)}
                                            </div>
                                            <div style={{ minWidth: 0 }}>
                                                {r.upstoxUrl ? (
                                                    <a href={r.upstoxUrl} target="_blank" rel="noopener noreferrer"
                                                        style={{
                                                            fontSize: 13, fontWeight: 600, color: 'var(--text)',
                                                            letterSpacing: '-0.005em', textDecoration: 'none',
                                                            borderBottom: '1px dashed var(--text-4)',
                                                        }}
                                                        onMouseEnter={(e) => e.currentTarget.style.color = 'var(--accent-text)'}
                                                        onMouseLeave={(e) => e.currentTarget.style.color = 'var(--text)'}>
                                                        {r.companyName || r.symbol}
                                                    </a>
                                                ) : (
                                                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', letterSpacing: '-0.005em' }}>
                                                        {r.companyName || r.symbol}
                                                    </div>
                                                )}
                                                <div className="mono" style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>
                                                    {r.symbol}
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td align="right" className="mono" style={{ fontSize: 13, color: 'var(--text-2)' }}>
                                        {r.qty.toLocaleString('en-IN')}
                                    </td>
                                    <td align="right" className="mono" style={{ fontSize: 13, color: 'var(--text-2)' }}>
                                        ₹{r.avg.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                                    </td>
                                    <td align="right" className="mono" style={{ fontSize: 13, color: 'var(--text-2)' }}>
                                        ₹{r.cur.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                                    </td>
                                    <td align="right" className="mono" style={{ fontSize: 13, fontWeight: 600 }}>
                                        {UI.fmtINR(r.value)}
                                    </td>
                                    <td align="right" className="mono" style={{
                                        fontSize: 13, fontWeight: 600,
                                        color: r.profit >= 0 ? 'var(--up)' : 'var(--down)',
                                    }}>
                                        {r.profit >= 0 ? '+' : ''}{UI.fmtINR(r.profit)}
                                    </td>
                                    <td align="right" className="mono" style={{
                                        fontSize: 13, fontWeight: 600,
                                        color: r.profitPct >= 0 ? 'var(--up)' : 'var(--down)',
                                    }}>
                                        {UI.fmtPct(r.profitPct)}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
}

// Two-slice donut: equity vs cash. Matches the chart-line palette so
// the Holdings card visually rhymes with the timeline above it
// (chart-2 = equity, chart-3 = cash on hold).
function SplitDonut({ equityValue, cashOnHold }) {
    const total = Math.max(0.0001, equityValue + cashOnHold);
    const equityFrac = equityValue / total;

    const size = 140;
    const stroke = 18;
    const r = (size - stroke) / 2;
    const c = 2 * Math.PI * r;
    const equityLen = c * equityFrac;
    const cashLen = c - equityLen;

    return (
        <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            gap: 14, paddingLeft: 8,
        }}>
            <div style={{ position: 'relative', width: size, height: size, flex: 'none' }}>
                <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
                    {/* Cash slice — drawn first as the full ring background. */}
                    <circle cx={size / 2} cy={size / 2} r={r}
                        fill="none" stroke="var(--chart-3)" strokeWidth={stroke}
                        opacity={cashOnHold > 0 ? 1 : 0.25} />
                    {/* Equity slice on top, measured from 12 o'clock. */}
                    {equityValue > 0 && (
                        <circle cx={size / 2} cy={size / 2} r={r}
                            fill="none" stroke="var(--chart-2)" strokeWidth={stroke}
                            strokeDasharray={`${equityLen} ${cashLen}`}
                            strokeDashoffset={c / 4}
                            transform={`rotate(-90 ${size / 2} ${size / 2})`}
                            strokeLinecap="butt" />
                    )}
                </svg>
                <div style={{
                    position: 'absolute', inset: 0,
                    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                    pointerEvents: 'none',
                }}>
                    <div style={{ fontSize: 10.5, color: 'var(--text-3)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>
                        Equity
                    </div>
                    <div className="mono" style={{ fontSize: 18, fontWeight: 600, lineHeight: 1.1 }}>
                        {(equityFrac * 100).toFixed(0)}%
                    </div>
                </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 12 }}>
                <DonutLegendRow color="var(--chart-2)" label="Equity" pct={equityFrac * 100} />
                <DonutLegendRow color="var(--chart-3)" label="Cash" pct={(1 - equityFrac) * 100} />
            </div>
        </div>
    );
}

function DonutLegendRow({ color, label, pct }) {
    return (
        <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <span style={{ width: 10, height: 10, borderRadius: 2, background: color, flex: 'none' }} />
            <span style={{ color: 'var(--text-2)' }}>{label}</span>
            <span className="mono" style={{ marginLeft: 'auto', fontWeight: 600, color: 'var(--text)' }}>
                {pct.toFixed(0)}%
            </span>
        </div>
    );
}

window.HoldingsCard = HoldingsCard;
