/* Tuo — Interactive Simulator v3 (§5.6b)
   Daily granularity (1,744 points). Withdrawal redesigned: free-form amount + %/$ unit
   + frequency (month/quarter/semester/year). Bug-fixed: previous version applied a per-week
   rate over a per-day loop, draining ~84%/yr instead of the intended 12%/yr for "1%/mo".
*/

function Dashboard() {
  const en = useLang() === 'en';
  const d = window.TUO_PERF_DATA;
  const [product, setProduct] = useState('core');
  const [window_, setWindow_] = useState('5Y');
  const [capital, setCapital] = useState(100000);
  const [benchmark, setBenchmark] = useState('btc');

  // ── Withdrawal: mode + amount + unit + frequency ──
  // mode:   'compound' | 'periodic' | 'harvest'
  // amount: numeric (interpreted per `unit`)
  // unit:   'pct' (percent of current NAV)  |  'usd' (fixed dollar amount)
  // freq:   'month' | 'quarter' | 'semester' | 'year'  (the period the rate applies to)
  const [wdMode, setWdMode] = useState('compound');
  const [wdAmount, setWdAmount] = useState(1);
  const [wdUnit, setWdUnit] = useState('pct');
  const [wdFreq, setWdFreq] = useState('month');

  // ── Data is DAILY (perf-data.js migration: weekly aliases now hold daily arrays) ──
  const allLabels = d.weeks; // daily ISO dates
  const lastDate = new Date(allLabels[allLabels.length - 1] + 'T00:00:00Z');
  let startIdx = 0;
  if (window_ === '3Y') {
    const cut = new Date(lastDate); cut.setUTCFullYear(cut.getUTCFullYear() - 3);
    startIdx = allLabels.findIndex(dt => new Date(dt + 'T00:00:00Z') >= cut);
  } else if (window_ === '1Y') {
    const cut = new Date(lastDate); cut.setUTCFullYear(cut.getUTCFullYear() - 1);
    startIdx = allLabels.findIndex(dt => new Date(dt + 'T00:00:00Z') >= cut);
  } else if (window_ === 'YTD') {
    const yr = lastDate.getUTCFullYear();
    startIdx = allLabels.findIndex(dt => dt.startsWith(yr + '-'));
  }
  if (startIdx < 0) startIdx = 0;
  const labels = allLabels.slice(startIdx);

  const rawNav = product === 'core' ? d.bpCoreWeekly
                : product === 'bullish' ? d.bpBullishWeekly
                : (d.dynHedgeWeekly || d.bpCoreWeekly);
  const navSlice = rawNav.slice(startIdx);
  const scale = capital / navSlice[0];

  // ── Withdrawal math (FIXED) ──
  // The loop iterates DAILY (1 step = 1 calendar day). Convert the user's period-rate
  // into a per-day deduction. This is the bug fix: the previous version divided by
  // WEEKS_PER_MONTH (4.33) but the loop ran daily — so "1%/mo" was applied as
  // 0.231% per DAY = ~84%/yr drain. Now we divide by actual days per period.
  const DAYS_PER_PERIOD = {
    month: 365.25 / 12,    // 30.44
    quarter: 365.25 / 4,   // 91.31
    semester: 365.25 / 2,  // 182.62
    year: 365.25,
  };
  const daysPerPeriod = DAYS_PER_PERIOD[wdFreq] || DAYS_PER_PERIOD.month;

  let nav = navSlice.map(v => v * scale);
  let totalWithdrawn = 0;
  if (wdMode !== 'compound') {
    const newNav = [nav[0]];
    let tw = 0;
    for (let i = 1; i < nav.length; i++) {
      let current = newNav[i - 1] * (navSlice[i] / navSlice[i - 1]);
      let w = 0;
      if (wdMode === 'periodic') {
        if (wdUnit === 'pct') {
          // % per period → applied as continuous per-day fraction of current NAV
          w = current * (wdAmount / 100) / daysPerPeriod;
        } else {
          // $ per period → applied as fixed daily dollar amount
          w = wdAmount / daysPerPeriod;
        }
      } else if (wdMode === 'harvest' && current > capital) {
        w = current - capital;
      }
      current -= w;
      if (current < 0) current = 0;
      tw += w;
      newNav.push(current);
    }
    nav = newNav;
    totalWithdrawn = tw;
  }

  // ── Benchmark ──
  let benchData = null, benchName = '';
  if (benchmark === 'btc') {
    const bSlice = d.btcHodlWeekly.slice(startIdx);
    benchData = bSlice.map(v => v * (capital / bSlice[0]));
    benchName = 'BTC HODL';
  } else if (benchmark === 'usdc5') {
    // Daily compounding factor for 5% APR
    benchData = labels.map((_, i) => capital * Math.pow(1.05, i / 365.25));
    benchName = 'USDC 5%';
  }

  // ── KPIs (FIXED — uses daily, not weekly, units) ──
  const finalNav = nav[nav.length - 1];
  const years = labels.length / 365.25;
  const cagr = years > 0.05
    ? (Math.pow(finalNav / capital, 1 / years) - 1) * 100
    : (finalNav / capital - 1) * 100; // for very short windows, show period return
  let maxDD = 0, peak = nav[0];
  nav.forEach(v => { if (v > peak) peak = v; const dd = (peak - v) / peak; if (dd > maxDD) maxDD = dd; });
  const totalClient = finalNav + totalWithdrawn;
  const dailyRets = [];
  for (let i = 1; i < nav.length; i++) dailyRets.push(nav[i] / nav[i - 1] - 1);
  const avgR = dailyRets.length ? dailyRets.reduce((a, b) => a + b, 0) / dailyRets.length : 0;
  const stdR = dailyRets.length ? Math.sqrt(dailyRets.reduce((a, b) => a + (b - avgR) ** 2, 0) / dailyRets.length) : 0;
  // Sharpe-like, annualized from daily returns (calendar-day basis, matches our resample)
  const sharpe = stdR > 0 ? (avgR / stdR) * Math.sqrt(365.25) : 0;

  const prodNames = { core: 'BP Core', bullish: 'BP Bullish', dynhedge: 'Dynamic Hedge' };
  const chartSeries = [{ name: prodNames[product] || 'BP Core', data: nav.map(Math.round) }];
  const colorMap = { core: '#3ecf8e', bullish: '#f5a524', dynhedge: '#7c8bff' };
  const chartColors = [colorMap[product] || '#3ecf8e'];
  if (benchData) {
    chartSeries.push({ name: benchName, data: benchData.map(Math.round) });
    chartColors.push(benchmark === 'btc' ? '#f7931a' : '#898989');
  }
  const chartEvents = d.events.filter(e => labels.includes(e.date));

  // Combined key fragment for invalidating StatTile animations on any input change
  const wdKey = wdMode === 'periodic' ? `${wdMode}-${wdAmount}-${wdUnit}-${wdFreq}` : wdMode;
  const keyBase = `${product}-${window_}-${capital}-${wdKey}-${benchmark}`;

  const ss = { background: '#0f0f0f', color: '#fafafa', border: '1px solid #2e2e2e', borderRadius: 6, padding: '6px 10px', fontSize: 13, fontFamily: 'inherit' };
  const ctrl = (label, ch) => React.createElement('div', { className: 'dash-ctrl' }, React.createElement('label', null, label), ch);

  // Frequency dropdown options (bilingual)
  const freqOptions = en
    ? [['month', 'month'], ['quarter', 'quarter'], ['semester', 'semester'], ['year', 'year']]
    : [['month', 'mes'], ['quarter', 'trimestre'], ['semester', 'semestre'], ['year', 'año']];

  return React.createElement(Section, { id: 'simulator', 'data-section': 'simulator' },
    React.createElement(Reveal, null,
      React.createElement('h2', null, en ? 'Run your own scenario' : 'Corre tu propio escenario'),
      React.createElement('p', null, en
        ? 'Pick a strategy. Pick a starting capital. Pick how you would have used it. The chart and the metrics update live, against a Bitcoin HODL benchmark.'
        : 'Elige una estrategia. Elige capital inicial. Elige cómo lo habrías usado. La gráfica y las métricas se actualizan en vivo, contra un benchmark de Bitcoin HODL.')
    ),
    // Main row: Strategy / Window / Initial capital / Use of capital / Compare against
    React.createElement('div', { className: 'dash-controls' },
      ctrl(en ? 'Strategy' : 'Estrategia',
        React.createElement('select', { style: ss, value: product, onChange: e => setProduct(e.target.value) },
          React.createElement('option', { value: 'core' }, 'BP Core'),
          React.createElement('option', { value: 'bullish' }, 'BP Bullish'),
          React.createElement('option', { value: 'dynhedge' }, 'Dynamic Hedge'))),
      ctrl(en ? 'Window' : 'Ventana',
        React.createElement('div', { className: 'dash-pills' },
          ['5Y', '3Y', '1Y', 'YTD'].map(w => React.createElement('button', {
            key: w, type: 'button', className: 'dash-pill' + (window_ === w ? ' active' : ''),
            onClick: () => setWindow_(w)
          }, w)))),
      ctrl(en ? 'Initial capital' : 'Capital inicial',
        React.createElement('input', { type: 'number', min: 1000, step: 1000, style: { ...ss, width: 110 }, value: capital, onChange: e => setCapital(Math.max(0, Number(e.target.value) || 0)) })),
      ctrl(en ? 'Use of capital' : 'Uso del capital',
        React.createElement('select', { style: ss, value: wdMode, onChange: e => setWdMode(e.target.value) },
          React.createElement('option', { value: 'compound' }, en ? 'Compound' : 'Compound'),
          React.createElement('option', { value: 'periodic' }, en ? 'Withdraw' : 'Retirar'),
          React.createElement('option', { value: 'harvest' }, en ? 'Profit harvest' : 'Cosecha de ganancia'))),
      ctrl(en ? 'Compare against' : 'Comparar contra',
        React.createElement('select', { style: ss, value: benchmark, onChange: e => setBenchmark(e.target.value) },
          React.createElement('option', { value: 'btc' }, 'BTC HODL'),
          React.createElement('option', { value: 'usdc5' }, 'USDC Lending 5%'),
          React.createElement('option', { value: 'none' }, en ? 'None' : 'Ninguno')))
    ),

    // Sub-row (only when "Withdraw" is selected): amount + unit toggle + frequency
    wdMode === 'periodic' && React.createElement('div', { className: 'dash-controls dash-controls-sub' },
      ctrl(en ? 'Amount' : 'Monto',
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
          wdUnit === 'usd' && React.createElement('span', { style: { color: '#898989', fontFamily: 'Source Code Pro, monospace' } }, '$'),
          React.createElement('input', {
            type: 'number', min: 0, step: wdUnit === 'pct' ? 0.1 : 50, value: wdAmount,
            onChange: e => setWdAmount(Math.max(0, Number(e.target.value) || 0)),
            style: { ...ss, width: 90 }
          }),
          wdUnit === 'pct' && React.createElement('span', { style: { color: '#898989', fontFamily: 'Source Code Pro, monospace' } }, '%')
        )),
      ctrl(en ? 'Unit' : 'Unidad',
        React.createElement('div', { className: 'dash-pills' },
          [['pct', '%'], ['usd', '$']].map(([u, lbl]) => React.createElement('button', {
            key: u, type: 'button', className: 'dash-pill' + (wdUnit === u ? ' active' : ''),
            onClick: () => setWdUnit(u)
          }, lbl)))),
      ctrl(en ? 'Per' : 'Por',
        React.createElement('select', { style: ss, value: wdFreq, onChange: e => setWdFreq(e.target.value) },
          freqOptions.map(([val, lbl]) => React.createElement('option', { key: val, value: val }, lbl))))
    ),

    React.createElement(EquityChart, { series: chartSeries, labels: labels, colors: chartColors, events: chartEvents }),

    // KPIs — uniform-width grid (3 cols compound, 5 cols when withdrawing).
    // Removed Sharpe (technical jargon, not actionable for retail/HNW). Kept the metrics
    // that answer the prospect's actual questions: "what return", "worst dip", "final amount".
    React.createElement('div', { className: 'dash-kpis dash-kpis-grid' + (wdMode !== 'compound' ? ' has-withdrawal' : '') },
      React.createElement(StatTile, {
        key: `cagr-${keyBase}`,
        value: Number(cagr.toFixed(1)),
        prefix: cagr >= 0 ? '+' : '', suffix: '%', startFrom: 0, decimals: 1,
        label: en ? (years > 0.05 ? 'Net CAGR' : 'Period return') : (years > 0.05 ? 'CAGR neto' : 'Retorno período')
      }),
      React.createElement(StatTile, {
        key: `dd-${keyBase}`,
        value: Number((maxDD * 100).toFixed(2)), suffix: '%', startFrom: 0, decimals: 2,
        label: en ? 'Max Drawdown' : 'Drawdown máx.'
      }),
      React.createElement(StatTile, {
        key: `nav-${keyBase}`,
        value: Math.round(finalNav), prefix: '$', startFrom: capital,
        label: en ? 'Final NAV' : 'NAV final'
      }),
      wdMode !== 'compound' && React.createElement(StatTile, {
        key: `tw-${keyBase}`,
        value: Math.round(totalWithdrawn), prefix: '$', startFrom: 0,
        label: en ? 'Total withdrawn' : 'Total retirado'
      }),
      wdMode !== 'compound' && React.createElement(StatTile, {
        key: `tc-${keyBase}`,
        value: Math.round(totalClient), prefix: '$', startFrom: capital,
        label: en ? 'Total client value' : 'Valor total cliente'
      })
    ),

    // Mandatory disclaimer microcopy
    React.createElement('div', { className: 'dash-disclaimer-card' },
      React.createElement('div', { className: 'dash-disclaimer-icon' }, 'i'),
      React.createElement('div', { className: 'dash-disclaimer-body' },
        React.createElement('p', { className: 'dash-disclaimer-title' }, en
          ? 'Hypothetical results · backtest 2021–2026'
          : 'Resultados hipotéticos · backtest 2021–2026'),
        React.createElement('p', { className: 'dash-disclaimer-text' }, en
          ? 'Past performance does not guarantee future results. This simulator is not investment advice.'
          : 'El desempeño pasado no garantiza resultados futuros. Este simulador no constituye asesoramiento de inversión.'),
        React.createElement('a', { className: 'dash-disclaimer-link', href: 'https://docs.tuo.app/methodology' },
          en ? 'How we computed this →' : 'Cómo calculamos esto →')))
  );
}

Object.assign(window, { Dashboard });
