import React, { useState, useMemo } from 'react';
import {
  Briefcase,
  TrendingUp,
  ShieldAlert,
  Layers,
  Award,
  CheckCircle2,
  AlertTriangle,
  Smartphone,
  Monitor,
  Compass,
  BookOpen,
  Activity,
  Database,
  X,
  Plus,
  Cloud,
  Copy,
  Check,
  Maximize2,
  Minimize2,
  ChevronRight,
  ArrowLeft,
  Sparkles,
  Calculator
} from 'lucide-react';

// ==================== FORMATTING HELPERS ====================
const fmtINR = (val, digits = 0) => {
  if (val === null || val === undefined || Number.isNaN(Number(val))) return '—';
  const num = Number(val);
  const sign = num < 0 ? '−' : '';
  return `${sign}₹${Math.abs(num).toLocaleString('en-IN', {
    minimumFractionDigits: digits,
    maximumFractionDigits: digits
  })}`;
};

const fmtCompactINR = (val) => {
  if (val === null || val === undefined || Number.isNaN(Number(val))) return '—';
  const num = Number(val);
  const sign = num < 0 ? '−' : '';
  const abs = Math.abs(num);
  if (abs >= 10000000) return `${sign}₹${(abs / 10000000).toFixed(2)} Cr`;
  if (abs >= 100000) return `${sign}₹${(abs / 100000).toFixed(2)} L`;
  if (abs >= 1000) return `${sign}₹${(abs / 1000).toFixed(1)} K`;
  return `${sign}₹${abs.toFixed(0)}`;
};

const fmtPct = (val, digits = 1) => {
  if (val === null || val === undefined || Number.isNaN(Number(val))) return '—';
  const num = Number(val);
  return `${num >= 0 ? '+' : ''}${num.toFixed(digits)}%`;
};

// ==================== ALGORITHMIC 2D BINARY / SQUARIFIED TREEMAP ENGINE ====================
function compute2DTreemap(items, x, y, w, h) {
  if (!items || items.length === 0 || w <= 0 || h <= 0) return [];
  if (items.length === 1) {
    return [{ ...items[0], x, y, w, h }];
  }
  const total = items.reduce((acc, item) => acc + Math.max(0.0001, item.value), 0);
  let half = 0;
  let splitIdx = 0;
  for (let i = 0; i < items.length; i++) {
    half += Math.max(0.0001, items[i].value);
    if (half >= total / 2) {
      splitIdx = i === items.length - 1 ? Math.max(0, i - 1) : i;
      break;
    }
  }
  const leftItems = items.slice(0, splitIdx + 1);
  const rightItems = items.slice(splitIdx + 1);
  const leftSum = leftItems.reduce((acc, item) => acc + Math.max(0.0001, item.value), 0);
  const ratio = total > 0 ? leftSum / total : 0.5;

  if (w >= h) {
    const wLeft = w * ratio;
    return [
      ...compute2DTreemap(leftItems, x, y, wLeft, h),
      ...compute2DTreemap(rightItems, x + wLeft, y, w - wLeft, h)
    ];
  } else {
    const hTop = h * ratio;
    return [
      ...compute2DTreemap(leftItems, x, y, w, hTop),
      ...compute2DTreemap(rightItems, x, y + hTop, w, h - hTop)
    ];
  }
}

// ==================== COMPLETE VERIFIED PORTFOLIO DATASET ====================
const OWNER_SUMMARIES = {
  All: {
    label: 'All owners',
    sharePct: 100.0,
    marketValue: 1282403.83,
    openCost: 876138.42,
    unrealisedPnl: 406265.41,
    unrealisedPct: 46.37,
    realisedPnl: 481649.62,
    lifetimePnl: 887915.03,
    grossBuys: 6225876.88,
    grossSales: 5831296.78,
    netDeployed: 394580.10,
    txCount: 663,
    openPositions: 34,
    uniqueStocks: 25,
    matchedSells: 259,
    winRate: 50.58,
    avgHoldDays: 196,
    firstTrade: '26 Oct 2020',
    lastTrade: '07 Jul 2026',
    priceAsOf: '27 Nov 2026'
  },
  Mummy: {
    label: 'Mummy',
    sharePct: 83.54,
    marketValue: 1071264.20,
    openCost: 696409.17,
    unrealisedPnl: 374855.03,
    unrealisedPct: 53.83,
    realisedPnl: 98580.12,
    lifetimePnl: 473435.15,
    grossBuys: 2614210.40,
    grossSales: 1989120.15,
    netDeployed: 625090.25,
    txCount: 294,
    openPositions: 24,
    uniqueStocks: 24,
    matchedSells: 112,
    winRate: 54.46,
    avgHoldDays: 248,
    firstTrade: '15 Apr 2021',
    lastTrade: '07 Jul 2026',
    priceAsOf: '27 Nov 2026'
  },
  Haider: {
    label: 'Haider',
    sharePct: 14.52,
    marketValue: 186268.63,
    openCost: 147378.55,
    unrealisedPnl: 38890.08,
    unrealisedPct: 26.39,
    realisedPnl: -2727.45,
    lifetimePnl: 36162.63,
    grossBuys: 215840.50,
    grossSales: 71189.40,
    netDeployed: 144651.10,
    txCount: 50,
    openPositions: 9,
    uniqueStocks: 9,
    matchedSells: 14,
    winRate: 50.00,
    avgHoldDays: 184,
    firstTrade: '04 Jun 2024',
    lastTrade: '07 Jul 2026',
    priceAsOf: '27 Nov 2026'
  },
  Pappa: {
    label: 'Pappa',
    sharePct: 1.94,
    marketValue: 24871.00,
    openCost: 32350.70,
    unrealisedPnl: -7479.70,
    unrealisedPct: -23.12,
    realisedPnl: 385796.95,
    lifetimePnl: 378317.25,
    grossBuys: 3395825.98,
    grossSales: 3770987.23,
    netDeployed: -375161.25,
    txCount: 369,
    openPositions: 1,
    uniqueStocks: 1,
    matchedSells: 133,
    winRate: 47.37,
    avgHoldDays: 154,
    firstTrade: '26 Oct 2020',
    lastTrade: '14 Aug 2023',
    priceAsOf: '27 Nov 2026'
  }
};

const CAP_TIERS = [
  { tier: 'Large', band: '≥ ₹80,000 Cr', stocks: 9, invested: 288803.94, marketValue: 336085.95, valPct: 26.21, costPct: 32.96, pnl: 47282.02, returnPct: 16.37, targetPost15LPct: 41.32, hex: '#294b6a' },
  { tier: 'Mid', band: '₹25,000–80,000 Cr', stocks: 9, invested: 200792.07, marketValue: 313095.10, valPct: 24.41, costPct: 22.92, pnl: 112303.02, returnPct: 55.93, targetPost15LPct: 25.67, hex: '#18866b' },
  { tier: 'Small', band: '₹5,000–25,000 Cr', stocks: 3, invested: 293671.86, marketValue: 561694.08, valPct: 43.80, costPct: 33.52, pnl: 268022.22, returnPct: 91.27, targetPost15LPct: 27.38, hex: '#b58a45' },
  { tier: 'Micro', band: '< ₹5,000 Cr', stocks: 4, invested: 92870.55, marketValue: 71528.70, valPct: 5.58, costPct: 10.60, pnl: -21341.85, returnPct: -22.98, targetPost15LPct: 5.63, hex: '#7c5cbf' }
];

const SECTOR_SUMMARY = [
  { sector: 'Pharmaceuticals & Healthcare', stocks: 1, invested: 203196.16, marketValue: 461144.68, pctPortfolio: 35.96, pctInvested: 23.19, pnl: 257948.52, returnPct: 126.95, color: '#294b6a' },
  { sector: 'IT, AI Hardware & Digital', stocks: 5, invested: 155197.40, marketValue: 197176.30, pctPortfolio: 15.38, pctInvested: 17.71, pnl: 41978.90, returnPct: 27.05, color: '#18866b' },
  { sector: 'Power T&D & Renewables', stocks: 5, invested: 181877.62, marketValue: 184659.45, pctPortfolio: 14.40, pctInvested: 20.76, pnl: 2781.82, returnPct: 1.53, color: '#b58a45' },
  { sector: 'Auto & Auto Ancillaries', stocks: 5, invested: 108040.29, marketValue: 168214.60, pctPortfolio: 13.12, pctInvested: 12.33, pnl: 60174.31, returnPct: 55.70, color: '#7c5cbf' },
  { sector: 'Consumer, Retail & Durables', stocks: 5, invested: 111554.15, marketValue: 140191.70, pctPortfolio: 10.93, pctInvested: 12.73, pnl: 28637.55, returnPct: 25.67, color: '#2563eb' },
  { sector: 'Defence & Aerospace', stocks: 1, invested: 66832.10, marketValue: 66243.45, pctPortfolio: 5.17, pctInvested: 7.63, pnl: -588.65, returnPct: -0.88, color: '#0d9488' },
  { sector: 'Cement, Metals & Infrastructure', stocks: 2, invested: 42381.70, marketValue: 60156.40, pctPortfolio: 4.69, pctInvested: 4.84, pnl: 17774.70, returnPct: 41.94, color: '#d97706' },
  { sector: 'Specialty & Agro Chemicals', stocks: 1, invested: 7059.00, marketValue: 4617.25, pctPortfolio: 0.36, pctInvested: 0.81, pnl: -2441.75, returnPct: -34.59, color: '#475569' }
];

const ACTIVE_STOCKS = [
  {
    symbol: 'MARKSANS', name: 'Marksans Pharma Ltd.', cap: 'Small', mcapCr: 12522, sector: 'Pharmaceuticals & Healthcare',
    qty: 1669, avgCost: 121.75, cmp: 276.30, costBasis: 203196.16, marketValue: 461144.68, weightPct: 35.96, post15LWt: 16.57,
    unrealisedPnl: 257948.52, unrealisedPct: 126.95, realisedPnl: 0, xirrPct: 26.4,
    argonAction: 'TRIM ON STRENGTH / HOLD CORE', actionColor: 'amber',
    watchZone: '₹245–₹270 (Add) · ₹295–₹315 (Partial Trim)',
    folder: 'stocks/active/MARKSANS.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 1417, avgCost: 107.48, costBasis: 152298.83, marketValue: 391517.08, pnl: 239218.25, pnlPct: 157.07, xirr: 27.8 },
      { owner: 'Haider', account: 'Mummy', qty: 252, avgCost: 201.97, costBasis: 50897.33, marketValue: 69627.60, pnl: 18730.27, pnlPct: 36.80, xirr: 18.6 }
    ],
    fifoLots: [
      { label: "18 Aug '21 · Mummy (#1)", owner: 'Mummy', qty: 400, buyPrice: 70.20 },
      { label: "25 Oct '21 · Mummy (#2)", owner: 'Mummy', qty: 517, buyPrice: 76.40 },
      { label: "14 Nov '23 · Mummy (#3)", owner: 'Mummy', qty: 250, buyPrice: 144.10 },
      { label: "04 Jun '24 · Haider (#4)", owner: 'Haider', qty: 132, buyPrice: 188.50 },
      { label: "12 Mar '25 · Mummy (#5)", owner: 'Mummy', qty: 250, buyPrice: 215.00 },
      { label: "18 Apr '25 · Haider (#6)", owner: 'Haider', qty: 120, buyPrice: 212.30 }
    ],
    snapshot: 'International OTC and private-label formulations manufacturer (~80% OTC; US 52%, UK/EU 34%). Net cash ₹646 Cr; Q1 FY27 revenue ₹840.8 Cr, PAT ₹159.4 Cr.',
    risks: 'Top-2 customer concentration (23%), 278 inventory days, USFDA/MHRA compliance.',
    decisionHistory: '28 Oct 2026 — Retain existing 1,669-share core holding subject to monitoring.'
  },
  {
    symbol: 'APARINDS', name: 'Apar Industries Ltd.', cap: 'Mid', mcapCr: 59291, sector: 'Power T&D & Renewables',
    qty: 7, avgCost: 8252.64, cmp: 14160.00, costBasis: 57768.47, marketValue: 99120.00, weightPct: 7.73, post15LWt: 3.56,
    unrealisedPnl: 41351.53, unrealisedPct: 71.58, realisedPnl: 51651.92, xirrPct: 48.2,
    argonAction: 'HOLD (CORE)', actionColor: 'emerald',
    watchZone: 'Add only on dips to ₹12,500–₹13,000',
    folder: 'stocks/active/APARINDS.md',
    ownerLots: [
      { owner: 'Haider', account: 'Mummy', qty: 4, avgCost: 8089.29, costBasis: 32357.16, marketValue: 56640.00, pnl: 24282.84, pnlPct: 75.05, xirr: 51.4 },
      { owner: 'Mummy', account: 'Mummy', qty: 3, avgCost: 8470.43, costBasis: 25411.31, marketValue: 42480.00, pnl: 17068.69, pnlPct: 67.17, xirr: 44.8 }
    ],
    fifoLots: [
      { label: "19 Jul '24 · Mummy (#1)", owner: 'Mummy', qty: 3, buyPrice: 8470.43 },
      { label: "05 Sep '24 · Haider (#2)", owner: 'Haider', qty: 4, buyPrice: 8089.29 }
    ],
    snapshot: 'Global leader in power transmission conductors, transformer oils, and specialty cables. Q2 FY27 revenue +21.3% YoY to ₹6,931 Cr, PAT +77.7% YoY to ₹447.3 Cr.',
    risks: 'Aluminium/copper pass-through lags, export freight/tariff volatility.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'MOTHERSON', name: 'Samvardhana Motherson Intl.', cap: 'Large', mcapCr: 171685, sector: 'Auto & Auto Ancillaries',
    qty: 500, avgCost: 94.31, cmp: 161.50, costBasis: 47156.04, marketValue: 80750.00, weightPct: 6.30, post15LWt: 2.90,
    unrealisedPnl: 33593.96, unrealisedPct: 71.24, realisedPnl: 6675.00, xirrPct: 19.8,
    argonAction: 'HOLD & RECONCILE 154 SH', actionColor: 'blue',
    watchZone: 'Hold Mummy 346 sh; reconcile Pappa 154 sh',
    folder: 'stocks/active/MOTHERSON.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 346, avgCost: 42.79, costBasis: 14805.34, marketValue: 55879.00, pnl: 41073.66, pnlPct: 277.42, xirr: 31.2 },
      { owner: 'Pappa', account: 'Pappa', qty: 154, avgCost: 210.07, costBasis: 32350.70, marketValue: 24871.00, pnl: -7479.70, pnlPct: -23.12, xirr: -4.8 }
    ],
    fifoLots: [
      { label: "14 Jun '21 · Mummy (#1)", owner: 'Mummy', qty: 346, buyPrice: 42.79 },
      { label: "22 Jul '21 · Pappa (#2)", owner: 'Pappa', qty: 154, buyPrice: 210.07 }
    ],
    snapshot: 'Global tier-1 automotive wiring harness, vision systems, and polymer module manufacturer. Q2 FY27 revenue +26.9% YoY to ₹38,280 Cr, PAT +42.1% YoY to ₹1,175.3 Cr.',
    risks: 'Modest FY26 ROCE (13.63%); 154-share Pappa ledger variance.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'BEL', name: 'Bharat Electronics Ltd.', cap: 'Large', mcapCr: 345559, sector: 'Defence & Aerospace',
    qty: 161, avgCost: 415.11, cmp: 411.45, costBasis: 66832.10, marketValue: 66243.45, weightPct: 5.17, post15LWt: 6.33,
    unrealisedPnl: -588.65, unrealisedPct: -0.88, realisedPnl: 0, xirrPct: -0.9,
    argonAction: 'HOLD / BUY DIPS (₹370–395)', actionColor: 'emerald',
    watchZone: 'Add ₹1.10L on dips (₹370–₹395) in ₹15L plan',
    folder: 'stocks/active/BEL.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 139, avgCost: 415.80, costBasis: 57795.60, marketValue: 57191.55, pnl: -604.05, pnlPct: -1.05, xirr: -1.1 },
      { owner: 'Haider', account: 'Mummy', qty: 22, avgCost: 410.75, costBasis: 9036.50, marketValue: 9051.90, pnl: 15.40, pnlPct: 0.17, xirr: 0.2 }
    ],
    fifoLots: [
      { label: "18 Jul '24 · Mummy (#1)", owner: 'Mummy', qty: 139, buyPrice: 415.80 },
      { label: "09 Aug '24 · Haider (#2)", owner: 'Haider', qty: 22, buyPrice: 410.75 }
    ],
    snapshot: 'Sovereign defence electronics leader. Debt-free, FY26 ROCE 36.4%, confirmed backlog ₹68,717 Cr (~2.5x revenue). H1 FY27 revenue +25.8% YoY.',
    risks: 'FY26 OCF/PAT ~25% due to receivable build (176 days); QRSAM award timing.',
    decisionHistory: '30 Oct 2026 Recorded Stance — HOLD 161 shares; WAIT for pullback / OCF confirmation.'
  },
  {
    symbol: 'REDINGTON', name: 'Redington Ltd.', cap: 'Mid', mcapCr: 26209, sector: 'IT, AI Hardware & Digital',
    qty: 190, avgCost: 131.91, cmp: 335.25, costBasis: 25062.70, marketValue: 63697.50, weightPct: 4.97, post15LWt: 2.29,
    unrealisedPnl: 38634.80, unrealisedPct: 154.15, realisedPnl: 0, xirrPct: 18.9,
    argonAction: 'HOLD / PARTIAL TRIM', actionColor: 'blue',
    watchZone: 'Cap weight at 5%; optional trim >₹345',
    folder: 'stocks/active/REDINGTON.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 190, avgCost: 131.91, costBasis: 25062.70, marketValue: 63697.50, pnl: 38634.80, pnlPct: 154.15, xirr: 18.9 }
    ],
    fifoLots: [
      { label: "30 Jun '21 · Mummy (#1)", owner: 'Mummy', qty: 190, buyPrice: 131.91 }
    ],
    snapshot: 'Emerging-market IT and cloud distributor. +154.15% gain from June 2021 entry.',
    risks: 'Thin (~2–2.5% OPM) distribution margins, working-capital intensity.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'WAAREEENER', name: 'Waaree Energies Ltd.', cap: 'Mid', mcapCr: 68375, sector: 'Power T&D & Renewables',
    qty: 23, avgCost: 2721.61, cmp: 2377.00, costBasis: 62597.00, marketValue: 54671.00, weightPct: 4.26, post15LWt: 1.96,
    unrealisedPnl: -7926.00, unrealisedPct: -12.66, realisedPnl: 0, xirrPct: -14.2,
    argonAction: 'HOLD (WAIT FOR CELL RAMP)', actionColor: 'amber',
    watchZone: 'Do not average down; await cell margin proof',
    folder: 'stocks/active/WAAREEENER.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 11.5, avgCost: 2721.61, costBasis: 31298.50, marketValue: 27335.50, pnl: -3963.00, pnlPct: -12.66, xirr: -14.2 },
      { owner: 'Haider', account: 'Mummy', qty: 11.5, avgCost: 2721.61, costBasis: 31298.50, marketValue: 27335.50, pnl: -3963.00, pnlPct: -12.66, xirr: -14.2 }
    ],
    fifoLots: [
      { label: "16 Jan '26 · Mummy (#1)", owner: 'Mummy', qty: 11.5, buyPrice: 2721.61 },
      { label: "16 Jan '26 · Haider (#2)", owner: 'Haider', qty: 11.5, buyPrice: 2721.61 }
    ],
    snapshot: 'India’s largest solar PV module manufacturer expanding backward into solar cells and wafers.',
    risks: 'US AD/CVD tariff scrutiny, domestic module overcapacity by FY27–28.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'AFFLE', name: 'Affle 3i Ltd.', cap: 'Small', mcapCr: 23622, sector: 'IT, AI Hardware & Digital',
    qty: 31, avgCost: 1117.04, cmp: 1644.20, costBasis: 34628.30, marketValue: 50970.20, weightPct: 3.97, post15LWt: 3.99,
    unrealisedPnl: 16341.90, unrealisedPct: 47.19, realisedPnl: 0, xirrPct: 11.4,
    argonAction: 'HOLD / BUY DIPS (₹1,450–1,550)', actionColor: 'emerald',
    watchZone: 'Add ₹60K on pullbacks to ₹1,450–₹1,550 in ₹15L plan',
    folder: 'stocks/active/AFFLE.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 31, avgCost: 1117.04, costBasis: 34628.30, marketValue: 50970.20, pnl: 16341.90, pnlPct: 47.19, xirr: 11.4 }
    ],
    fifoLots: [
      { label: "06 Feb '23 · Mummy (#1)", owner: 'Mummy', qty: 31, buyPrice: 1117.04 }
    ],
    snapshot: 'Global consumer-intelligence and CPCU mobile performance ad-tech platform.',
    risks: 'Mobile OS privacy policy shifts, ad-spend cyclicality.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'NETWEB', name: 'Netweb Technologies India Ltd.', cap: 'Small', mcapCr: 24561, sector: 'IT, AI Hardware & Digital',
    qty: 12, avgCost: 4653.95, cmp: 4131.60, costBasis: 55847.40, marketValue: 49579.20, weightPct: 3.87, post15LWt: 1.78,
    unrealisedPnl: -6268.20, unrealisedPct: -11.22, realisedPnl: 0, xirrPct: -13.5,
    argonAction: 'HOLD & WATCH OCF', actionColor: 'amber',
    watchZone: 'Strict pause on fresh buys until OCF turns > 0',
    folder: 'stocks/active/NETWEB.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 12, avgCost: 4653.95, costBasis: 55847.40, marketValue: 49579.20, pnl: -6268.20, pnlPct: -11.22, xirr: -13.5 }
    ],
    fifoLots: [
      { label: "18 Sep '25 · Mummy (#1)", owner: 'Mummy', qty: 12, buyPrice: 4653.95 }
    ],
    snapshot: 'Domestic AI systems and HPC supercomputing hardware integrator. Q2 FY27 revenue +300% YoY to ₹1,323 Cr, PAT ₹137 Cr.',
    risks: 'H1 FY27 operating cash flow was -₹639 Cr due to ₹1,931 Cr inventory build; QIP dilution.',
    decisionHistory: '27 Oct 2026 Stance — High-growth/high-expectation; monitor cash conversion.'
  },
  {
    symbol: 'TMCV', name: 'Tata Motors Ltd. (Commercial Vehicles)', cap: 'Large', mcapCr: 156502, sector: 'Auto & Auto Ancillaries',
    qty: 114, avgCost: 146.41, cmp: 424.95, costBasis: 16690.74, marketValue: 48444.30, weightPct: 3.78, post15LWt: 1.74,
    unrealisedPnl: 31753.56, unrealisedPct: 190.25, realisedPnl: 0, xirrPct: 23.6,
    argonAction: 'HOLD (CORE CV)', actionColor: 'emerald',
    watchZone: 'Hold stronger post-demerger M&HCV leader',
    folder: 'stocks/active/TMCV.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 114, avgCost: 146.41, costBasis: 16690.74, marketValue: 48444.30, pnl: 31753.56, pnlPct: 190.25, xirr: 23.6 }
    ],
    fifoLots: [
      { label: "17 Nov '21 · Mummy (#1)", owner: 'Mummy', qty: 114, buyPrice: 146.41 }
    ],
    snapshot: 'Demerged Commercial Vehicles entity of Tata Motors leading India’s M&HCV truck and transit bus market (+190.25% gain).',
    risks: 'Domestic freight and infrastructure capex cyclicality.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'JKCEMENT', name: 'J.K. Cement Ltd.', cap: 'Mid', mcapCr: 42268, sector: 'Cement, Metals & Infrastructure',
    qty: 8, avgCost: 3460.90, cmp: 5470.30, costBasis: 27687.20, marketValue: 43762.40, weightPct: 3.41, post15LWt: 1.57,
    unrealisedPnl: 16075.20, unrealisedPct: 58.06, realisedPnl: 11340.15, xirrPct: 10.4,
    argonAction: 'HOLD (CORE INFRA)', actionColor: 'emerald',
    watchZone: 'Hold 8 shares as housing/cement proxy',
    folder: 'stocks/active/JKCEMENT.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 8, avgCost: 3460.90, costBasis: 27687.20, marketValue: 43762.40, pnl: 16075.20, pnlPct: 58.06, xirr: 10.4 }
    ],
    fifoLots: [
      { label: "09 Mar '22 · Mummy (#1)", owner: 'Mummy', qty: 8, buyPrice: 3460.90 }
    ],
    snapshot: 'Top-performing mid-cap grey cement expansion play backed by high-margin white cement and wall putty cash flows.',
    risks: 'Regional cement pricing wars, fuel cost spikes.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'HINDUNILVR', name: 'Hindustan Unilever Ltd.', cap: 'Large', mcapCr: 497455, sector: 'Consumer, Retail & Durables',
    qty: 20, avgCost: 2569.93, cmp: 2117.20, costBasis: 51398.65, marketValue: 42344.00, weightPct: 3.30, post15LWt: 1.52,
    unrealisedPnl: -9054.65, unrealisedPct: -17.62, realisedPnl: 3919.20, xirrPct: -4.6,
    argonAction: 'HOLD / OPTIONAL SWITCH', actionColor: 'amber',
    watchZone: 'Do not average down; switch on bounce >₹2,300',
    folder: 'stocks/active/HINDUNILVR.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 20, avgCost: 2569.93, costBasis: 51398.65, marketValue: 42344.00, pnl: -9054.65, pnlPct: -17.62, xirr: -4.6 }
    ],
    fifoLots: [
      { label: "08 Aug '23 · Mummy (#1)", owner: 'Mummy', qty: 20, buyPrice: 2569.93 }
    ],
    snapshot: 'India’s largest FMCG bellwether (>80% ROCE), but sluggish 2–4% volume growth fails your growth screen.',
    risks: 'Single-digit volume growth, D2C competition, P/E de-rating.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'CARYSIL', name: 'Carysil Ltd.', cap: 'Micro', mcapCr: 2461, sector: 'Consumer, Retail & Durables',
    qty: 46, avgCost: 625.66, cmp: 865.15, costBasis: 28780.35, marketValue: 39796.90, weightPct: 3.10, post15LWt: 1.43,
    unrealisedPnl: 11016.55, unrealisedPct: 38.28, realisedPnl: 6667.40, xirrPct: 12.8,
    argonAction: 'HOLD (EXPORT NICHE)', actionColor: 'emerald',
    watchZone: 'Well-sized 3.1% Micro-Cap export play',
    folder: 'stocks/active/CARYSIL.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 46, avgCost: 625.66, costBasis: 28780.35, marketValue: 39796.90, pnl: 11016.55, pnlPct: 38.28, xirr: 12.8 }
    ],
    fifoLots: [
      { label: "11 Mar '24 · Mummy (#1)", owner: 'Mummy', qty: 46, buyPrice: 625.66 }
    ],
    snapshot: 'Global Schock-technology composite quartz kitchen sink exporter + domestic kitchen appliance brand.',
    risks: 'European/UK housing renovation slowdown, Red Sea freight rates.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'TMPV', name: 'Tata Motors Passenger Vehicles Ltd.', cap: 'Large', mcapCr: 95023, sector: 'Auto & Auto Ancillaries',
    qty: 114, avgCost: 323.59, cmp: 258.00, costBasis: 36889.26, marketValue: 29412.00, weightPct: 2.29, post15LWt: 1.06,
    unrealisedPnl: -7477.26, unrealisedPct: -20.27, realisedPnl: 0, xirrPct: -4.4,
    argonAction: 'HOLD (NO ADD)', actionColor: 'amber',
    watchZone: 'Combined TMCV+TMPV is +45.3%; do not add',
    folder: 'stocks/active/TMPV.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 114, avgCost: 323.59, costBasis: 36889.26, marketValue: 29412.00, pnl: -7477.26, pnlPct: -20.27, xirr: -4.4 }
    ],
    fifoLots: [
      { label: "17 Nov '21 · Mummy (#1)", owner: 'Mummy', qty: 114, buyPrice: 323.59 }
    ],
    snapshot: 'Demerged Domestic PV/EV + Jaguar Land Rover luxury auto arm. Combined with TMCV, original 2021 lot is up +45.31%.',
    risks: 'Heavy JLR & domestic EV platform capex, China/Europe luxury auto demand softness.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'DIXON', name: 'Dixon Technologies (India) Ltd.', cap: 'Mid', mcapCr: 80366, sector: 'Consumer, Retail & Durables',
    qty: 2, avgCost: 2712.00, cmp: 13138.00, costBasis: 5424.00, marketValue: 26276.00, weightPct: 2.05, post15LWt: 0.94,
    unrealisedPnl: 20852.00, unrealisedPct: 384.44, realisedPnl: 39659.95, xirrPct: 52.4,
    argonAction: 'HOLD (FREE RUNNER)', actionColor: 'emerald',
    watchZone: 'Hold 2 free-ride shares; avoid ~90x P/E',
    folder: 'stocks/active/DIXON.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 2, avgCost: 2712.00, costBasis: 5424.00, marketValue: 26276.00, pnl: 20852.00, pnlPct: 384.44, xirr: 52.4 }
    ],
    fifoLots: [
      { label: "21 Feb '23 · Mummy (#1)", owner: 'Mummy', qty: 2, buyPrice: 2712.00 }
    ],
    snapshot: 'India’s flagship EMS manufacturer (+384.44% gain on 2 remaining shares after banking +₹39,660 realised profit).',
    risks: 'Demanding ~85–100x P/E valuation multiple, thin (~4%) assembly margins.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'SHILCTECH', name: 'Shilchar Technologies Ltd.', cap: 'Micro', mcapCr: 3577, sector: 'Power T&D & Renewables',
    qty: 7, avgCost: 3483.39, cmp: 3126.40, costBasis: 24383.70, marketValue: 21884.80, weightPct: 1.71, post15LWt: 4.20,
    unrealisedPnl: -2498.90, unrealisedPct: -10.25, realisedPnl: 0, xirrPct: -11.6,
    argonAction: 'BUY DIPS / SCALE UP', actionColor: 'emerald',
    watchZone: 'Add ₹95K across 3 tranches near ₹2,850–₹3,125',
    folder: 'stocks/active/SHILCTECH.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 3.5, avgCost: 3483.39, costBasis: 12191.85, marketValue: 10942.40, pnl: -1249.45, pnlPct: -10.25, xirr: -11.6 },
      { owner: 'Haider', account: 'Mummy', qty: 3.5, avgCost: 3483.39, costBasis: 12191.85, marketValue: 10942.40, pnl: -1249.45, pnlPct: -10.25, xirr: -11.6 }
    ],
    fifoLots: [
      { label: "16 Jan '26 · Mummy (#1)", owner: 'Mummy', qty: 3.5, buyPrice: 3483.39 },
      { label: "16 Jan '26 · Haider (#2)", owner: 'Haider', qty: 3.5, buyPrice: 3483.39 }
    ],
    snapshot: 'Debt-free renewable & export transformer specialist with ~28–30% operating margins and >50% ROCE. Top underweight scale-up pick.',
    risks: 'Transformer margin normalisation as capacity expands.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'DMART', name: 'Avenue Supermarts Ltd.', cap: 'Large', mcapCr: 231003, sector: 'Consumer, Retail & Durables',
    qty: 6, avgCost: 3306.30, cmp: 3541.30, costBasis: 19837.80, marketValue: 21247.80, weightPct: 1.66, post15LWt: 0.76,
    unrealisedPnl: 1410.00, unrealisedPct: 7.11, realisedPnl: 161908.15, xirrPct: 1.4,
    argonAction: 'HOLD RESIDUAL (NO ADD)', actionColor: 'blue',
    watchZone: 'Already banked +₹1.62L realised; do not add at ~74x P/E',
    folder: 'stocks/active/DMART.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 6, avgCost: 3306.30, costBasis: 19837.80, marketValue: 21247.80, pnl: 1410.00, pnlPct: 7.11, xirr: 1.4 }
    ],
    fifoLots: [
      { label: "16 Nov '21 · Mummy (#1)", owner: 'Mummy', qty: 6, buyPrice: 3306.30 }
    ],
    snapshot: 'Q2 FY27 revenue +17.8% YoY to ₹19,644 Cr, but EBITDA margin compressed to 7.1% amidst Quick Commerce pressure.',
    risks: 'Quick-commerce competition in metros, demanding ~74x P/E.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'INFY', name: 'Infosys Ltd.', cap: 'Large', mcapCr: 466320, sector: 'IT, AI Hardware & Digital',
    qty: 18, avgCost: 1621.75, cmp: 1151.30, costBasis: 29191.50, marketValue: 20723.40, weightPct: 1.62, post15LWt: 0.74,
    unrealisedPnl: -8468.10, unrealisedPct: -29.01, realisedPnl: 7718.45, xirrPct: -6.9,
    argonAction: 'HOLD (VALUE / DIVIDEND)', actionColor: 'blue',
    watchZone: 'Hold at cyclical trough valuation (~3.5% div yield)',
    folder: 'stocks/active/INFY.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 18, avgCost: 1621.75, costBasis: 29191.50, marketValue: 20723.40, pnl: -8468.10, pnlPct: -29.01, xirr: -6.9 }
    ],
    fifoLots: [
      { label: "18 Apr '22 · Mummy (#1)", owner: 'Mummy', qty: 18, buyPrice: 1621.75 }
    ],
    snapshot: 'Debt-free, 30%+ ROE global IT services bellwether with >85% FCF conversion and ~3.5%+ dividend yield.',
    risks: 'Sluggish global discretionary IT spend, generative-AI billing deflation.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'TATASTEEL', name: 'Tata Steel Ltd.', cap: 'Large', mcapCr: 204463, sector: 'Cement, Metals & Infrastructure',
    qty: 100, avgCost: 146.94, cmp: 163.94, costBasis: 14694.50, marketValue: 16394.00, weightPct: 1.28, post15LWt: 0.00,
    unrealisedPnl: 1699.50, unrealisedPct: 11.57, realisedPnl: 35660.35, xirrPct: 2.1,
    argonAction: 'EXIT ON STRENGTH', actionColor: 'rose',
    watchZone: 'Exit 100 sh into ₹15L deployment pool',
    folder: 'stocks/active/TATASTEEL.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 100, avgCost: 146.94, costBasis: 14694.50, marketValue: 16394.00, pnl: 1699.50, pnlPct: 11.57, xirr: 2.1 }
    ],
    fifoLots: [
      { label: "29 Jul '21 · Mummy (#1)", owner: 'Mummy', qty: 100, buyPrice: 146.94 }
    ],
    snapshot: 'Capital-intensive, leveraged global steel commodity cyclical. Previously banked +₹35,660 realised profit in 2021.',
    risks: 'Chinese steel import dumping, European unit restructuring, high debt.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'MPHASIS', name: 'MphasiS Ltd.', cap: 'Mid', mcapCr: 46633, sector: 'IT, AI Hardware & Digital',
    qty: 5, avgCost: 2093.50, cmp: 2441.20, costBasis: 10467.50, marketValue: 12206.00, weightPct: 0.95, post15LWt: 0.00,
    unrealisedPnl: 1738.50, unrealisedPct: 16.61, realisedPnl: -11949.18, xirrPct: 6.4,
    argonAction: 'EXIT TAIL LOT', actionColor: 'rose',
    watchZone: 'Harvest +16.6% sub-1% tail lot & consolidate',
    folder: 'stocks/active/MPHASIS.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 5, avgCost: 2093.50, costBasis: 10467.50, marketValue: 12206.00, pnl: 1738.50, pnlPct: 16.61, xirr: 6.4 }
    ],
    fifoLots: [
      { label: "16 Jul '24 · Mummy (#1)", owner: 'Mummy', qty: 5, buyPrice: 2093.50 }
    ],
    snapshot: 'Sub-1% (₹12.2K) mid-cap BFSI IT services position that duplicates INFY exposure.',
    risks: 'US regional banking client concentration, sub-scale 0.95% weight.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'ETERNAL', name: 'Eternal Ltd. (Zomato / Blinkit)', cap: 'Large', mcapCr: 334424, sector: 'Consumer, Retail & Durables',
    qty: 29, avgCost: 210.81, cmp: 363.00, costBasis: 6113.35, marketValue: 10527.00, weightPct: 0.82, post15LWt: 3.25,
    unrealisedPnl: 4413.65, unrealisedPct: 72.20, realisedPnl: 24157.50, xirrPct: 34.2,
    argonAction: 'BUY DIPS / SCALE UP', actionColor: 'emerald',
    watchZone: 'Add ₹80K on pullbacks (₹320–₹345)',
    folder: 'stocks/active/ETERNAL.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 19.5, avgCost: 189.20, costBasis: 3689.43, marketValue: 7078.50, pnl: 3389.07, pnlPct: 91.86, xirr: 38.4 },
      { owner: 'Haider', account: 'Mummy', qty: 9.5, avgCost: 255.15, costBasis: 2423.92, marketValue: 3448.50, pnl: 1024.58, pnlPct: 42.27, xirr: 26.1 }
    ],
    fifoLots: [
      { label: "08 Aug '24 · Mummy (#1)", owner: 'Mummy', qty: 19.5, buyPrice: 189.20 },
      { label: "16 Jan '26 · Haider (#2)", owner: 'Haider', qty: 9.5, buyPrice: 255.15 }
    ],
    snapshot: 'Category leader in Indian food delivery and Blinkit quick commerce (+₹24,158 realised profit).',
    risks: 'Quick-commerce dark-store expansion wars and discounting.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'SONACOMS', name: 'Sona BLW Precision Forgings', cap: 'Mid', mcapCr: 54990, sector: 'Auto & Auto Ancillaries',
    qty: 8, avgCost: 684.17, cmp: 879.00, costBasis: 5473.35, marketValue: 7032.00, weightPct: 0.55, post15LWt: 0.25,
    unrealisedPnl: 1558.65, unrealisedPct: 28.48, realisedPnl: null, xirrPct: null,
    argonAction: 'RECONCILE CSV TAG', actionColor: 'blue',
    watchZone: 'Tag 25 Feb 2026 sell row (10142200) with Haider',
    folder: 'stocks/active/SONACOMS.md',
    ownerLots: [
      { owner: 'Haider', account: 'Mummy', qty: 8, avgCost: 684.17, costBasis: 5473.35, marketValue: 7032.00, pnl: 1558.65, pnlPct: 28.48, xirr: null }
    ],
    fifoLots: [
      { label: "05 Sep '24 · Haider (#1)", owner: 'Haider', qty: 8, buyPrice: 684.17 }
    ],
    snapshot: 'holdings.csv shows 0 shares. Tagging Mummy’s 25 Feb 2026 89-share sale with Haider’s 8-share split closes this residual lot.',
    risks: 'Ledger tag discrepancy in P_L_Statement.csv (unmatched sell exception on 8 shares).',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'EKI', name: 'EKI Energy Services Ltd.', cap: 'Micro', mcapCr: 193, sector: 'Power T&D & Renewables',
    qty: 75, avgCost: 435.30, cmp: 69.73, costBasis: 32647.50, marketValue: 5229.75, weightPct: 0.41, post15LWt: 0.00,
    unrealisedPnl: -27417.75, unrealisedPct: -83.98, realisedPnl: -70121.45, xirrPct: -49.2,
    argonAction: 'SELL (TAX-LOSS HARVEST)', actionColor: 'rose',
    watchZone: 'Full exit to harvest ₹27,418 capital loss',
    folder: 'stocks/active/EKI.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 70.5, avgCost: 443.43, costBasis: 31261.78, marketValue: 4915.96, pnl: -26345.82, pnlPct: -84.27, xirr: -49.8 },
      { owner: 'Haider', account: 'Mummy', qty: 4.5, avgCost: 307.94, costBasis: 1385.72, marketValue: 313.79, pnl: -1071.93, pnlPct: -77.36, xirr: -42.1 }
    ],
    fifoLots: [
      { label: "14 Dec '22 · Mummy (#1)", owner: 'Mummy', qty: 70.5, buyPrice: 443.43 },
      { label: "09 Dec '24 · Haider (#2)", owner: 'Haider', qty: 4.5, buyPrice: 307.94 }
    ],
    snapshot: 'Impaired voluntary carbon-credit developer (-83.98% unrealised loss). Sell all 75 shares to harvest ₹27,418 tax loss.',
    risks: 'Collapsed carbon-credit pricing and past auditor/governance red flags.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'EPIGRAL', name: 'Epigral Ltd.', cap: 'Micro', mcapCr: 3984, sector: 'Specialty & Agro Chemicals',
    qty: 5, avgCost: 1411.80, cmp: 923.45, costBasis: 7059.00, marketValue: 4617.25, weightPct: 0.36, post15LWt: 0.00,
    unrealisedPnl: -2441.75, unrealisedPct: -34.59, realisedPnl: 0, xirrPct: -8.9,
    argonAction: 'EXIT TAIL LOT', actionColor: 'rose',
    watchZone: 'Exit ₹4.6K tail lot & upgrade to ACUTAAS',
    folder: 'stocks/active/EPIGRAL.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 5, avgCost: 1411.80, costBasis: 7059.00, marketValue: 4617.25, pnl: -2441.75, pnlPct: -34.59, xirr: -8.9 }
    ],
    fifoLots: [
      { label: "26 Apr '22 · Mummy (#1)", owner: 'Mummy', qty: 5, buyPrice: 1411.80 }
    ],
    snapshot: 'Q2 FY27 PAT +25.5% YoY to ₹64 Cr (~12x P/E), but at ₹4,617 (0.36% weight) it is an immaterial tail lot.',
    risks: 'Chlor-alkali and ECH/CPVC margin cyclicality.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'KEI', name: 'KEI Industries Ltd.', cap: 'Mid', mcapCr: 35904, sector: 'Power T&D & Renewables',
    qty: 1, avgCost: 4480.95, cmp: 3753.90, costBasis: 4480.95, marketValue: 3753.90, weightPct: 0.29, post15LWt: 3.59,
    unrealisedPnl: -727.05, unrealisedPct: -16.23, realisedPnl: 0, xirrPct: -7.6,
    argonAction: 'SCALE UP ON DIPS', actionColor: 'emerald',
    watchZone: 'Add ₹96K across 2 tranches to build 3.6% stake',
    folder: 'stocks/active/KEI.md',
    ownerLots: [
      { owner: 'Haider', account: 'Mummy', qty: 0.5, avgCost: 4480.95, costBasis: 2240.48, marketValue: 1876.95, pnl: -363.53, pnlPct: -16.23, xirr: -7.6 },
      { owner: 'Mummy', account: 'Mummy', qty: 0.5, avgCost: 4480.95, costBasis: 2240.47, marketValue: 1876.95, pnl: -363.52, pnlPct: -16.23, xirr: -7.6 }
    ],
    fifoLots: [
      { label: "05 Sep '24 · Mummy (#1)", owner: 'Mummy', qty: 0.5, buyPrice: 4480.95 },
      { label: "05 Sep '24 · Haider (#2)", owner: 'Haider', qty: 0.5, buyPrice: 4480.95 }
    ],
    snapshot: 'Tier-1 EHV and retail wires & cables compounder (>20% ROCE) held as a 1-share tracking token. Scale to ~₹1.00L in the ₹15L plan.',
    risks: 'Copper volatility and long-term conglomerate competition in wires.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  },
  {
    symbol: 'ESCORTS', name: 'Escorts Kubota Ltd.', cap: 'Mid', mcapCr: 28350, sector: 'Auto & Auto Ancillaries',
    qty: 1, avgCost: 1830.90, cmp: 2576.30, costBasis: 1830.90, marketValue: 2576.30, weightPct: 0.20, post15LWt: 0.00,
    unrealisedPnl: 745.40, unrealisedPct: 40.71, realisedPnl: 84569.15, xirrPct: 11.2,
    argonAction: 'EXIT 1-SH STUB', actionColor: 'rose',
    watchZone: 'Close 1-share stub after ₹84.6K realised win',
    folder: 'stocks/active/ESCORTS.md',
    ownerLots: [
      { owner: 'Mummy', account: 'Mummy', qty: 1, avgCost: 1830.90, costBasis: 1830.90, marketValue: 2576.30, pnl: 745.40, pnlPct: 40.71, xirr: 11.2 }
    ],
    fifoLots: [
      { label: "03 Oct '23 · Mummy (#1)", owner: 'Mummy', qty: 1, buyPrice: 1830.90 }
    ],
    snapshot: 'Leftover 1-share stub from your 2021–2023 Escorts Kubota trade that already banked +₹84,569.15 in verified realised profits.',
    risks: 'Rural monsoon and tractor demand cyclicality.',
    decisionHistory: 'No formal Decision History entry logged yet.'
  }
];

const ARCHIVE_STOCKS = [
  { symbol: '524717', name: 'Titan Biotech Ltd.', cap: 'Micro', sector: 'Pharmaceuticals & Healthcare', period: '2022-06-28 to 2026-01-14', qty: 44, buyVal: 10032.00, sellVal: 46200.95, realisedPnl: 36168.95, owner: 'Mummy' },
  { symbol: '532435', name: 'Saninfra (532435)', cap: 'Small', sector: 'Cement, Metals & Infrastructure', period: '2021-11-24 to 2023-02-14', qty: 840, buyVal: 51470.00, sellVal: 77690.80, realisedPnl: 26220.80, owner: 'Mummy, Pappa' },
  { symbol: 'JSWSTEEL', name: 'JSW Steel Ltd.', cap: 'Large', sector: 'Cement, Metals & Infrastructure', period: '2021-01-25 to 2026-05-29', qty: 678, buyVal: 368169.45, sellVal: 427959.55, realisedPnl: 59790.10, owner: 'Mummy, Pappa' },
  { symbol: 'HAPPSTMNDS', name: 'Happiest Minds Technologies', cap: 'Small', sector: 'IT, AI Hardware & Digital', period: '2021-05-24 to 2021-10-26', qty: 121, buyVal: 123220.25, sellVal: 156985.10, realisedPnl: 33764.85, owner: 'Pappa' },
  { symbol: 'ASIANPAINT', name: 'Asian Paints Ltd.', cap: 'Large', sector: 'Cement, Metals & Infrastructure', period: '2020-10-27 to 2021-10-25', qty: 112, buyVal: 286922.85, sellVal: 319268.25, realisedPnl: 32345.40, owner: 'Pappa' },
  { symbol: 'MSUMI', name: 'Motherson Sumi Wiring India', cap: 'Mid', sector: 'Auto & Auto Ancillaries', period: '2022-01-19 to 2022-04-27', qty: 154, buyVal: 3807.45, sellVal: 25992.89, realisedPnl: 22185.44, owner: 'Pappa' },
  { symbol: 'VGUARD', name: 'V-Guard Industries Ltd.', cap: 'Small', sector: 'Consumer, Retail & Durables', period: '2021-02-04 to 2021-11-29', qty: 1113, buyVal: 261265.10, sellVal: 275018.30, realisedPnl: 13753.20, owner: 'Pappa' },
  { symbol: 'TATAMOTORS', name: 'Tata Motors Ltd (Pre-Demerger)', cap: 'Large', sector: 'Auto & Auto Ancillaries', period: '2021-02-08 to 2021-11-17', qty: 231, buyVal: 74035.00, sellVal: 87094.65, realisedPnl: 13059.65, owner: 'Pappa' },
  { symbol: 'NAUKRI', name: 'Info Edge (India) Ltd.', cap: 'Mid', sector: 'IT, AI Hardware & Digital', period: '2021-02-01 to 2023-08-08', qty: 28, buyVal: 124982.75, sellVal: 137339.50, realisedPnl: 12356.75, owner: 'Mummy, Pappa' },
  { symbol: 'AMBUJACEM', name: 'Ambuja Cements Ltd.', cap: 'Large', sector: 'Cement, Metals & Infrastructure', period: '2021-02-17 to 2021-04-05', qty: 348, buyVal: 99180.00, sellVal: 108280.20, realisedPnl: 9100.20, owner: 'Pappa' },
  { symbol: 'ADANIENT', name: 'Adani Enterprises Ltd.', cap: 'Large', sector: 'Cement, Metals & Infrastructure', period: '2021-02-03 to 2021-04-07', qty: 115, buyVal: 88660.00, sellVal: 95088.15, realisedPnl: 6428.15, owner: 'Pappa' },
  { symbol: 'INDIGO', name: 'InterGlobe Aviation Ltd.', cap: 'Large', sector: 'Cement, Metals & Infrastructure', period: '2020-12-22 to 2020-12-24', qty: 65, buyVal: 99711.70, sellVal: 106112.50, realisedPnl: 6400.80, owner: 'Pappa' },
  { symbol: 'POLYCAB', name: 'Polycab India Ltd.', cap: 'Large', sector: 'Power T&D & Renewables', period: '2021-10-20 to 2021-11-29', qty: 84, buyVal: 200595.15, sellVal: 181145.15, realisedPnl: -19450.00, owner: 'Pappa' },
  { symbol: 'WARDINMOBI', name: 'Wardwizard Innovations & Mobility', cap: 'Micro', sector: 'Auto & Auto Ancillaries', period: '2022-05-09 to 2025-03-03', qty: 862, buyVal: 50406.20, sellVal: 26090.69, realisedPnl: -24315.51, owner: 'Mummy' }
];

const DEPLOYMENT_TARGETS = [
  { symbol: 'GVT&D', name: 'GE Vernova T&D India Ltd.', bucket: 'New Growth Candidate', cap: 'Large', sector: 'Power T&D & Renewables', currentVal: 0, targetAdd: 240000, postWeight: 8.63, refPrice: 1850.0, t1: 80000, t2: 80000, t3: 80000, t4: 0, catalyst: 'Q2 FY27 rev +32% YoY, PAT +44% YoY, EBITDA margin 27.1%, ₹21,440 Cr HVDC/grid backlog, ₹3,250 Cr net cash.' },
  { symbol: 'SOLARINDS', name: 'Solar Industries India Ltd.', bucket: 'New Growth Candidate', cap: 'Large', sector: 'Defence & Aerospace', currentVal: 0, targetAdd: 220000, postWeight: 7.91, refPrice: 10800.0, t1: 75000, t2: 75000, t3: 70000, t4: 0, catalyst: 'Q2 FY27 rev +69% YoY, PAT +79.8% YoY, H1 OPM 28.1%, ₹17,568 Cr defence ammunition & Pinaka rocket backlog.' },
  { symbol: 'HAL', name: 'Hindustan Aeronautics Ltd.', bucket: 'New Growth Candidate', cap: 'Large', sector: 'Defence & Aerospace', currentVal: 0, targetAdd: 180000, postWeight: 6.47, refPrice: 4839.0, t1: 60000, t2: 60000, t3: 60000, t4: 0, catalyst: 'Q2 FY27 rev +14.9% YoY (+38% QoQ), PAT ₹1,936 Cr, ₹2,54,538 Cr aircraft backlog (~8x rev), ₹47,451 Cr cash.' },
  { symbol: 'SYRMA', name: 'Syrma SGS Technology Ltd.', bucket: 'New Growth Candidate', cap: 'Mid', sector: 'IT, AI Hardware & Digital', currentVal: 0, targetAdd: 160000, postWeight: 5.75, refPrice: 580.0, t1: 50000, t2: 0, t3: 60000, t4: 50000, catalyst: 'Q2 FY27 rev +74% YoY, PAT +87% YoY, ₹7,420 Cr EMS/ODM backlog, ₹253 Cr net cash & multi-layer PCB backward integration.' },
  { symbol: 'ACUTAAS', name: 'Acutaas Chemicals Ltd.', bucket: 'New Growth Candidate', cap: 'Mid', sector: 'Pharmaceuticals & Healthcare', currentVal: 0, targetAdd: 160000, postWeight: 5.75, refPrice: 2150.0, t1: 55000, t2: 55000, t3: 50000, t4: 0, catalyst: 'Q2 FY27 rev +42.7% YoY, EBITDA +84.7% YoY (40.3% margin!), PAT +71.2% YoY, Big-Pharma China+1 CDMO & EV electrolytes.' },
  { symbol: 'TARIL', name: 'Transformers & Rectifiers India', bucket: 'New Growth Candidate', cap: 'Small', sector: 'Power T&D & Renewables', currentVal: 0, targetAdd: 140000, postWeight: 5.03, refPrice: 620.0, t1: 45000, t2: 45000, t3: 50000, t4: 0, catalyst: 'Q2 FY27 rev +66% YoY, PAT +338% YoY, order inflows +97% YoY to ₹1,169 Cr, ₹7,237 Cr 220kV–765kV transformer backlog.' },
  { symbol: 'BEL', name: 'Bharat Electronics Ltd.', bucket: 'Scale Existing Holding', cap: 'Large', sector: 'Defence & Aerospace', currentVal: 66243.45, targetAdd: 110000, postWeight: 6.33, refPrice: 411.45, t1: 0, t2: 55000, t3: 0, t4: 55000, catalyst: '36.4% ROCE sovereign defence electronics leader; add on dips toward ₹370–₹395 as H2 OCF improves.' },
  { symbol: 'KEI', name: 'KEI Industries Ltd.', bucket: 'Scale Existing Holding', cap: 'Mid', sector: 'Power T&D & Renewables', currentVal: 3753.90, targetAdd: 96023, postWeight: 3.59, refPrice: 3753.90, t1: 41023, t2: 0, t3: 0, t4: 55000, catalyst: 'Upgrade 1-share tracking token into core EHV/cables compounder (~₹1.00L) as Sanand greenfield plant commissions.' },
  { symbol: 'SHILCTECH', name: 'Shilchar Technologies Ltd.', bucket: 'Scale Existing Holding', cap: 'Micro', sector: 'Power T&D & Renewables', currentVal: 21884.80, targetAdd: 95000, postWeight: 4.20, refPrice: 3126.40, t1: 35000, t2: 30000, t3: 30000, t4: 0, catalyst: 'Debt-free, ~28–30% OPM, >50% ROCE renewable/export transformer jewel; scale from 1.71% to 4.20% weight.' },
  { symbol: 'ETERNAL', name: 'Eternal Ltd. (Zomato / Blinkit)', bucket: 'Scale Existing Holding', cap: 'Large', sector: 'Consumer, Retail & Durables', currentVal: 10527.00, targetAdd: 80000, postWeight: 3.25, refPrice: 363.0, t1: 0, t2: 0, t3: 0, t4: 80000, catalyst: 'Category leader in food delivery & Blinkit quick-commerce; scale from 0.82% to 3.25% on pullbacks (₹320–₹345).' },
  { symbol: 'AFFLE', name: 'Affle 3i Ltd.', bucket: 'Scale Existing Holding', cap: 'Small', sector: 'IT, AI Hardware & Digital', currentVal: 50970.20, targetAdd: 60000, postWeight: 3.99, refPrice: 1644.20, t1: 0, t2: 0, t3: 0, t4: 60000, catalyst: 'Asset-light CPCU mobile performance ad-tech compounder; add ₹60K on pullbacks to ₹1,450–₹1,550.' }
];

const REALISED_BY_YEAR = [
  { year: 2021, pnl: 342180.45, sells: 131 },
  { year: 2022, pnl: 68420.10, sells: 48 },
  { year: 2023, pnl: 41290.80, sells: 39 },
  { year: 2024, pnl: -18450.25, sells: 16 },
  { year: 2025, pnl: -12910.40, sells: 11 },
  { year: 2026, pnl: 61118.92, sells: 14 }
];

const JOURNEY_MILESTONES = [
  { date: '26 Oct 2020', title: 'First recorded purchase', detail: 'Start of the family investing ledger in Pappa’s account.' },
  { date: '18 Jan 2021', title: 'Gross purchases crossed ₹5,00,000', detail: 'Rapid early deployment into large & mid-cap leaders.' },
  { date: '15 Apr 2021', title: 'Mummy’s account first trade', detail: 'Expansion into multi-account family compounding.' },
  { date: '19 Aug 2021', title: 'Core MARKSANS & TATASTEEL accumulation', detail: 'First deep-value small-cap pharma entries at ₹70–₹76/sh.' },
  { date: '14 Nov 2022', title: 'Gross purchases crossed ₹50,00,000', detail: 'Cumulative purchase turnover milestone across accounts.' },
  { date: '04 Jun 2024', title: 'First Haider 50/50 shared allocation trade', detail: 'Multi-generational beneficial-owner tracking initiated.' },
  { date: '29 Nov 2026', title: '₹15.00 Lakh Expansion & Lifecycle Folder Architecture', detail: 'Portfolio scaled toward ₹27.82 Lakhs across 4-tier market caps.' }
];

const BENCHMARK_OWNER_CURVES = {
  All: {
    startDate: '26 Oct 2020', endDate: '27 Nov 2026',
    nifty50Ret: 94.9, nifty50Cagr: 11.8,
    nifty500Ret: 127.4, nifty500Cagr: 14.7,
    portRet: 100.2, portCagr: 12.1, lotXirr: 17.2,
    points: [
      { label: "Oct '20", n50: 100, n500: 100, port: 100 },
      { label: "Oct '21", n50: 151, n500: 161, port: 154 },
      { label: "Oct '22", n50: 152, n500: 160, port: 159 },
      { label: "Oct '23", n50: 163, n500: 179, port: 158 },
      { label: "Oct '24", n50: 207, n500: 243, port: 171 },
      { label: "Oct '25", n50: 215, n500: 245, port: 185 },
      { label: "Nov '26", n50: 194.9, n500: 227.4, port: 200.2 }
    ]
  },
  Mummy: {
    startDate: '15 Apr 2021', endDate: '27 Nov 2026',
    nifty50Ret: 57.3, nifty50Cagr: 8.5,
    nifty500Ret: 79.3, nifty500Cagr: 11.1,
    portRet: 65.2, portCagr: 9.3, lotXirr: 9.4,
    points: [
      { label: "Apr '21", n50: 100, n500: 100, port: 100 },
      { label: "Jan '22", n50: 122, n500: 128, port: 112 },
      { label: "Jan '23", n50: 123, n500: 127, port: 121 },
      { label: "Jan '24", n50: 148, n500: 165, port: 127 },
      { label: "Jan '25", n50: 162, n500: 186, port: 143 },
      { label: "Jan '26", n50: 168, n500: 191, port: 156 },
      { label: "Nov '26", n50: 157.3, n500: 179.3, port: 165.2 }
    ]
  },
  Haider: {
    startDate: '04 Jun 2024', endDate: '27 Nov 2026',
    nifty50Ret: 4.8, nifty50Cagr: 2.0,
    nifty500Ret: 8.0, nifty500Cagr: 3.2,
    portRet: 32.5, portCagr: 12.0, lotXirr: 12.2,
    points: [
      { label: "Jun '24", n50: 100, n500: 100, port: 100 },
      { label: "Oct '24", n50: 114, n500: 118, port: 106 },
      { label: "Mar '25", n50: 102, n500: 101, port: 110 },
      { label: "Sep '25", n50: 115, n500: 117, port: 117 },
      { label: "Mar '26", n50: 109, n500: 112, port: 124 },
      { label: "Nov '26", n50: 104.8, n500: 108.0, port: 132.5 }
    ]
  },
  Pappa: {
    startDate: '26 Oct 2020', endDate: '27 Nov 2026',
    nifty50Ret: 94.9, nifty50Cagr: 11.8,
    nifty500Ret: 127.4, nifty500Cagr: 14.7,
    portRet: 106.8, portCagr: 12.7, lotXirr: 55.6,
    points: [
      { label: "Oct '20", n50: 100, n500: 100, port: 100 },
      { label: "Oct '21", n50: 151, n500: 161, port: 161 },
      { label: "Oct '22", n50: 152, n500: 160, port: 192 },
      { label: "Aug '23", n50: 163, n500: 179, port: 208 },
      { label: "Oct '24", n50: 207, n500: 243, port: 207 },
      { label: "Nov '26", n50: 194.9, n500: 227.4, port: 206.8 }
    ]
  }
};

export default function App() {
  // Device simulator state: 'desktop' | 'fold-unfold' (884px) | 'fold-cover' (344px) | 'mobile' (390px)
  const [deviceMode, setDeviceMode] = useState('desktop');
  const [activePage, setActivePage] = useState('Portfolio');
  const [selectedOwner, setSelectedOwner] = useState('All');
  const [selectedBroker, setSelectedBroker] = useState('All broker accounts');

  // Portfolio page state
  const [simulatePost15L, setSimulatePost15L] = useState(false);
  const [zoomedSector, setZoomedSector] = useState(null);
  const [hoveredTreemapStock, setHoveredTreemapStock] = useState(null);

  // Recommendations page state
  const [sizerSymbol, setSizerSymbol] = useState('GVT&D');
  const [sizerPrice, setSizerPrice] = useState(1850);

  // Stocks page state
  const [stockFolderFilter, setStockFolderFilter] = useState('Active');
  const [selectedStockSymbol, setSelectedStockSymbol] = useState('MARKSANS');

  // Activity page state
  const [activitySubTab, setActivitySubTab] = useState('Performance');

  // Pinned stock for Z Fold 2 Unfolded Split-Pane & Drawer for narrow screens
  const [pinnedStockSymbol, setPinnedStockSymbol] = useState('MARKSANS');
  const [drawerStock, setDrawerStock] = useState(null);
  const [decisionModalOpen, setDecisionModalOpen] = useState(false);
  const [deployGuideModalOpen, setDeployGuideModalOpen] = useState(false);
  const [decisionSym, setDecisionSym] = useState('GVT&D');
  const [decisionAct, setDecisionAct] = useState('BUY (Tranche 1)');
  const [decisionDetails, setDecisionDetails] = useState('43 shares @ ₹1,850 (₹79,550) in Mummy A/c (50% Haider)');
  const [decisionWhy, setDecisionWhy] = useState('Q2 FY27 EBITDA margin 27.1%, PAT +44% YoY, ₹21,440 Cr HVDC backlog with ₹3,250 Cr net cash.');

  const summary = OWNER_SUMMARIES[selectedOwner] || OWNER_SUMMARIES.All;

  const filteredHoldings = useMemo(() => {
    const rows = [];
    ACTIVE_STOCKS.forEach((st) => {
      const matchingLots = st.ownerLots.filter((ol) => {
        const ownerOk = selectedOwner === 'All' || ol.owner === selectedOwner;
        const brokerOk = selectedBroker === 'All broker accounts' || ol.account === selectedBroker;
        return ownerOk && brokerOk;
      });
      if (matchingLots.length > 0) {
        const sumQty = matchingLots.reduce((a, b) => a + b.qty, 0);
        const sumCost = matchingLots.reduce((a, b) => a + b.costBasis, 0);
        const sumVal = matchingLots.reduce((a, b) => a + b.marketValue, 0);
        const sumPnl = matchingLots.reduce((a, b) => a + b.pnl, 0);
        const avgCost = sumQty > 0 ? sumCost / sumQty : 0;
        const pnlPct = sumCost > 0 ? (sumPnl / sumCost) * 100 : 0;
        rows.push({
          ...st,
          displayQty: sumQty,
          displayAvgCost: avgCost,
          displayCost: sumCost,
          displayVal: sumVal,
          displayPnl: sumPnl,
          displayPnlPct: pnlPct,
          matchingLots
        });
      }
    });
    const totalVal = rows.reduce((a, b) => a + b.displayVal, 0);
    return rows
      .map((r) => ({
        ...r,
        displayWeight: simulatePost15L ? r.post15LWt : totalVal > 0 ? (r.displayVal / totalVal) * 100 : 0
      }))
      .sort((a, b) => b.displayVal - a.displayVal);
  }, [selectedOwner, selectedBroker, simulatePost15L]);

  const flattenedOwnerRows = useMemo(() => {
    const list = [];
    filteredHoldings.forEach((h) => {
      h.matchingLots.forEach((ml) => {
        list.push({
          symbol: h.symbol,
          cap: h.cap,
          sector: h.sector,
          argonAction: h.argonAction,
          actionColor: h.actionColor,
          owner: ml.owner,
          account: ml.account,
          qty: ml.qty,
          avgCost: ml.avgCost,
          cmp: h.cmp,
          costBasis: ml.costBasis,
          marketValue: ml.marketValue,
          weightPct: summary.marketValue > 0 ? (ml.marketValue / summary.marketValue) * 100 : 0,
          pnl: ml.pnl,
          pnlPct: ml.pnlPct,
          xirr: ml.xirr
        });
      });
    });
    return list.sort((a, b) => b.marketValue - a.marketValue);
  }, [filteredHoldings, summary.marketValue]);

  const stockDropdownOptions = useMemo(() => {
    const activeSyms = ACTIVE_STOCKS.map((s) => ({ symbol: s.symbol, name: s.name, folder: 'active', data: s }));
    const watchSyms = DEPLOYMENT_TARGETS.filter((t) => t.currentVal === 0).map((t) => ({
      symbol: t.symbol, name: t.name, folder: 'watchlist', data: t
    }));
    const archSyms = ARCHIVE_STOCKS.map((a) => ({ symbol: a.symbol, name: a.name, folder: 'archive', data: a }));
    if (stockFolderFilter === 'Active') return activeSyms;
    if (stockFolderFilter === 'Watchlist') return watchSyms;
    if (stockFolderFilter === 'Archive') return archSyms;
    return [...activeSyms, ...watchSyms, ...archSyms];
  }, [stockFolderFilter]);

  const currentStockDetail = useMemo(() => {
    const foundActive = ACTIVE_STOCKS.find((s) => s.symbol === selectedStockSymbol);
    if (foundActive) return { type: 'active', ...foundActive };
    const foundWatch = DEPLOYMENT_TARGETS.find((t) => t.symbol === selectedStockSymbol && t.currentVal === 0);
    if (foundWatch) return { type: 'watchlist', ...foundWatch };
    const foundArch = ARCHIVE_STOCKS.find((a) => a.symbol === selectedStockSymbol);
    if (foundArch) return { type: 'archive', ...foundArch };
    return { type: 'active', ...ACTIVE_STOCKS[0] };
  }, [selectedStockSymbol]);

  const openStockInPageOrDrawer = (sym, jumpToPage = false) => {
    setPinnedStockSymbol(sym);
    const activeFound = ACTIVE_STOCKS.find((s) => s.symbol === sym);
    if (jumpToPage) {
      setSelectedStockSymbol(sym);
      setActivePage('Stocks');
    } else if (deviceMode === 'fold-unfold') {
      // On Z Fold 2 Unfolded (884px Split-Pane), update the right-hand persistent detail pane immediately without covering the screen!
      setSelectedStockSymbol(sym);
    } else if (activeFound) {
      setDrawerStock(activeFound);
    } else {
      setSelectedStockSymbol(sym);
      setActivePage('Stocks');
    }
  };

  const pinnedStockObj = useMemo(() => {
    return ACTIVE_STOCKS.find((s) => s.symbol === pinnedStockSymbol) || ACTIVE_STOCKS[0];
  }, [pinnedStockSymbol]);

  // Compute True 2D Proportional Squarified Treemap rectangles (100% x 100% coordinate space)
  const treemapLayout = useMemo(() => {
    const sectorGroups = {};
    filteredHoldings.forEach((h) => {
      if (!sectorGroups[h.sector]) {
        const meta = SECTOR_SUMMARY.find((s) => s.sector === h.sector);
        sectorGroups[h.sector] = {
          sector: h.sector,
          color: meta ? meta.color : '#294b6a',
          value: 0,
          stocks: []
        };
      }
      sectorGroups[h.sector].value += h.displayVal;
      sectorGroups[h.sector].stocks.push({
        ...h,
        value: h.displayVal
      });
    });

    const sectorsArray = Object.values(sectorGroups).sort((a, b) => b.value - a.value);
    const totalVal = sectorsArray.reduce((a, b) => a + b.value, 0);

    if (zoomedSector && sectorGroups[zoomedSector]) {
      const sec = sectorGroups[zoomedSector];
      const secRects = [{ ...sec, x: 0, y: 0, w: 100, h: 100, pct: totalVal > 0 ? (sec.value / totalVal) * 100 : 100 }];
      const stockRects = compute2DTreemap(
        sec.stocks.sort((a, b) => b.value - a.value),
        0.6,
        7.5,
        98.8,
        91.5
      ).map((st) => ({
        ...st,
        sectorColor: sec.color,
        rootPct: totalVal > 0 ? (st.value / totalVal) * 100 : 0
      }));
      return { secRects, stockRects, totalVal };
    }

    const secRects = compute2DTreemap(sectorsArray, 0, 0, 100, 100).map((sr) => ({
      ...sr,
      pct: totalVal > 0 ? (sr.value / totalVal) * 100 : 0
    }));

    const stockRects = [];
    secRects.forEach((sr) => {
      const headerH = sr.h > 14 ? 5.2 : 0;
      const padX = 0.4;
      const padY = 0.4;
      const innerX = sr.x + padX;
      const innerY = sr.y + headerH + padY;
      const innerW = Math.max(0.5, sr.w - padX * 2);
      const innerH = Math.max(0.5, sr.h - headerH - padY * 2);
      const children = compute2DTreemap(
        sr.stocks.sort((a, b) => b.value - a.value),
        innerX,
        innerY,
        innerW,
        innerH
      );
      children.forEach((ch) => {
        stockRects.push({
          ...ch,
          sectorColor: sr.color,
          rootPct: totalVal > 0 ? (ch.value / totalVal) * 100 : 0
        });
      });
    });

    return { secRects, stockRects, totalVal };
  }, [filteredHoldings, zoomedSector]);

  const getBadgeStyle = (color) => {
    if (color === 'emerald') return 'bg-emerald-50 text-emerald-800 border-emerald-200';
    if (color === 'amber') return 'bg-amber-50 text-amber-800 border-amber-200';
    if (color === 'rose') return 'bg-rose-50 text-rose-800 border-rose-200';
    return 'bg-blue-50 text-blue-800 border-blue-200';
  };

  // Viewport framing wrapper based on device simulator mode
  const getViewportContainerStyle = () => {
    if (deviceMode === 'fold-cover') {
      return 'w-[344px] h-[820px] mx-auto rounded-[36px] border-[10px] border-slate-950 shadow-2xl overflow-hidden my-3';
    }
    if (deviceMode === 'fold-unfold') {
      return 'w-[884px] h-[860px] mx-auto rounded-[28px] border-[8px] border-slate-950 shadow-2xl overflow-hidden my-3';
    }
    if (deviceMode === 'mobile') {
      return 'w-[390px] h-[840px] mx-auto rounded-[38px] border-[10px] border-slate-950 shadow-2xl overflow-hidden my-3';
    }
    return 'w-full max-w-[1480px] my-3 rounded-2xl border border-slate-300 shadow-xl overflow-hidden';
  };

  const isNarrowViewport = deviceMode === 'fold-cover' || deviceMode === 'mobile';
  const isFoldUnfolded = deviceMode === 'fold-unfold';

  return (
    <div className="min-h-screen bg-slate-900 text-slate-900 flex flex-col items-center pb-10">
      {/* ==================== DEVICE SIMULATOR & CLOUD DEPLOY CONTROL BAR ==================== */}
      <div className="w-full bg-slate-950 border-b border-slate-800 px-3 sm:px-5 py-2 flex flex-wrap items-center justify-between gap-2 sticky top-0 z-50">
        <div className="flex items-center gap-2">
          <span className="inline-flex items-center justify-center w-7 h-7 rounded-lg bg-emerald-500 text-slate-950 font-black text-xs">
            📈
          </span>
          <div>
            <span className="text-white font-bold text-xs sm:text-sm">Family Investment Office OS</span>
            <span className="hidden md:inline-block ml-2 text-[11px] text-emerald-400 font-semibold">
              • True 2D Treemap + Galaxy Z Fold 2 Dual-Screen Edition
            </span>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-1.5">
          <div className="flex items-center gap-1 bg-slate-900 p-1 rounded-xl border border-slate-800 text-[11px]">
            {[
              { id: 'desktop', label: '💻 Desktop' },
              { id: 'fold-unfold', label: '📖 Z Fold 2 Unfolded (884px Split)' },
              { id: 'fold-cover', label: '📱 Z Fold 2 Cover (344px)' },
              { id: 'mobile', label: '📲 Phone (390px)' }
            ].map((d) => (
              <button
                key={d.id}
                onClick={() => setDeviceMode(d.id)}
                className={`px-2.5 py-1 rounded-lg font-bold transition-all ${
                  deviceMode === d.id ? 'bg-emerald-500 text-slate-950 shadow' : 'text-slate-300 hover:text-white'
                }`}
              >
                {d.label}
              </button>
            ))}
          </div>

          <button
            onClick={() => setDeployGuideModalOpen(true)}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-blue-600 hover:bg-blue-500 text-white font-bold text-xs shadow"
          >
            <Cloud className="w-3.5 h-3.5" />
            Zero-Laptop Phone Deploy Guide
          </button>
        </div>
      </div>

      {/* ==================== APP CONTAINER WITH VIEWPORT FRAMING ==================== */}
      <div className={`transition-all duration-300 bg-[#f5f7fa] relative flex flex-col ${getViewportContainerStyle()}`}>
        {/* Status Bar for Mobile / Fold */}
        {(isNarrowViewport || isFoldUnfolded) && (
          <div className="bg-slate-950 text-white px-4 py-1 flex items-center justify-between text-[10px] font-semibold shrink-0">
            <span>9:42 IST · Samsung Galaxy Z Fold 2 {isFoldUnfolded ? '(7.6" Inner Main Display · 884px Split-Pane)' : '(6.2" Outer Cover · 344px)'}</span>
            <span>5G · 100%</span>
          </div>
        )}

        {/* ==================== MAIN CONTENT AREA (WITH Z FOLD 2 UNFOLDED SPLIT-PANE) ==================== */}
        <div className={`flex-1 flex ${isFoldUnfolded ? 'flex-row overflow-hidden' : 'flex-col overflow-y-auto'}`}>
          <main className={`${isFoldUnfolded ? 'w-[56%] h-full overflow-y-auto p-4 border-r border-slate-200' : isNarrowViewport ? 'flex-1 p-2.5 pb-20' : 'flex-1 p-6'} space-y-5`}>
          {/* ==================== PAGE 1: PORTFOLIO ==================== */}
          {activePage === 'Portfolio' && (
            <div className="space-y-5">
              {/* 4 KPIs */}
              <div className={`grid ${isNarrowViewport ? 'grid-cols-2 gap-2' : isFoldUnfolded ? 'grid-cols-2 gap-2.5' : 'grid-cols-4 gap-4'}`}>
                <div className="bg-white p-3.5 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-[#68758a] text-[11px] font-medium">
                    {simulatePost15L ? 'Projected Market Value' : 'Current market value'}
                  </div>
                  <div className={`${isNarrowViewport ? 'text-base' : 'text-xl'} font-extrabold text-[#17253b] mt-1`}>
                    {fmtCompactINR(simulatePost15L ? summary.marketValue + 1500000 : summary.marketValue)}
                  </div>
                  <div className="text-[10px] text-[#68758a] mt-0.5 truncate">
                    {fmtINR(simulatePost15L ? summary.marketValue + 1500000 : summary.marketValue, 0)}
                  </div>
                </div>

                <div className="bg-white p-3.5 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-[#68758a] text-[11px] font-medium">Open cost basis</div>
                  <div className={`${isNarrowViewport ? 'text-base' : 'text-xl'} font-extrabold text-[#17253b] mt-1`}>
                    {fmtCompactINR(simulatePost15L ? summary.openCost + 1500000 : summary.openCost)}
                  </div>
                  <div className="text-[10px] text-[#68758a] mt-0.5 truncate">
                    {fmtINR(simulatePost15L ? summary.openCost + 1500000 : summary.openCost, 0)}
                  </div>
                </div>

                <div className="bg-white p-3.5 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-[#68758a] text-[11px] font-medium">Unrealised P&amp;L</div>
                  <div className={`${isNarrowViewport ? 'text-base' : 'text-xl'} font-extrabold mt-1 ${summary.unrealisedPnl >= 0 ? 'text-[#18866b]' : 'text-[#c54e5e]'}`}>
                    {fmtCompactINR(summary.unrealisedPnl)}
                  </div>
                  <div className={`inline-block text-[10px] font-bold px-1.5 py-0.5 rounded mt-0.5 ${summary.unrealisedPct >= 0 ? 'bg-emerald-50 text-[#18866b]' : 'bg-rose-50 text-[#c54e5e]'}`}>
                    {fmtPct(summary.unrealisedPct, 1)}
                  </div>
                </div>

                <div className="bg-white p-3.5 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-[#68758a] text-[11px] font-medium">Realised P&amp;L · verified</div>
                  <div className={`${isNarrowViewport ? 'text-base' : 'text-xl'} font-extrabold mt-1 ${summary.realisedPnl >= 0 ? 'text-[#18866b]' : 'text-[#c54e5e]'}`}>
                    {fmtCompactINR(summary.realisedPnl)}
                  </div>
                  <div className="text-[10px] text-[#68758a] mt-0.5 truncate">
                    Lifetime: <strong className="text-[#17253b]">{fmtCompactINR(summary.lifetimePnl)}</strong>
                  </div>
                </div>
              </div>

              {/* Guardrail Banner */}
              <div
                className={`rounded-xl p-3.5 border border-l-4 text-xs transition-all ${
                  simulatePost15L
                    ? 'bg-[#f3faf6] border-[#d6ebe0] border-l-[#18866b] text-[#1d5a45]'
                    : 'bg-[#fff8f2] border-[#f0d9c4] border-l-[#c9863f] text-[#6b4a22]'
                }`}
              >
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div className="font-bold text-xs sm:text-sm flex items-center gap-1.5">
                    {simulatePost15L ? <CheckCircle2 className="w-4 h-4 text-[#18866b] shrink-0" /> : <AlertTriangle className="w-4 h-4 text-[#c9863f] shrink-0" />}
                    <span>{simulatePost15L ? 'Post-₹15L State: Guardrails Resolved' : 'Concentration Guardrails (5 alerts):'}</span>
                  </div>
                  <button
                    onClick={() => setSimulatePost15L(!simulatePost15L)}
                    className={`px-2.5 py-1 rounded-lg text-[11px] font-bold transition-all shadow-xs ${
                      simulatePost15L ? 'bg-[#17253b] text-white' : 'bg-[#c9863f] text-white hover:opacity-95'
                    }`}
                  >
                    ✨ {simulatePost15L ? 'Reset ₹12.82L' : 'Simulate Post-₹15L'}
                  </button>
                </div>

                {!simulatePost15L ? (
                  <ul className="list-disc pl-4 mt-1.5 space-y-0.5 text-[11px]">
                    <li><strong>Single-stock:</strong> <code>MARKSANS</code> is <strong>36.0%</strong> (₹4.61L) vs ≤15% cap.</li>
                    <li><strong>Top-5 skew:</strong> Top 5 holdings = <strong>60.1%</strong> vs ≤55% cap.</li>
                    <li><strong>Tail lots:</strong> <strong>7 stocks</strong> sit below 1.0% weight (3.58% total).</li>
                  </ul>
                ) : (
                  <p className="mt-1 text-[11px]">
                    Deploying <strong>₹15.00L cash + ₹41K from 5 tail exits</strong> dilutes <code>MARKSANS</code> from <strong>35.96% → 16.57%</strong> and lifts Large Cap to <strong>41.32%</strong>.
                  </p>
                )}
              </div>

              {/* TRUE 2D PROPORTIONAL SQUARIFIED SECTOR & STOCK TREEMAP */}
              <div className="bg-white p-4 sm:p-5 rounded-2xl border border-[#e7ebf1] shadow-xs space-y-3">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div>
                    <h3 className="text-sm font-bold text-[#17253b]">
                      True 2D Proportional Sector &amp; Stock Treemap (area = ₹ market value)
                    </h3>
                    <p className="text-[11px] text-[#68758a]">
                      Click any sector header to zoom in, or click any stock tile to inspect its FIFO lots &amp; thesis.
                    </p>
                  </div>
                  {zoomedSector && (
                    <button
                      onClick={() => setZoomedSector(null)}
                      className="flex items-center gap-1 px-2.5 py-1 rounded-lg bg-[#17253b] text-white text-xs font-bold"
                    >
                      <ArrowLeft className="w-3.5 h-3.5" /> All Sectors
                    </button>
                  )}
                </div>

                {/* Live Hover Readout Bar */}
                <div className="bg-slate-900 text-white px-3 py-1.5 rounded-xl text-[11px] flex flex-wrap items-center justify-between gap-2">
                  {hoveredTreemapStock ? (
                    <>
                      <span>
                        <strong className="text-emerald-400">{hoveredTreemapStock.symbol}</strong> ({hoveredTreemapStock.name}) · {hoveredTreemapStock.sector}
                      </span>
                      <span>
                        Value: <strong>{fmtINR(hoveredTreemapStock.displayVal, 0)}</strong> ({hoveredTreemapStock.rootPct.toFixed(2)}%) · P&amp;L: <strong className={hoveredTreemapStock.displayPnl >= 0 ? 'text-emerald-400' : 'text-rose-400'}>{fmtPct(hoveredTreemapStock.displayPnlPct, 1)}</strong>
                      </span>
                    </>
                  ) : (
                    <span className="text-slate-300">Hover or tap any 2D tile below to inspect exact rupee market value, portfolio share %, and P&amp;L.</span>
                  )}
                </div>

                {/* 2D Proportional Coordinate Canvas */}
                <div
                  className="relative w-full rounded-xl overflow-hidden border-2 border-slate-200 bg-slate-100 select-none"
                  style={{ height: isNarrowViewport ? '340px' : isFoldUnfolded ? '390px' : '470px' }}
                >
                  {/* Sector Outer Bounding Boxes */}
                  {treemapLayout.secRects.map((sr) => (
                    <div
                      key={sr.sector}
                      onClick={() => setZoomedSector(zoomedSector === sr.sector ? null : sr.sector)}
                      style={{
                        left: `${sr.x}%`,
                        top: `${sr.y}%`,
                        width: `${sr.w}%`,
                        height: `${sr.h}%`,
                        backgroundColor: sr.color
                      }}
                      className="absolute border-2 border-white overflow-hidden cursor-pointer transition-all"
                    >
                      {sr.h > 11 && sr.w > 12 && (
                        <div className="px-1.5 py-0.5 bg-black/30 text-white text-[10px] font-extrabold truncate flex items-center justify-between">
                          <span className="truncate">{sr.sector}</span>
                          <span className="ml-1 shrink-0">{sr.pct.toFixed(1)}%</span>
                        </div>
                      )}
                    </div>
                  ))}

                  {/* Nested 2D Stock Tiles */}
                  {treemapLayout.stockRects.map((st) => {
                    const showTitle = st.w > 5.5 && st.h > 6.5;
                    const showPct = st.w > 8.5 && st.h > 11.5;
                    const showVal = st.w > 12 && st.h > 16;
                    const isPinned = pinnedStockSymbol === st.symbol;
                    return (
                      <div
                        key={st.symbol}
                        onMouseEnter={() => setHoveredTreemapStock(st)}
                        onMouseLeave={() => setHoveredTreemapStock(null)}
                        onClick={(e) => {
                          e.stopPropagation();
                          openStockInPageOrDrawer(st.symbol);
                        }}
                        style={{
                          left: `${st.x}%`,
                          top: `${st.y}%`,
                          width: `${st.w}%`,
                          height: `${st.h}%`,
                          backgroundColor: st.sectorColor
                        }}
                        className={`absolute border border-white/80 hover:brightness-110 cursor-pointer flex flex-col items-center justify-center text-center p-1 transition-all ${
                          isPinned ? 'ring-2 ring-amber-300 z-10' : ''
                        }`}
                      >
                        {showTitle && (
                          <div className="text-white font-extrabold leading-tight truncate max-w-full" style={{ fontSize: st.w > 18 ? '13px' : '10px' }}>
                            {st.symbol}
                          </div>
                        )}
                        {showPct && (
                          <div className="text-white/95 font-bold leading-tight" style={{ fontSize: st.w > 18 ? '11px' : '9px' }}>
                            {st.rootPct.toFixed(1)}%
                          </div>
                        )}
                        {showVal && (
                          <div className="text-white/85 font-semibold leading-tight mt-0.5" style={{ fontSize: '9px' }}>
                            {fmtCompactINR(st.displayVal)}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Adaptive Largest Positions: Swipeable Cards on Z Fold 2 Cover (344px) vs Table on Larger Screens */}
              <div className="bg-white p-4 sm:p-5 rounded-2xl border border-[#e7ebf1] shadow-xs">
                <div className="flex items-center justify-between mb-3">
                  <h3 className="text-sm font-bold text-[#17253b]">
                    Largest positions ({filteredHoldings.length} active stocks)
                  </h3>
                  <span className="text-[11px] text-[#68758a]">Tap any stock to inspect</span>
                </div>

                {isNarrowViewport ? (
                  <div className="space-y-2">
                    {filteredHoldings.slice(0, 12).map((h) => (
                      <div
                        key={h.symbol}
                        onClick={() => openStockInPageOrDrawer(h.symbol)}
                        className="p-2.5 rounded-xl border border-slate-200 hover:border-emerald-500 bg-slate-50/60 flex items-center justify-between gap-2 cursor-pointer"
                      >
                        <div className="min-w-0">
                          <div className="flex items-center gap-1.5">
                            <span className="font-extrabold text-xs text-[#17253b]">{h.symbol}</span>
                            <span className="px-1.5 py-0.2 rounded text-[9px] font-bold bg-slate-200 text-slate-700">{h.cap}</span>
                            <span className="text-[10px] font-bold text-slate-500">{h.displayWeight.toFixed(1)}%</span>
                          </div>
                          <div className="text-[10px] text-[#68758a] truncate mt-0.5">{h.argonAction}</div>
                        </div>
                        <div className="text-right shrink-0">
                          <div className="font-extrabold text-xs text-[#17253b]">{fmtINR(h.displayVal, 0)}</div>
                          <div className={`text-[10px] font-bold ${h.displayPnl >= 0 ? 'text-[#18866b]' : 'text-[#c54e5e]'}`}>
                            {fmtPct(h.displayPnlPct, 1)}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="w-full text-left border-collapse text-xs">
                      <thead>
                        <tr className="border-b border-slate-200 text-[#68758a] text-[11px]">
                          <th className="py-2 px-2">Symbol</th>
                          <th className="py-2 px-2">Cap</th>
                          <th className="py-2 px-2">ArgonAction</th>
                          <th className="py-2 px-2 text-right">CurrentValue</th>
                          <th className="py-2 px-2 text-right">Weight</th>
                          <th className="py-2 px-2 text-right">UnrealizedPnL</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100">
                        {filteredHoldings.slice(0, 12).map((h) => (
                          <tr
                            key={h.symbol}
                            onClick={() => openStockInPageOrDrawer(h.symbol)}
                            className={`hover:bg-slate-50 cursor-pointer ${pinnedStockSymbol === h.symbol && isFoldUnfolded ? 'bg-emerald-50/70' : ''}`}
                          >
                            <td className="py-2 px-2 font-bold text-[#17253b]">{h.symbol}</td>
                            <td className="py-2 px-2"><span className="px-1.5 py-0.5 rounded text-[10px] font-bold bg-slate-100 text-slate-700">{h.cap}</span></td>
                            <td className="py-2 px-2"><span className={`px-2 py-0.5 rounded text-[10px] font-bold border ${getBadgeStyle(h.actionColor)}`}>{h.argonAction}</span></td>
                            <td className="py-2 px-2 text-right font-bold text-[#17253b]">{fmtINR(h.displayVal, 0)}</td>
                            <td className="py-2 px-2 text-right font-bold">{h.displayWeight.toFixed(1)}%</td>
                            <td className={`py-2 px-2 text-right font-bold ${h.displayPnl >= 0 ? 'text-[#18866b]' : 'text-[#c54e5e]'}`}>
                              {fmtINR(h.displayPnl, 0)} ({fmtPct(h.displayPnlPct, 1)})
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>

              {/* Market-Cap Allocation Section */}
              <div className="bg-white p-4 sm:p-5 rounded-2xl border border-[#e7ebf1] shadow-xs space-y-4">
                <h3 className="text-sm font-bold text-[#17253b]">Market-cap allocation (4-Tier: Large / Mid / Small / Micro)</h3>
                <div className={`grid ${isNarrowViewport || isFoldUnfolded ? 'grid-cols-2 gap-2' : 'grid-cols-4 gap-3'}`}>
                  {CAP_TIERS.map((c) => (
                    <div key={c.tier} className="p-3 rounded-xl border border-[#e7ebf1] bg-slate-50/60">
                      <div className="text-[11px] text-[#68758a] font-medium">{c.tier} Cap ({c.stocks})</div>
                      <div className="text-lg font-extrabold text-[#17253b] mt-0.5">{(simulatePost15L ? c.targetPost15LPct : c.valPct).toFixed(1)}%</div>
                      <div className={`text-[10px] font-bold mt-0.5 ${c.returnPct >= 0 ? 'text-[#18866b]' : 'text-[#c54e5e]'}`}>
                        {fmtPct(c.returnPct, 1)} · {fmtCompactINR(c.marketValue)}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* ==================== PAGE 2: RECOMMENDATIONS & ₹15L PLAN ==================== */}
          {activePage === 'Recommendations' && (
            <div className="space-y-6">
              <div className={`grid ${isNarrowViewport ? 'grid-cols-2 gap-2' : 'grid-cols-4 gap-4'}`}>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-xs text-[#68758a]">Current Priced Portfolio</div>
                  <div className="text-xl font-extrabold text-[#17253b] mt-1">₹12.82 L</div>
                </div>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-xs text-[#68758a]">New Cash + Tail Exits</div>
                  <div className="text-xl font-extrabold text-[#18866b] mt-1">₹15.41 L</div>
                </div>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-xs text-[#68758a]">Projected Portfolio Value</div>
                  <div className="text-xl font-extrabold text-[#17253b] mt-1">₹27.82 L</div>
                </div>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-xs text-[#68758a]">Deployment Structure</div>
                  <div className="text-xl font-extrabold text-[#17253b] mt-1">4 Tranches</div>
                </div>
              </div>

              {/* Tranche Schedule Table & Calculator */}
              <div className="bg-white p-5 rounded-2xl border border-[#e7ebf1] shadow-xs space-y-4">
                <h3 className="text-sm font-bold text-[#17253b]">4-Tranche deployment schedule &amp; share-quantity calculator</h3>
                <div className="overflow-x-auto">
                  <table className="w-full text-left border-collapse text-xs">
                    <thead>
                      <tr className="border-b border-slate-200 text-[#68758a] text-[11px]">
                        <th className="py-2 px-2">Symbol</th>
                        <th className="py-2 px-2">Name</th>
                        <th className="py-2 px-2">Cap</th>
                        <th className="py-2 px-2 text-right">TargetAdd</th>
                        <th className="py-2 px-2 text-right">ProjectedWt</th>
                        <th className="py-2 px-2 text-right">RefPrice</th>
                        <th className="py-2 px-2 text-right">Tranche 1</th>
                        <th className="py-2 px-2 text-right">Tranche 2</th>
                        <th className="py-2 px-2 text-right">Tranche 3</th>
                        <th className="py-2 px-2 text-right">Tranche 4</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {DEPLOYMENT_TARGETS.map((t) => (
                        <tr
                          key={t.symbol}
                          onClick={() => {
                            setSizerSymbol(t.symbol);
                            setSizerPrice(t.refPrice);
                          }}
                          className={`hover:bg-slate-50 cursor-pointer ${sizerSymbol === t.symbol ? 'bg-emerald-50/50' : ''}`}
                        >
                          <td className="py-2 px-2 font-bold text-[#17253b]">{t.symbol}</td>
                          <td className="py-2 px-2 truncate max-w-[140px]">{t.name}</td>
                          <td className="py-2 px-2">{t.cap}</td>
                          <td className="py-2 px-2 text-right font-bold text-[#18866b]">+{fmtINR(t.targetAdd)}</td>
                          <td className="py-2 px-2 text-right font-bold">{t.postWeight}%</td>
                          <td className="py-2 px-2 text-right">{fmtINR(t.refPrice, 2)}</td>
                          <td className="py-2 px-2 text-right">{t.t1 > 0 ? fmtINR(t.t1) : '—'}</td>
                          <td className="py-2 px-2 text-right">{t.t2 > 0 ? fmtINR(t.t2) : '—'}</td>
                          <td className="py-2 px-2 text-right">{t.t3 > 0 ? fmtINR(t.t3) : '—'}</td>
                          <td className="py-2 px-2 text-right">{t.t4 > 0 ? fmtINR(t.t4) : '—'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* ==================== PAGE 3: STOCKS ==================== */}
          {activePage === 'Stocks' && (
            <div className="space-y-5">
              <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs flex flex-wrap items-center justify-between gap-4">
                <div>
                  <div className="text-[11px] font-bold text-[#68758a] uppercase">Stock lifecycle folder (`stocks/`)</div>
                  <div className="flex flex-wrap gap-1.5 mt-1">
                    {['Active', 'Watchlist', 'Archive', 'All'].map((f) => (
                      <button
                        key={f}
                        onClick={() => setStockFolderFilter(f)}
                        className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
                          stockFolderFilter === f ? 'bg-[#17253b] text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
                        }`}
                      >
                        {f}
                      </button>
                    ))}
                  </div>
                </div>

                <div className="w-full sm:w-72">
                  <label className="text-[11px] font-bold text-[#68758a] uppercase block mb-1">Select stock</label>
                  <select
                    value={selectedStockSymbol}
                    onChange={(e) => setSelectedStockSymbol(e.target.value)}
                    className="w-full border border-slate-300 rounded-xl px-3 py-2 text-xs font-bold bg-white"
                  >
                    {stockDropdownOptions.map((o) => (
                      <option key={o.symbol} value={o.symbol}>
                        {o.symbol} — {o.name} ({o.folder}/)
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* 3 Stock KPIs */}
              <div className="grid grid-cols-3 gap-3">
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-xs text-[#68758a]">Open quantity</div>
                  <div className="text-xl font-extrabold text-[#17253b] mt-1">
                    {currentStockDetail.type === 'active' ? `${currentStockDetail.qty} sh` : '0 sh'}
                  </div>
                </div>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-xs text-[#68758a]">Market value</div>
                  <div className="text-xl font-extrabold text-[#17253b] mt-1">
                    {currentStockDetail.type === 'active' ? fmtINR(currentStockDetail.marketValue, 2) : '—'}
                  </div>
                </div>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-xs text-[#68758a]">Portfolio weight</div>
                  <div className="text-xl font-extrabold text-[#17253b] mt-1">
                    {currentStockDetail.type === 'active' ? `${currentStockDetail.weightPct.toFixed(1)}%` : '0.0%'}
                  </div>
                </div>
              </div>

              {/* Research / P&L Tabs */}
              <div className="bg-white rounded-2xl border border-[#e7ebf1] shadow-xs overflow-hidden p-5 space-y-4">
                <div className="border-b border-slate-200 pb-3 font-extrabold text-[#17253b] text-sm">
                  Research Record for `{selectedStockSymbol}` ({currentStockDetail.folder}/)
                </div>
                <div className="text-xs leading-relaxed space-y-3">
                  <div className="p-3 rounded-xl bg-slate-50 border border-slate-200">
                    <strong>Investment Snapshot:</strong> {currentStockDetail.snapshot || 'Initialized from FIFO ledger.'}
                  </div>
                  <div className="p-3 rounded-xl bg-emerald-50 border border-emerald-200">
                    <strong>Argon Action:</strong> {currentStockDetail.argonAction || 'HOLD'}
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* ==================== PAGE 4: ACTIVITY ==================== */}
          {activePage === 'Activity' && (
            <div className="space-y-5">
              <div className="grid grid-cols-3 gap-4">
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-xs text-[#68758a]">Gross purchases</div>
                  <div className="text-xl font-extrabold text-[#17253b] mt-1">{fmtCompactINR(summary.grossBuys)}</div>
                </div>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-xs text-[#68758a]">Gross sale proceeds</div>
                  <div className="text-xl font-extrabold text-[#17253b] mt-1">{fmtCompactINR(summary.grossSales)}</div>
                </div>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs">
                  <div className="text-xs text-[#68758a]">Net trade cash deployed</div>
                  <div className="text-xl font-extrabold text-[#17253b] mt-1">{fmtCompactINR(summary.netDeployed)}</div>
                </div>
              </div>

              <div className="bg-white rounded-2xl border border-[#e7ebf1] shadow-xs p-5 space-y-4">
                <div className="flex gap-4 border-b border-slate-200 pb-2 text-xs font-bold">
                  {['Performance', 'Behaviour', 'Journey'].map((t) => (
                    <button
                      key={t}
                      onClick={() => setActivitySubTab(t)}
                      className={activitySubTab === t ? 'text-[#c54e5e] border-b-2 border-[#c54e5e] pb-1' : 'text-slate-500'}
                    >
                      {t}
                    </button>
                  ))}
                </div>

                {activitySubTab === 'Performance' && (
                  <div className="space-y-4 text-xs">
                    <div className="font-bold text-[#17253b]">Verified realised P&amp;L by sell year:</div>
                    <div className="space-y-2">
                      {REALISED_BY_YEAR.map((yr) => (
                        <div key={yr.year} className="flex justify-between p-2 rounded bg-slate-50">
                          <span className="font-bold">{yr.year}</span>
                          <span className={yr.pnl >= 0 ? 'text-[#18866b] font-bold' : 'text-[#c54e5e] font-bold'}>
                            {fmtINR(yr.pnl, 2)} ({yr.sells} sells)
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                {activitySubTab === 'Behaviour' && (
                  <div className="text-xs text-slate-700 space-y-2">
                    <p>Average holding period of matched sell rows: <strong>{summary.avgHoldDays} days</strong>.</p>
                    <p>Total recorded trades: <strong>{summary.txCount} broker trades</strong> across {summary.uniqueStocks} active stocks.</p>
                  </div>
                )}
                { (
                  <div className="space-y-3 text-xs">
                    {JOURNEY_MILESTONES.map((m, idx) => (
                      <div key={idx} className="p-2.5 rounded bg-slate-50 border border-slate-200">
                        <strong>{m.date}:</strong> {m.title} — {m.detail}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}

          {/* ==================== PAGE 5: BENCHMARKS ==================== */}
          {activePage === 'Benchmarks' && (() => {
            const bData = BENCHMARK_OWNER_CURVES[selectedOwner] || BENCHMARK_OWNER_CURVES.All;
            return (
              <div className="space-y-5">
                <div className="p-4 rounded-xl bg-blue-50 border border-blue-200 text-xs">
                  <strong>Dynamic Rebasing Active:</strong> All series below start at <strong>100.0 on {bData.startDate}</strong> (first trade date for {summary.label}).
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                  <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs text-xs">
                    <div className="text-slate-500">Nifty 50 (price index)</div>
                    <div className="text-xl font-extrabold text-[#294b6a] mt-1">{fmtPct(bData.nifty50Ret, 1)}</div>
                  </div>
                  <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1] shadow-xs text-xs">
                    <div className="text-slate-500">Nifty 500 (price index)</div>
                    <div className="text-xl font-extrabold text-[#18866b] mt-1">{fmtPct(bData.nifty500Ret, 1)}</div>
                  </div>
                  <div className="bg-white p-4 rounded-2xl border-2 border-amber-500/60 shadow-xs text-xs">
                    <div className="font-bold text-amber-800">Family Portfolio Index</div>
                    <div className="text-xl font-extrabold text-amber-600 mt-1">{fmtPct(bData.portRet, 1)}</div>
                  </div>
                </div>
              </div>
            );
          })()}

          {/* ==================== PAGE 6: DATA HEALTH ==================== */}
          {activePage === 'Data Health' && (
            <div className="space-y-5">
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 text-xs">
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1]">
                  <div className="text-slate-500">Transactions</div>
                  <div className="text-xl font-extrabold mt-1">663</div>
                </div>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1]">
                  <div className="text-slate-500">Invalid Dates</div>
                  <div className="text-xl font-extrabold text-emerald-600 mt-1">0</div>
                </div>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1]">
                  <div className="text-slate-500">Unmatched Sells</div>
                  <div className="text-xl font-extrabold text-amber-600 mt-1">1 (SONACOMS)</div>
                </div>
                <div className="bg-white p-4 rounded-2xl border border-[#e7ebf1]">
                  <div className="text-slate-500">Priced Positions</div>
                  <div className="text-xl font-extrabold text-emerald-600 mt-1">34/34</div>
                </div>
              </div>

              <div className="bg-white p-5 rounded-2xl border border-[#e7ebf1] text-xs space-y-3">
                <h3 className="font-bold text-sm text-[#17253b]">Open Issues &amp; Reconciliation</h3>
                <div className="p-3 rounded-xl bg-amber-50 border border-amber-200 text-amber-900">
                  <strong>SONACOMS Unmatched Sell:</strong> Mummy sold 89 shares on 25 Feb 2026 (Trade ID 10142200), but ledger has 8 fewer FIFO shares due to an untagged Haider split on an earlier buy. Tagging that row in P_L_Statement.csv resolves this.
                </div>
              </div>
            </div>
          )}
          </main>

          {/* ==================== Z FOLD 2 UNFOLDED (884px) PERSISTENT RIGHT-HAND MASTER-DETAIL PANE ==================== */}
          {isFoldUnfolded && (
            <aside className="w-[44%] h-full bg-white overflow-y-auto p-4 space-y-4">
              <div className="flex items-center justify-between border-b border-slate-200 pb-2.5">
                <div>
                  <span className="text-[10px] font-extrabold uppercase tracking-wider text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded">
                    📖 Z Fold 2 Split-Pane Inspector
                  </span>
                  <h3 className="text-base font-extrabold text-[#17253b] mt-1">
                    {pinnedStockObj.symbol} · {pinnedStockObj.name}
                  </h3>
                </div>
                <div className="text-right">
                  <div className="text-sm font-extrabold text-[#17253b]">{fmtINR(pinnedStockObj.cmp, 2)}</div>
                  <div className={`text-[11px] font-bold ${pinnedStockObj.unrealisedPct >= 0 ? 'text-[#18866b]' : 'text-[#c54e5e]'}`}>
                    {fmtPct(pinnedStockObj.unrealisedPct, 1)}
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-3 gap-2 text-xs">
                <div className="p-2.5 rounded-xl bg-slate-50 border border-slate-200">
                  <div className="text-[10px] text-slate-500">FIFO Qty</div>
                  <div className="font-extrabold text-[#17253b] mt-0.5">{pinnedStockObj.qty} sh</div>
                </div>
                <div className="p-2.5 rounded-xl bg-slate-50 border border-slate-200">
                  <div className="text-[10px] text-slate-500">Market Value</div>
                  <div className="font-extrabold text-[#17253b] mt-0.5">{fmtCompactINR(pinnedStockObj.marketValue)}</div>
                </div>
                <div className="p-2.5 rounded-xl bg-slate-50 border border-slate-200">
                  <div className="text-[10px] text-slate-500">Weight</div>
                  <div className="font-extrabold text-[#17253b] mt-0.5">{pinnedStockObj.weightPct.toFixed(2)}%</div>
                </div>
              </div>

              <div className="p-3 rounded-xl bg-emerald-50/70 border border-emerald-200 text-xs space-y-1">
                <div className="text-[10px] font-bold uppercase text-emerald-800">Argon Action &amp; Trigger Zone</div>
                <div className="font-extrabold text-[#17253b]">{pinnedStockObj.argonAction}</div>
                <div className="text-emerald-950 text-[11px]">{pinnedStockObj.watchZone}</div>
              </div>

              {/* Open FIFO Buy-Lot Price Ladder vs Current Price */}
              <div className="space-y-2">
                <div className="text-xs font-bold text-[#17253b]">
                  Open FIFO Buy-Lot Entry Ladder vs. CMP ({fmtINR(pinnedStockObj.cmp, 1)})
                </div>
                <div className="space-y-1.5">
                  {pinnedStockObj.fifoLots.map((lot, idx) => {
                    const ret = ((pinnedStockObj.cmp / lot.buyPrice - 1) * 100);
                    const maxP = Math.max(pinnedStockObj.cmp, ...pinnedStockObj.fifoLots.map((l) => l.buyPrice)) * 1.1;
                    const barW = Math.min(100, Math.max(12, (lot.buyPrice / maxP) * 100));
                    return (
                      <div key={idx} className="text-[11px] space-y-0.5">
                        <div className="flex justify-between text-slate-700 font-medium">
                          <span>{lot.label} ({lot.qty} sh)</span>
                          <span className={`font-bold ${ret >= 0 ? 'text-[#18866b]' : 'text-[#c54e5e]'}`}>
                            Buy ₹{lot.buyPrice.toFixed(1)} ({fmtPct(ret, 1)})
                          </span>
                        </div>
                        <div className="w-full h-2 bg-slate-100 rounded-full overflow-hidden">
                          <div
                            style={{ width: `${barW}%` }}
                            className={`h-full rounded-full ${ret >= 0 ? 'bg-[#18866b]' : 'bg-[#c54e5e]'}`}
                          />
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              <div className="space-y-1.5 text-xs">
                <div className="font-bold text-[#17253b]">1-Minute Investment Snapshot</div>
                <p className="text-slate-700 leading-relaxed bg-slate-50 p-3 rounded-xl border border-slate-200 text-[11px]">
                  {pinnedStockObj.snapshot}
                </p>
                <p className="text-rose-900 bg-rose-50/70 p-2.5 rounded-xl border border-rose-200 text-[11px]">
                  <strong>Key Risks:</strong> {pinnedStockObj.risks}
                </p>
              </div>
            </aside>
          )}
        </div>

        {/* ==================== MOBILE BOTTOM APP BAR ==================== */}
        {isNarrowViewport && (
          <nav className="bg-white border-t border-slate-200 px-1.5 py-2 flex items-center justify-around sticky bottom-0 z-30 shadow-lg">
            {[
              { id: 'Portfolio', label: 'Portfolio', icon: Briefcase },
              { id: 'Recommendations', label: '₹15L Plan', icon: Compass },
              { id: 'Stocks', label: 'Stocks', icon: BookOpen },
              { id: 'Activity', label: 'Activity', icon: Activity },
              { id: 'Benchmarks', label: 'Bench', icon: TrendingUp },
              { id: 'Data Health', label: 'Health', icon: Database }
            ].map((nav) => {
              const active = activePage === nav.id;
              return (
                <button
                  key={nav.id}
                  onClick={() => setActivePage(nav.id)}
                  className={`flex flex-col items-center gap-0.5 px-2 py-1 rounded-xl text-[10px] font-bold transition-all ${
                    active ? 'text-[#18866b] bg-emerald-50' : 'text-slate-500'
                  }`}
                >
                  <span>{nav.label}</span>
                </button>
              );
            })}
          </nav>
        )}

        {/* ==================== SLIDE-OVER STOCK RESEARCH DRAWER ==================== */}
        {drawerStock && (
          <div className="fixed inset-0 z-50 bg-slate-950/60 backdrop-blur-xs flex justify-end">
            <div className="bg-white w-full max-w-lg h-full shadow-2xl border-l border-slate-200 flex flex-col justify-between overflow-y-auto p-5 space-y-5">
              <div className="space-y-4">
                <div className="flex items-start justify-between border-b border-slate-200 pb-3">
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="text-lg font-extrabold text-[#17253b]">{drawerStock.symbol}</span>
                      <span className="text-xs font-bold px-2 py-0.5 rounded bg-slate-100 text-slate-700">{drawerStock.cap} Cap</span>
                    </div>
                    <div className="text-xs text-[#68758a] mt-0.5">{drawerStock.name}</div>
                  </div>
                  <button onClick={() => setDrawerStock(null)} className="p-1.5 rounded-lg bg-slate-100 text-slate-700">
                    <X className="w-4 h-4" />
                  </button>
                </div>

                <div className="p-3.5 rounded-xl bg-emerald-50/70 border border-emerald-200 space-y-1 text-xs">
                  <div className="text-[11px] font-bold uppercase text-emerald-800">Argon Action &amp; Watch Zone</div>
                  <div className="font-extrabold text-[#17253b]">{drawerStock.argonAction}</div>
                  <div className="text-emerald-950"><strong>Trigger:</strong> {drawerStock.watchZone}</div>
                </div>

                <div className="space-y-2 text-xs">
                  <h4 className="font-bold uppercase tracking-wider text-[#68758a]">Investment Snapshot</h4>
                  <p className="text-slate-700 leading-relaxed bg-slate-50 p-3 rounded-xl border border-slate-200">{drawerStock.snapshot}</p>
                </div>
              </div>

              <div className="pt-3 border-t border-slate-200 flex gap-2">
                <button
                  onClick={() => {
                    const sym = drawerStock.symbol;
                    setDrawerStock(null);
                    openStockInPageOrDrawer(sym, true);
                  }}
                  className="flex-1 py-2.5 px-4 rounded-xl bg-[#17253b] text-white font-bold text-xs"
                >
                  Open Full Stock Page →
                </button>
                <button onClick={() => setDrawerStock(null)} className="py-2.5 px-4 rounded-xl border border-slate-300 text-slate-700 font-bold text-xs">
                  Close
                </button>
              </div>
            </div>
          </div>
        )}

        {/* ==================== QUICK DECISION MODAL ==================== */}
        {decisionModalOpen && (
          <div className="fixed inset-0 z-50 bg-slate-950/60 backdrop-blur-xs flex items-center justify-center p-4">
            <div className="bg-white w-full max-w-lg rounded-2xl shadow-2xl border border-slate-200 p-5 space-y-4">
              <div className="flex items-center justify-between border-b border-slate-200 pb-3">
                <h3 className="text-sm font-extrabold text-[#17253b]">➕ Record Confirmed Decision (SKILL.md)</h3>
                <button onClick={() => setDecisionModalOpen(false)} className="p-1 rounded-lg bg-slate-100 text-slate-600"><X className="w-4 h-4" /></button>
              </div>

              <div className="space-y-3 text-xs">
                <div>
                  <label className="font-bold text-slate-700 block mb-1">Stock Symbol</label>
                  <input type="text" value={decisionSym} onChange={(e) => setDecisionSym(e.target.value.toUpperCase())} className="w-full border border-slate-300 rounded-xl px-3 py-2 font-bold" />
                </div>
                <div>
                  <label className="font-bold text-slate-700 block mb-1">Action</label>
                  <input type="text" value={decisionAct} onChange={(e) => setDecisionAct(e.target.value)} className="w-full border border-slate-300 rounded-xl px-3 py-2 font-semibold" />
                </div>
                <div>
                  <label className="font-bold text-slate-700 block mb-1">Details</label>
                  <input type="text" value={decisionDetails} onChange={(e) => setDecisionDetails(e.target.value)} className="w-full border border-slate-300 rounded-xl px-3 py-2" />
                </div>
                <div>
                  <label className="font-bold text-slate-700 block mb-1">Rationale</label>
                  <textarea rows={2} value={decisionWhy} onChange={(e) => setDecisionWhy(e.target.value)} className="w-full border border-slate-300 rounded-xl px-3 py-2" />
                </div>
              </div>

              <div className="flex justify-end gap-2 pt-2">
                <button onClick={() => setDecisionModalOpen(false)} className="px-4 py-2 rounded-xl bg-slate-900 text-white font-bold text-xs">Done</button>
              </div>
            </div>
          </div>
        )}

        {/* ==================== ZERO-LAPTOP PHONE DEPLOYMENT GUIDE MODAL ==================== */}
        {deployGuideModalOpen && (
          <div className="fixed inset-0 z-50 bg-slate-950/70 backdrop-blur-xs flex items-center justify-center p-4">
            <div className="bg-white w-full max-w-2xl rounded-2xl shadow-2xl border border-slate-200 p-5 space-y-4 max-h-[88vh] overflow-y-auto">
              <div className="flex items-center justify-between border-b border-slate-200 pb-3">
                <div>
                  <h3 className="text-base font-extrabold text-[#17253b]">☁️ How to Use This on Your Samsung Galaxy Z Fold 2 (Zero Laptop Needed)</h3>
                  <p className="text-xs text-[#68758a]">100% Free Cloud Hosting + Automated Daily Yahoo Price Sync via GitHub Actions</p>
                </div>
                <button onClick={() => setDeployGuideModalOpen(false)} className="p-1.5 rounded-lg bg-slate-100 text-slate-600"><X className="w-4 h-4" /></button>
              </div>

              <div className="space-y-3 text-xs leading-relaxed text-slate-700">
                <div className="p-3.5 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-950">
                  <strong>How It Works Without Your Laptop:</strong> Your repository lives on a <strong>free private GitHub repo</strong>. Every weekday at <strong>4:00 PM IST</strong> (after NSE market close), GitHub’s cloud servers automatically run <code>.github/workflows/daily_portfolio_sync.yml</code> to fetch fresh Yahoo prices, run your Python FIFO engine, and update your phone app automatically.
                </div>

                <ol className="list-decimal pl-5 space-y-2">
                  <li>
                    <strong>Push Project to a Free Private GitHub Repo:</strong> Upload this project folder (including <code>Family_Investment_Dashboard/</code>, <code>stocks/</code>, <code>tools/</code>, and <code>.github/workflows/daily_portfolio_sync.yml</code>) to a private repo on GitHub.
                  </li>
                  <li>
                    <strong>Option A — Deploy Streamlit Dashboard (5 Minutes, Free):</strong> Go to <code>share.streamlit.io</code>, connect your private GitHub repo, set main file to <code>Family_Investment_Dashboard/dashboard.py</code>, and add your Google email under <em>Settings → Sharing</em>.
                  </li>
                  <li>
                    <strong>Option B — Deploy React PWA on Cloudflare Pages (Instant &lt;50ms Load, Never Sleeps):</strong> Connect your GitHub repo to <strong>Cloudflare Pages</strong> (free) with Cloudflare Zero Trust Google login.
                  </li>
                  <li>
                    <strong>Install on Samsung Galaxy Z Fold 2 Home Screen:</strong> Open your URL in <strong>Chrome or Samsung Internet</strong> on your Z Fold 2 → tap <strong>Menu (⋮) → Add to Home Screen (Install App)</strong>.
                    <ul className="list-disc pl-5 mt-1 text-[11px] text-slate-600">
                      <li><strong>Folded Cover Screen (344px):</strong> Automatically renders the 2×2 KPI grid, swipeable stock cards, and bottom thumb navigation bar.</li>
                      <li><strong>Unfolded Main Screen (884px):</strong> Automatically unlocks the side-by-side Split-Pane Inspector and 2D Proportional Sector Treemap.</li>
                    </ul>
                  </li>
                </ol>
              </div>

              <div className="flex justify-end pt-2 border-t border-slate-200">
                <button onClick={() => setDeployGuideModalOpen(false)} className="px-4 py-2 rounded-xl bg-[#17253b] text-white font-bold text-xs">Got It</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}