// FIRE Tracker — independence timeline detail screen

/* ── helpers ─────────────────────────────────────────────────────────────── */

function calcYearsToFire(pv, annualSavings, rateDecimal, target) {
  let fv = pv;
  for (let y = 1; y <= 60; y++) {
    fv = fv * (1 + rateDecimal) + annualSavings;
    if (fv >= target) return y;
  }
  return 60;
}

function calcMilestones(pv, annualSavings, rateDecimal, fireNumber, baseYear) {
  const milePcts = [0.25, 0.50, 0.75, 1.0];
  const targets  = milePcts.map(p => fireNumber * p);
  const hitYears = [null, null, null, null];
  let fv = pv;
  for (let y = 1; y <= 60; y++) {
    fv = fv * (1 + rateDecimal) + annualSavings;
    targets.forEach((t, i) => { if (hitYears[i] === null && fv >= t) hitYears[i] = y; });
    if (hitYears.every(v => v !== null)) break;
  }
  return milePcts.map((p, i) => ({
    pct:       p,
    label:     ['25%', '50%', '75%', 'FIRE'][i],
    year:      hitYears[i] ? String(baseYear + hitYears[i]) : '–',
    amount:    targets[i],
    highlight: i === 3,
  }));
}

/* ── FIRE info sheet ─────────────────────────────────────────────────────── */

function FireInfoSheet({ theme, accent, midnight, onClose }) {
  const sheetBg = midnight ? '#1B1F2E' : '#FFFFFF';

  const explainers = [
    {
      title: 'The idea',
      body:  'FIRE is about accumulating enough invested wealth that your portfolio\'s annual growth covers your living expenses, freeing you from needing to trade time for money.',
    },
    {
      title: 'The 4% rule',
      body:  'Research (the "Trinity Study") suggests you can safely withdraw 4% of your portfolio per year without running out of money over a 30+ year horizon. This is the standard starting point.',
    },
    {
      title: 'Your FIRE number',
      body:  'Annual expenses ÷ withdrawal rate. At 4%, that\'s 25× your annual spending. Lower your expenses or raise the rate and the target drops; higher spending or a more conservative rate raises it.',
    },
  ];

  const flavours = [
    { label: 'Lean FIRE',    desc: 'Minimal lifestyle. Lower target, earlier date.',           color: '#5B9BD5' },
    { label: 'Regular FIRE', desc: 'Comfortable lifestyle. The standard 25× approach.',        color: accent   },
    { label: 'Fat FIRE',     desc: 'High-spend retirement. Larger target, more time.',          color: '#8B6FBF' },
    { label: 'Barista FIRE', desc: 'Semi-retired. Part-time work covers extras, portfolio rests.', color: '#C68B4E' },
  ];

  return (
    <div style={{ position:'absolute', inset:0, zIndex:60, display:'flex', flexDirection:'column', justifyContent:'flex-end' }}>
      {/* backdrop */}
      <div
        onClick={onClose}
        style={{ position:'absolute', inset:0, background:'rgba(0,0,0,0.38)', backdropFilter:'blur(2px)', WebkitBackdropFilter:'blur(2px)' }}
      />

      {/* sheet */}
      <div style={{
        position:'relative', zIndex:1,
        background: sheetBg,
        borderRadius:'24px 24px 0 0',
        boxShadow:'0 -8px 40px rgba(0,0,0,0.18)',
        maxHeight:'84%',
        overflow:'hidden',
        display:'flex', flexDirection:'column',
      }}>
        {/* drag handle */}
        <div style={{ width:36, height:4, borderRadius:2, background: midnight ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.12)', margin:'10px auto 0', flexShrink:0 }} />

        {/* scrollable body */}
        <div style={{ overflowY:'auto', padding:'16px 20px 36px' }}>

          {/* title */}
          <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:22 }}>
            <div style={{ width:40, height:40, borderRadius:12, background:`${accent}18`, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
              <Ico.target size={20} stroke={accent} sw={1.7} />
            </div>
            <div>
              <div style={{ fontFamily:FONTS.display, fontSize:21, color:theme.text, letterSpacing:-0.4, lineHeight:1.1 }}>What is FIRE?</div>
              <div style={{ fontFamily:FONTS.mono, fontSize:10, color:theme.textMute, marginTop:3, letterSpacing:0.4 }}>FINANCIAL INDEPENDENCE · RETIRE EARLY</div>
            </div>
          </div>

          {/* explainer cards */}
          {explainers.map(s => (
            <div key={s.title} style={{ marginBottom:10, padding:'13px 14px', background: midnight ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)', borderRadius:13 }}>
              <div style={{ fontFamily:FONTS.ui, fontSize:13, fontWeight:600, color:theme.text, marginBottom:5 }}>{s.title}</div>
              <div style={{ fontFamily:FONTS.ui, fontSize:12.5, color:theme.textDim, lineHeight:1.58 }}>{s.body}</div>
            </div>
          ))}

          {/* FIRE flavours */}
          <div style={{ marginTop:18, marginBottom:20 }}>
            <div style={{ fontFamily:FONTS.mono, fontSize:9.5, letterSpacing:1.4, textTransform:'uppercase', color:theme.textMute, marginBottom:12 }}>
              FIRE flavours
            </div>
            {flavours.map(f => (
              <div key={f.label} style={{ display:'flex', gap:10, alignItems:'flex-start', marginBottom:11 }}>
                <div style={{ width:7, height:7, borderRadius:99, background:f.color, flexShrink:0, marginTop:4 }} />
                <div>
                  <span style={{ fontFamily:FONTS.ui, fontSize:12.5, fontWeight:600, color:theme.text }}>{f.label} · </span>
                  <span style={{ fontFamily:FONTS.ui, fontSize:12.5, color:theme.textDim }}>{f.desc}</span>
                </div>
              </div>
            ))}
          </div>

          {/* close */}
          <button
            onClick={onClose}
            style={{ width:'100%', background: midnight ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)', border:'none', borderRadius:14, padding:'14px', fontFamily:FONTS.ui, fontSize:14, fontWeight:500, color:theme.textDim, cursor:'pointer' }}
          >
            Got it
          </button>
        </div>
      </div>
    </div>
  );
}

/* ── Main screen ─────────────────────────────────────────────────────────── */

function FireTrackerScreen({ theme, accent, onBack, onAskHimma }) {
  const YEARLY_INCOME = 297_600;
  const BASE_YEAR     = 2026;
  const BASE_AGE      = 31;

  const midnight = theme?.label === 'Midnight';

  // ── Shared inputs (pre-filled from the user's data, all editable) ─────────
  const [tab,            setTab]            = React.useState('when');
  const [yearlyExpenses, setYearlyExpenses] = React.useState(162_000);
  const [withdrawalRate, setWithdrawalRate] = React.useState(4);
  const [netWorth,       setNetWorth]       = React.useState(593_020);
  const [yearlySavings,  setYearlySavings]  = React.useState(86_400);
  const [returnRate,     setReturnRate]     = React.useState(8);
  const [targetAge,      setTargetAge]      = React.useState(45);

  const [showInfo, setShowInfo] = React.useState(false);

  const num = (v) => Math.max(0, parseFloat(String(v).replace(/[^\d.]/g, '')) || 0);

  // ── Derived: tab 1 (when can I retire?) ───────────────────────────────────
  const FIRE_NUMBER   = withdrawalRate > 0 ? Math.round(yearlyExpenses / (withdrawalRate / 100)) : 0;
  const YEARS_TO_FIRE = calcYearsToFire(netWorth, yearlySavings, returnRate / 100, FIRE_NUMBER);
  const FIRE_YEAR     = BASE_YEAR + YEARS_TO_FIRE;
  const FIRE_AGE      = BASE_AGE  + YEARS_TO_FIRE;
  const PROGRESS_PCT  = FIRE_NUMBER > 0 ? Math.min(netWorth / FIRE_NUMBER, 1) : 0;

  // ── Derived: tab 2 (retire by a target age) ───────────────────────────────
  const n      = Math.max(targetAge - BASE_AGE, 1);
  const r      = Math.max(returnRate, 0.1) / 100;
  const growth = Math.pow(1 + r, n);
  const fvOfNetWorth = netWorth * growth;
  const reqSavings   = Math.max(0, Math.round((FIRE_NUMBER - fvOfNetWorth) * r / (growth - 1)));
  const savingsGap   = reqSavings - yearlySavings;

  const heroBg = midnight ? `${accent}14` : '#E8F0FB';
  const dhPrefix = <Dh size="0.8em" color={theme.textMute} />;

  const fields = [
    ...(tab === 'age' ? [
      { key:'age', label:'Target retirement age', value:targetAge, set:setTargetAge, suffix:`${Math.max(targetAge - BASE_AGE, 0)} yrs away` },
    ] : []),
    { key:'networth',   label:'Current net worth',  value:netWorth,       set:setNetWorth,       prefix:dhPrefix },
    { key:'expenses',   label:'Yearly expenditure', value:yearlyExpenses, set:setYearlyExpenses, prefix:dhPrefix },
    { key:'savings',    label:'Yearly savings',     value:yearlySavings,  set:setYearlySavings,  prefix:dhPrefix },
    { key:'withdrawal', label:'Withdrawal rate',    value:withdrawalRate, set:setWithdrawalRate, suffix:'%' },
    { key:'return',     label:'Expected return',    value:returnRate,     set:setReturnRate,     suffix:'% / yr' },
  ];

  return (
    <div style={{ position: 'relative', height: '100%' }}>
    <Screen theme={theme} padBottom={48}>

      {/* ── Header ── */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 20px 4px' }}>
        <button onClick={onBack} style={{ width:36, height:36, borderRadius:18, background:'transparent', border:`0.5px solid ${theme.line2}`, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Ico.chevL size={14} stroke={theme.text} />
        </button>
        <div style={{ fontFamily:FONTS.mono, fontSize:10, letterSpacing:1.5, textTransform:'uppercase', color:theme.textMute }}>
          FIRE Tracker
        </div>
        <button onClick={() => setShowInfo(true)} style={{ width:36, height:36, borderRadius:18, background:'transparent', border:`0.5px solid ${theme.line2}`, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Ico.info size={15} stroke={theme.text} sw={1.5} />
        </button>
      </div>

      <div style={{ padding: '14px 16px 0', display: 'flex', flexDirection: 'column', gap: 12 }}>

        {/* ── Tab switch ── */}
        <div style={{ display:'flex', gap:3, background: midnight ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)', borderRadius:13, padding:3 }}>
          {[
            ['when', 'When can I retire?'],
            ['age',  'Retire by an age'],
          ].map(([key, label]) => {
            const sel = tab === key;
            return (
              <button key={key} onClick={() => setTab(key)} style={{
                flex:1, padding:'9px 0', borderRadius:10, cursor:'pointer', border:'none',
                background: sel ? (midnight ? 'rgba(255,255,255,0.12)' : theme.surface) : 'transparent',
                boxShadow: sel && !midnight ? '0 1px 4px rgba(0,0,0,0.08)' : 'none',
                fontFamily:FONTS.ui, fontSize:12.5, fontWeight: sel ? 650 : 450,
                color: sel ? theme.text : theme.textDim,
              }}>
                {label}
              </button>
            );
          })}
        </div>

        {/* ── Output card ── */}
        {tab === 'when' ? (
          <Card theme={theme} style={{ background: heroBg, padding: 20 }}>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:14 }}>
              <div style={{ fontFamily:FONTS.mono, fontSize:9.5, letterSpacing:1.4, textTransform:'uppercase', color:theme.textMute }}>
                Financial independence
              </div>
              <div style={{ fontFamily:FONTS.mono, fontSize:10, fontWeight:600, color:accent, background:`${accent}18`, padding:'3px 9px', borderRadius:8, letterSpacing:0.2 }}>
                {(PROGRESS_PCT * 100).toFixed(1)}% there
              </div>
            </div>
            <div style={{ display:'flex', alignItems:'baseline', gap:8 }}>
              <span style={{ fontFamily:FONTS.display, fontSize:38, color:theme.text, letterSpacing:-1.2, lineHeight:1 }}>
                {YEARS_TO_FIRE} {YEARS_TO_FIRE === 1 ? 'year' : 'years'}
              </span>
              <span style={{ fontFamily:FONTS.ui, fontSize:13, color:theme.textDim }}>{FIRE_YEAR} · age {FIRE_AGE}</span>
            </div>
            <div style={{ marginTop:16, background: midnight ? 'rgba(255,255,255,0.1)' : 'rgba(255,255,255,0.75)', borderRadius:6, height:8, overflow:'hidden' }}>
              <div style={{ width:`${PROGRESS_PCT * 100}%`, height:'100%', borderRadius:6, background:`linear-gradient(90deg, ${accent}99 0%, ${accent} 100%)` }} />
            </div>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop:13 }}>
              <span style={{ fontFamily:FONTS.ui, fontSize:13, color:theme.text }}>Your FIRE number</span>
              <span style={{ fontFamily:FONTS.display, fontSize:18, color:accent, letterSpacing:-0.4, display:'flex', alignItems:'center', gap:3 }}>
                <Dh size="0.82em" color={accent} />
                {fmtAED(FIRE_NUMBER, { compact:false })}
              </span>
            </div>
          </Card>
        ) : (
          <Card theme={theme} style={{ background: heroBg, padding: 20 }}>
            <div style={{ fontFamily:FONTS.mono, fontSize:9.5, letterSpacing:1.4, textTransform:'uppercase', color:theme.textMute, marginBottom:14 }}>
              To retire at {targetAge}
            </div>
            <div style={{ display:'flex', alignItems:'baseline', gap:6 }}>
              <Dh size="1em" color={theme.text} />
              <span style={{ fontFamily:FONTS.display, fontSize:38, color:theme.text, letterSpacing:-1.2, lineHeight:1 }}>
                {fmtAED(reqSavings, { compact:false })}
              </span>
              <span style={{ fontFamily:FONTS.ui, fontSize:13, color:theme.textDim }}>savings needed per year</span>
            </div>
            <div style={{ fontFamily:FONTS.ui, fontSize:11.5, marginTop:7, color: savingsGap > 0 ? theme.negative : theme.positive, fontWeight:600 }}>
              {reqSavings === 0
                ? 'Already on track with your net worth alone'
                : savingsGap > 0
                  ? dhText(`AED ${fmtAED(savingsGap)} more than you save today`)
                  : dhText(`You already save AED ${fmtAED(Math.abs(savingsGap))} more than needed`)}
            </div>
            <div style={{ marginTop:14, paddingTop:12, borderTop:`0.5px solid ${midnight ? 'rgba(255,255,255,0.1)' : 'rgba(11,29,58,0.12)'}` }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                <span style={{ fontFamily:FONTS.ui, fontSize:12.5, color:theme.textDim }}>FIRE number at {targetAge}</span>
                <span style={{ fontFamily:FONTS.mono, fontSize:12.5, fontWeight:600, color:accent, whiteSpace:'nowrap' }}>
                  <Dh size="0.85em" color={accent} /> {fmtAED(FIRE_NUMBER, { compact:false })}
                </span>
              </div>
            </div>
          </Card>
        )}

        {/* ── Calculator inputs ── */}
        <Card theme={theme} style={{ padding:18 }}>
          <div style={{ fontFamily:FONTS.mono, fontSize:9.5, letterSpacing:1.3, textTransform:'uppercase', color:theme.textMute, marginBottom:14 }}>
            {tab === 'when' ? 'Your numbers' : 'Your plan'}
          </div>

          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {fields.map((f) => (
              <div key={f.key} style={{ minWidth: 0 }}>
                <Field
                  theme={theme}
                  label={f.label}
                  value={f.value.toLocaleString()}
                  onChange={(v) => f.set(num(v))}
                  prefix={f.prefix}
                  suffix={f.suffix}
                  placeholder="0"
                />
              </div>
            ))}
          </div>

          <div style={{ fontFamily:FONTS.ui, fontSize:10, color:theme.textMute, marginTop:12 }}>
            Expenses held constant in real terms · property equity not counted
          </div>
        </Card>

        {/* ── Ask Himma CTA ── */}
        <button
          onClick={onAskHimma}
          style={{
            width:'100%', background:accent, color:'#fff', border:'none',
            borderRadius:999, padding:'15px 20px', fontFamily:FONTS.ui, fontSize:15, fontWeight:600,
            cursor:'pointer', letterSpacing:-0.2,
          }}
        >
          Refine my FIRE plan with Himma
        </button>

      </div>
    </Screen>

    {/* ── FIRE info sheet ── */}
    {showInfo && (
      <FireInfoSheet
        theme={theme} accent={accent} midnight={midnight}
        onClose={() => setShowInfo(false)}
      />
    )}

    </div>
  );
}

Object.assign(window, { FireTrackerScreen });
