const { useState, useMemo } = React;

const VERSION = 'v1.2';

// ── Themes ────────────────────────────────────────────────────────────────────

const THEMES = {
  light: {
    bg:            "#ffffff",
    panelBg:       "#f8fafc",
    cardBg:        "#ffffff",
    border:        "#e2e8f0",
    textPrimary:   "#0f172a",
    textSecondary: "#475569",
    textMuted:     "#94a3b8",
    inputBg:       "#f1f5f9",
    inputBorder:   "#e2e8f0",
    inputColor:    "#EA580C",
    primary:       "#EA580C",
    primaryDark:   "#C2410C",
    gain:          "#16A34A",
    gainBg:        "#dcfce7",
    gainText:      "#15803d",
    burnBg:        "#fff7ed",
    burnBorder:    "#fed7aa",
    burnText:      "#EA580C",
    goldBg:        "#fefce8",
    goldText:      "#854d0e",
    sliderTrack:   "#e2e8f0",
    sliderFill:    "linear-gradient(90deg,#c2410c,#EA580C)",
    toggleBg:      "#f1f5f9",
    toggleBorder:  "#e2e8f0",
    toggleText:    "#475569",
    activeBg:      "#fff7ed",
    activeBorder:  "#EA580C",
    activeText:    "#EA580C",
    inactiveBorder:"#e2e8f0",
    inactiveText:  "#94a3b8",
    hintText:      "#94a3b8",
    labelText:     "#475569",
    sectionLabel:  "#94a3b8",
    disclaimer:    "#94a3b8",
    warningText:   "#b45309",
    warningBg:     "#fffbeb",
    errorText:     "#DC2626",
    errorBg:       "rgba(220,38,38,0.08)",
  },
  dark: {
    bg:            "#0F172A",
    panelBg:       "#1E293B",
    cardBg:        "#1E293B",
    border:        "#334155",
    textPrimary:   "#f1f5f9",
    textSecondary: "#cbd5e1",
    textMuted:     "#94a3b8",
    inputBg:       "#0F172A",
    inputBorder:   "#334155",
    inputColor:    "#FB923C",
    primary:       "#FB923C",
    primaryDark:   "#EA580C",
    gain:          "#4ADE80",
    gainBg:        "rgba(74,222,128,0.10)",
    gainText:      "#4ADE80",
    burnBg:        "rgba(251,146,60,0.10)",
    burnBorder:    "rgba(251,146,60,0.30)",
    burnText:      "#FB923C",
    goldBg:        "rgba(250,204,21,0.08)",
    goldText:      "#FCD34D",
    sliderTrack:   "#334155",
    sliderFill:    "linear-gradient(90deg,#C2410C,#FB923C)",
    toggleBg:      "#1E293B",
    toggleBorder:  "#334155",
    toggleText:    "#cbd5e1",
    activeBg:      "rgba(251,146,60,0.12)",
    activeBorder:  "#FB923C",
    activeText:    "#FB923C",
    inactiveBorder:"#334155",
    inactiveText:  "#94a3b8",
    hintText:      "#94a3b8",
    labelText:     "#cbd5e1",
    sectionLabel:  "#94a3b8",
    disclaimer:    "#94a3b8",
    warningText:   "#FCD34D",
    warningBg:     "rgba(250,204,21,0.08)",
    errorText:     "#F87171",
    errorBg:       "rgba(248,113,113,0.10)",
  }
};

// ── Historical Data ────────────────────────────────────────────────────────────
// US average retail cigarette price per pack of 20 (CDC/BLS)

const PACK_PRICES = {
  1945: 0.18, 1946: 0.18, 1947: 0.19, 1948: 0.19, 1949: 0.19,
  1950: 0.20, 1951: 0.21, 1952: 0.21, 1953: 0.22, 1954: 0.22,
  1955: 0.22, 1956: 0.23, 1957: 0.23, 1958: 0.24, 1959: 0.24,
  1960: 0.25, 1961: 0.25, 1962: 0.26, 1963: 0.26,
  1964: 0.27, 1965: 0.28, 1966: 0.29, 1967: 0.30, 1968: 0.31, 1969: 0.33,
  1970: 0.35, 1971: 0.37, 1972: 0.38, 1973: 0.40, 1974: 0.43, 1975: 0.46,
  1976: 0.49, 1977: 0.52, 1978: 0.56, 1979: 0.60, 1980: 0.63, 1981: 0.71,
  1982: 0.77, 1983: 0.84, 1984: 0.87, 1985: 0.88, 1986: 0.89, 1987: 0.97,
  1988: 1.10, 1989: 1.25, 1990: 1.58, 1991: 1.75, 1992: 1.89, 1993: 1.93,
  1994: 1.84, 1995: 1.73, 1996: 1.76, 1997: 1.77, 1998: 1.86, 1999: 2.09,
  2000: 3.73, 2001: 3.91, 2002: 4.10, 2003: 4.22, 2004: 4.25, 2005: 4.54,
  2006: 4.69, 2007: 4.85, 2008: 5.05, 2009: 5.24, 2010: 5.54, 2011: 5.71,
  2012: 5.80, 2013: 5.89, 2014: 6.03, 2015: 6.22, 2016: 6.38, 2017: 6.49,
  2018: 6.56, 2019: 6.63, 2020: 6.65, 2021: 7.13, 2022: 7.61, 2023: 7.92,
  2024: 8.24
};

// S&P 500 annual total returns (dividends reinvested), actual historical data
const SP500_RETURNS = {
  1945: 0.364, 1946: -0.081, 1947: 0.052, 1948: 0.055, 1949: 0.188,
  1950: 0.317, 1951: 0.240, 1952: 0.184, 1953: -0.010, 1954: 0.526,
  1955: 0.316, 1956: 0.066, 1957: -0.108, 1958: 0.434, 1959: 0.120,
  1960: 0.005, 1961: 0.269, 1962: -0.087, 1963: 0.228,
  1964: 0.163, 1965: 0.125, 1966: -0.101, 1967: 0.240, 1968: 0.111, 1969: -0.085,
  1970: 0.040, 1971: 0.143, 1972: 0.190, 1973: -0.147, 1974: -0.265, 1975: 0.372,
  1976: 0.236, 1977: -0.072, 1978: 0.066, 1979: 0.184, 1980: 0.324, 1981: -0.049,
  1982: 0.214, 1983: 0.225, 1984: 0.063, 1985: 0.322, 1986: 0.185, 1987: 0.052,
  1988: 0.168, 1989: 0.315, 1990: -0.032, 1991: 0.306, 1992: 0.077, 1993: 0.099,
  1994: 0.013, 1995: 0.375, 1996: 0.230, 1997: 0.334, 1998: 0.286, 1999: 0.210,
  2000: -0.091, 2001: -0.119, 2002: -0.221, 2003: 0.287, 2004: 0.109, 2005: 0.049,
  2006: 0.158, 2007: 0.055, 2008: -0.370, 2009: 0.265, 2010: 0.151, 2011: 0.021,
  2012: 0.160, 2013: 0.324, 2014: 0.137, 2015: 0.014, 2016: 0.120, 2017: 0.218,
  2018: -0.044, 2019: 0.315, 2020: 0.184, 2021: 0.287, 2022: -0.181, 2023: 0.263,
  2024: 0.233
};

// Gold annual average price per troy oz (USD) — LBMA data
const GOLD_PRICES = {
  // Bretton Woods fixed rate: $35/oz until Nixon shock (1971)
  1945: 35.0, 1946: 35.0, 1947: 35.0, 1948: 35.0, 1949: 35.0,
  1950: 35.0, 1951: 35.0, 1952: 35.0, 1953: 35.0, 1954: 35.0,
  1955: 35.0, 1956: 35.0, 1957: 35.0, 1958: 35.0, 1959: 35.0,
  1960: 35.0, 1961: 35.0, 1962: 35.0, 1963: 35.1,
  1964: 35.1, 1965: 35.1, 1966: 35.1, 1967: 35.2, 1968: 39.3, 1969: 41.1,
  1970: 36.0, 1971: 40.8, 1972: 64.9, 1973: 107.0, 1974: 185.0, 1975: 161.0,
  1976: 124.0, 1977: 148.0, 1978: 194.0, 1979: 307.0, 1980: 590.0, 1981: 459.0,
  1982: 376.0, 1983: 424.0, 1984: 360.0, 1985: 327.0, 1986: 368.0, 1987: 484.0,
  1988: 438.0, 1989: 381.0, 1990: 385.0, 1991: 362.0, 1992: 344.0, 1993: 360.0,
  1994: 384.0, 1995: 384.0, 1996: 387.0, 1997: 331.0, 1998: 294.0, 1999: 279.0,
  2000: 279.0, 2001: 271.0, 2002: 310.0, 2003: 416.0, 2004: 438.0, 2005: 513.0,
  2006: 636.0, 2007: 833.0, 2008: 869.0, 2009: 1088.0, 2010: 1225.0, 2011: 1572.0,
  2012: 1669.0, 2013: 1204.0, 2014: 1200.0, 2015: 1060.0, 2016: 1151.0, 2017: 1302.0,
  2018: 1268.0, 2019: 1478.0, 2020: 1887.0, 2021: 1800.0, 2022: 1800.0, 2023: 2063.0,
  2024: 2500.0
};

const CURRENT_GOLD_PRICE = 3300; // USD/troy oz, June 2025
const CURRENT_YEAR = 2025;
const MINS_PER_CIGARETTE = 7;

// ── Assets you could own ──────────────────────────────────────────────────────

const ASSETS = [
  { id: 'camry',    name: 'Toyota Camry',      detail: '2025 XSE',           price: 31000,  icon: '🚗' },
  { id: 'tesla3',   name: 'Tesla Model 3',      detail: 'Long Range AWD',     price: 43000,  icon: '⚡' },
  { id: 'bmw3',     name: 'BMW 3 Series',       detail: '330i xDrive',        price: 47500,  icon: '🚗' },
  { id: 'teslaS',   name: 'Tesla Model S',      detail: 'Plaid',              price: 89990,  icon: '⚡' },
  { id: 'porsche',  name: 'Porsche 911',        detail: 'Carrera 4S',         price: 130000, icon: '🏎️' },
  { id: 'ferrari',  name: 'Ferrari F8',         detail: 'Spider',             price: 285000, icon: '🏎️' },
  { id: 'gold_oz',  name: 'Troy Oz of Gold',    detail: '~June 2025 spot',    price: 3300,   icon: '🏅' },
  { id: 'btc',      name: 'Bitcoin',            detail: '1 BTC ~Jun 2025',    price: 98000,  icon: '₿' },
  { id: 'harvard',  name: 'Harvard — 1 Year',  detail: 'Tuition + fees',     price: 65000,  icon: '🎓' },
  { id: 'house_dp', name: 'House Down Payment', detail: '20% of $410k median',price: 82000,  icon: '🏡' },
];

// ── Share Card Configs ────────────────────────────────────────────────────────

const CARD_CONFIGS = {
  porsche: {
    file:     'images/SmokeLossPorsche02.png',
    label:    'Porsche 911',
    carPrice: 130000,
    pos: {
      mainSpent:  { x: 726,  y: 154, s: 100 },
      smokeSpent: { x: 235,  y: 411, s: 52  },
      sp500:      { x: 712,  y: 411, s: 52  },
      car:        { x: 1180, y: 411, s: 46  },
      cigarettes: { x: 285,  y: 843, s: 36  },
    }
  },
  tesla: {
    file:     'images/SmokeLossTesla3.png',
    label:    'Tesla Model 3',
    carPrice: 43000,
    pos: {
      mainSpent:  { x: 726,  y: 154, s: 100 },
      smokeSpent: { x: 235,  y: 411, s: 52  },
      sp500:      { x: 712,  y: 411, s: 52  },
      car:        { x: 1180, y: 411, s: 46  },
      cigarettes: { x: 285,  y: 843, s: 36  },
    }
  },
  porscheM: {
    file:     'images/SmokeLossPorscheM.png',
    label:    'Porsche (Portrait)',
    carPrice: 130000,
    pos: {
      mainSpent:  { x: 478,  y: 228,  s: 120 },
      smokeSpent: null,
      sp500:      { x: 265,  y: 923,  s: 60  },
      car:        { x: 208,  y: 1325, s: 75  },
      cigarettes: { x: 685,  y: 540,  s: 72  },
    }
  },
  teslaM: {
    file:     'images/SmokeLossTesla3M.png',
    label:    'Tesla (Portrait)',
    carPrice: 43000,
    pos: {
      mainSpent:  { x: 478,  y: 228,  s: 120 },
      smokeSpent: null,
      sp500:      { x: 265,  y: 923,  s: 60  },
      car:        { x: 208,  y: 1325, s: 75  },
      cigarettes: { x: 685,  y: 540,  s: 72  },
    }
  }
};

// ── Helpers ───────────────────────────────────────────────────────────────────

function fmt(n) {
  return '$' + Math.round(n).toLocaleString('en-US');
}

function fmtOz(n) {
  return n < 1 ? n.toFixed(2) + ' oz' : n.toFixed(1) + ' oz';
}

function getRoast(totalSpent) {
  if (totalSpent < 2000)   return "You got off easy. For now.";
  if (totalSpent < 5000)   return "That's a decent vacation — gone.";
  if (totalSpent < 10000)  return "A year of car payments. Inhaled.";
  if (totalSpent < 20000)  return "A solid used car. Up in smoke.";
  if (totalSpent < 31000)  return "A brand new Toyota Camry. Smoked away.";
  if (totalSpent < 50000)  return "BMW 3 Series money. Gone.";
  if (totalSpent < 82000)  return "College tuition. Inhaled.";
  if (totalSpent < 130000) return "A house down payment. Up in smoke.";
  if (totalSpent < 500000) return "You've burned a small fortune.";
  return "Congratulations. You've burned enough to retire on.";
}

// ── Calculation ───────────────────────────────────────────────────────────────

function calculateResults(startYear, cigsPerDay) {
  let totalSpent    = 0;
  let sp500Portfolio = 0;
  let totalGoldOz   = 0;
  let totalCigs     = 0;
  const yearlyData  = [];

  for (let y = startYear; y < CURRENT_YEAR; y++) {
    const packPrice   = PACK_PRICES[y]    ?? PACK_PRICES[2024];
    const goldPrice   = GOLD_PRICES[y]    ?? GOLD_PRICES[2024];
    const sp500Return = SP500_RETURNS[y]  ?? 0.10;

    const annualSpend = (cigsPerDay / 20) * 365 * packPrice;
    const annualCigs  = cigsPerDay * 365;

    totalSpent     += annualSpend;
    totalCigs      += annualCigs;
    sp500Portfolio  = (sp500Portfolio + annualSpend) * (1 + sp500Return);
    totalGoldOz    += annualSpend / goldPrice;

    yearlyData.push({ year: y, annualSpend, cumulative: totalSpent });
  }

  const goldValue   = totalGoldOz * CURRENT_GOLD_PRICE;
  const yearsSmoked = CURRENT_YEAR - startYear;
  const minutesSmoking = totalCigs * MINS_PER_CIGARETTE;

  return {
    totalSpent,
    sp500Value:    sp500Portfolio,
    goldValue,
    totalGoldOz,
    totalCigs,
    yearsSmoked,
    daysOfLife:    Math.round(minutesSmoking / 60 / 24),
    sp500Gain:     sp500Portfolio / Math.max(1, totalSpent),
    goldGain:      goldValue      / Math.max(1, totalSpent),
    packYears:     (cigsPerDay / 20) * yearsSmoked,
    yearlyData,
  };
}

// ── Slider ────────────────────────────────────────────────────────────────────

function Slider({ label, value, min, max, step = 1, display, unit, onChange, hint, theme: t }) {
  const [inputVal, setInputVal] = useState(String(display ?? value));

  React.useEffect(() => { setInputVal(String(display ?? value)); }, [value, display]);

  const handleInputChange = (e) => {
    setInputVal(e.target.value);
    const n = Number(e.target.value);
    if (!isNaN(n) && n >= min && n <= max) onChange(n);
  };

  const handleBlur = () => {
    const n = Number(inputVal);
    if (isNaN(n)) { setInputVal(String(display ?? value)); return; }
    const clamped = Math.max(min, Math.min(max, n));
    onChange(clamped);
    setInputVal(String(clamped));
  };

  const pct = ((value - min) / (max - min)) * 100;

  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
        <span style={{ fontSize: 13, color: t.labelText, fontFamily: "'DM Sans', sans-serif" }}>{label}</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <input
            type="number"
            value={inputVal}
            min={min} max={max} step={step}
            onChange={handleInputChange}
            onBlur={handleBlur}
            style={{
              width: 68, padding: '3px 6px', borderRadius: 6,
              border: `1px solid ${t.inputBorder}`,
              background: t.inputBg, color: t.inputColor,
              fontSize: 13, fontWeight: 600, fontFamily: 'monospace',
              textAlign: 'right', outline: 'none',
              WebkitAppearance: 'none', MozAppearance: 'textfield'
            }}
          />
          {unit && <span className="sl-hint" style={{ fontSize: 12, color: t.textMuted, minWidth: 24 }}>{unit}</span>}
        </div>
      </div>

      <div style={{ position: 'relative', height: 6, background: t.sliderTrack, borderRadius: 3 }}>
        <div style={{
          position: 'absolute', left: 0, width: `${pct}%`,
          height: '100%', background: t.sliderFill,
          borderRadius: 3, pointerEvents: 'none'
        }} />
        <input
          type="range" min={min} max={max} step={step} value={value}
          onChange={e => onChange(Number(e.target.value))}
          style={{
            position: 'absolute', top: -5, left: 0,
            width: '100%', height: 16,
            opacity: 0, cursor: 'pointer', zIndex: 2
          }}
        />
      </div>

      {hint && (
        <p className="sl-hint" style={{ fontSize: 12, color: t.hintText, margin: '4px 0 0' }}>{hint}</p>
      )}
    </div>
  );
}

// ── StatCard ──────────────────────────────────────────────────────────────────

function StatCard({ label, value, sub, subColor, borderColor, bg, theme: t }) {
  return (
    <div style={{
      flex: 1, minWidth: 0,
      background: bg || t.cardBg,
      border: `1px solid ${borderColor || t.border}`,
      borderRadius: 12, padding: '16px 16px 14px'
    }}>
      <div style={{ fontSize: 11, color: t.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6 }}>
        {label}
      </div>
      <div style={{ fontSize: 26, fontWeight: 700, fontFamily: "'DM Mono', monospace", color: t.textPrimary, lineHeight: 1.1, marginBottom: 4 }}>
        {value}
      </div>
      {sub && (
        <div style={{ fontSize: 12, color: subColor || t.textMuted, fontWeight: 500 }}>
          {sub}
        </div>
      )}
    </div>
  );
}

// ── Investment Panel ──────────────────────────────────────────────────────────

function InvestmentPanel({ results, theme: t }) {
  // ARCHIVED: gold toggle — restore activeTab/setActiveTab props + isGold logic to re-enable
  // const isGold = activeTab === 'gold';
  // const value  = isGold ? results.goldValue : results.sp500Value;
  // const gain   = isGold ? results.goldGain  : results.sp500Gain;
  const value = results.sp500Value;
  const gain  = results.sp500Gain;
  const extra = value - results.totalSpent;

  return (
    <div style={{
      background: t.cardBg, border: `1px solid ${t.border}`,
      borderRadius: 12, padding: '18px 18px 16px', marginBottom: 14
    }}>
      {/* ARCHIVED: S&P 500 / Gold tab toggle
      <div style={{ display: 'flex', gap: 6, marginBottom: 18 }}>
        {[['sp500', 'S&P 500'], ['gold', 'Gold']].map(([id, label]) => (
          <button key={id} onClick={() => setActiveTab(id)} style={{
            padding: '5px 14px', borderRadius: 20, cursor: 'pointer',
            border: `1px solid ${activeTab === id ? t.activeBorder : t.inactiveBorder}`,
            background: activeTab === id ? t.activeBg : 'transparent',
            color: activeTab === id ? t.activeText : t.inactiveText,
            fontSize: 12, fontWeight: 500, fontFamily: "'DM Sans', sans-serif"
          }}>{label}</button>
        ))}
        <span style={{ marginLeft: 'auto', fontSize: 11, color: t.textMuted, alignSelf: 'center' }}>
          if you'd invested instead
        </span>
      </div>
      */}

      {/* Header */}
      <div style={{ marginBottom: 18 }}>
        <span className="sl-label" style={{ fontSize: 11, color: t.textMuted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
          S&amp;P 500 — if you'd invested instead
        </span>
      </div>

      {/* Big value */}
      <div className="sl-invest-row" style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 10 }}>
        <div className="sl-invest-big" style={{ fontSize: 42, fontWeight: 700, fontFamily: "'DM Mono', monospace", color: t.gain, lineHeight: 1 }}>
          {fmt(value)}
        </div>
        <div style={{
          padding: '5px 14px', borderRadius: 20,
          background: t.gainBg, color: t.gainText,
          fontSize: 13, fontWeight: 700, flexShrink: 0
        }}>
          {gain.toFixed(1)}× your money
        </div>
      </div>

      {/* Gain bar */}
      <div style={{ marginBottom: 10 }}>
        <div className="sl-label" style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: t.textMuted, marginBottom: 4 }}>
          <span>Your actual spend</span>
          <span>Investment value today</span>
        </div>
        <div style={{ display: 'flex', height: 8, borderRadius: 4, overflow: 'hidden', gap: 2 }}>
          <div style={{
            width: `${Math.min(85, (1 / gain) * 100)}%`,
            background: t.burnBg, border: `1px solid ${t.burnBorder}`,
            borderRadius: 4, minWidth: 4
          }} />
          <div style={{ flex: 1, background: t.gain, borderRadius: 4 }} />
        </div>
      </div>

      {/* Detail row */}
      <div className="sl-hint" style={{ display: 'flex', gap: 20, fontSize: 12, color: t.textSecondary }}>
        <span>Spent: <strong style={{ color: t.textPrimary, fontFamily: "'DM Mono', monospace" }}>{fmt(results.totalSpent)}</strong></span>
        <span>Gain: <strong style={{ color: t.gain, fontFamily: "'DM Mono', monospace" }}>+{fmt(extra)}</strong></span>
        {/* ARCHIVED: gold oz detail
        {isGold && <span>Oz: <strong style={{ color: t.goldText, fontFamily: "'DM Mono', monospace" }}>{fmtOz(results.totalGoldOz)}</strong></span>}
        */}
      </div>

      {/* ARCHIVED: gold note
      {isGold && (
        <div style={{ marginTop: 10, fontSize: 11, color: t.textMuted, lineHeight: 1.6 }}>
          Gold spot price used: <strong style={{ color: t.goldText }}>${CURRENT_GOLD_PRICE.toLocaleString()}/oz</strong> (June 2025).
          You accumulated <strong style={{ color: t.goldText }}>{results.totalGoldOz.toFixed(2)} troy oz</strong> of gold.
        </div>
      )}
      */}
      <div className="sl-label" style={{ marginTop: 10, fontSize: 11, color: t.textMuted, lineHeight: 1.6 }}>
        Assumes annual investment at actual S&amp;P 500 total returns, 1964–2024. No taxes or fees modelled. Past performance.
      </div>
    </div>
  );
}

// ── Asset Gallery ─────────────────────────────────────────────────────────────

function AssetCard({ asset, budget, theme: t }) {
  const count    = budget / asset.price;
  const canAfford = count >= 1;
  const nearMiss  = count >= 0.5 && count < 1;

  let borderCol  = t.border;
  let badgeBg    = t.inputBg;
  let badgeColor = t.textMuted;
  let label      = '';

  if (canAfford) {
    borderCol  = t.gain;
    badgeBg    = t.gainBg;
    badgeColor = t.gainText;
    label      = `${count >= 10 ? Math.floor(count) : count.toFixed(1)}×`;
  } else if (nearMiss) {
    borderCol  = t.warningText;
    badgeBg    = t.warningBg;
    badgeColor = t.warningText;
    label      = `${Math.round(count * 100)}%`;
  } else {
    label = `${Math.round(count * 100)}%`;
  }

  return (
    <div style={{
      background: t.cardBg,
      border: `1.5px solid ${borderCol}`,
      borderRadius: 10, padding: '14px 12px',
      display: 'flex', flexDirection: 'column', gap: 6
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <span style={{ fontSize: 28, lineHeight: 1 }}>{asset.icon}</span>
        <span style={{
          fontSize: 13, fontWeight: 700, fontFamily: "'DM Mono', monospace",
          background: badgeBg, color: badgeColor,
          padding: '2px 8px', borderRadius: 20
        }}>{label}</span>
      </div>
      <div>
        <div style={{ fontSize: 13, fontWeight: 600, color: t.textPrimary, lineHeight: 1.3 }}>{asset.name}</div>
        <div className="sl-label" style={{ fontSize: 11, color: t.textMuted, marginTop: 2 }}>{asset.detail}</div>
      </div>
      <div className="sl-hint" style={{ fontSize: 12, color: t.textSecondary, fontFamily: "'DM Mono', monospace", fontWeight: 600 }}>
        {fmt(asset.price)}
      </div>
    </div>
  );
}

// ── Fun Stats Bar ─────────────────────────────────────────────────────────────

function FunStats({ results, theme: t }) {
  const stats = [
    { label: 'Cigarettes smoked', value: results.totalCigs.toLocaleString('en-US') },
    { label: 'Days spent smoking', value: results.daysOfLife + ' days' },
    { label: 'Years of habit', value: results.yearsSmoked + ' yrs' },
  ];

  return (
    <div style={{ display: 'flex', gap: 10, marginBottom: 14, flexWrap: 'wrap' }}>
      {stats.map(s => (
        <div key={s.label} className="sl-stat-card" style={{
          flex: 1, minWidth: 120,
          background: t.cardBg, border: `1px solid ${t.border}`,
          borderRadius: 10, padding: '12px 14px'
        }}>
          <div className="sl-label" style={{ fontSize: 11, color: t.textMuted, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4 }}>
            {s.label}
          </div>
          <div style={{ fontSize: 18, fontWeight: 700, fontFamily: "'DM Mono', monospace", color: t.textPrimary }}>
            {s.value}
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Health Risk Data ──────────────────────────────────────────────────────────

// Lung cancer RR by pack-years — Pesch B et al. Br J Cancer. 2012;106(5):1029–1036
function getLungRR(packYears) {
  if (packYears < 1)   return 1.5;
  if (packYears <= 5)  return 3;
  if (packYears <= 10) return 5;
  if (packYears <= 20) return 11;
  if (packYears <= 30) return 18;
  if (packYears <= 40) return 22;
  return 30;
}

// Current smoker vs. never-smoker RR
// Sources: Gandini S et al. Int J Cancer. 2008;122(1):155–164 [G]
//          US Surgeon General's Report 2014 [SG]
const CANCER_RISKS_BASE = [
  { name: 'Larynx',              rr: 7,   detail: 'Throat / voice box',       citation: '[G]' },
  { name: 'Oral cavity / pharynx', rr: 6, detail: 'Mouth, tongue, throat',    citation: '[G]' },
  { name: 'Esophagus',           rr: 4,   detail: 'Squamous cell type',        citation: '[G]' },
  { name: 'Bladder',             rr: 3,   detail: '',                          citation: '[SG]' },
  { name: 'Pancreas',            rr: 2,   detail: '',                          citation: '[G]' },
  { name: 'Kidney',              rr: 1.5, detail: 'Renal cell carcinoma',      citation: '[G]' },
  { name: 'Stomach',             rr: 1.5, detail: '',                          citation: '[SG]' },
  { name: 'Colorectal',          rr: 1.2, detail: '',                          citation: '[SG]' },
];

function getRiskLevel(rr) {
  if (rr >= 15) return 'very-high';
  if (rr >= 5)  return 'high';
  if (rr >= 2)  return 'elevated';
  return 'slight';
}

// ── Health Risk Component ──────────────────────────────────────────────────────

function HealthRisk({ packYears, theme: t }) {
  const [expanded, setExpanded] = useState(false);

  const lungRR  = getLungRR(packYears);
  const lungLevel = getRiskLevel(lungRR);

  const riskStyle = (rr) => {
    const level = getRiskLevel(rr);
    const map = {
      'slight':    { bar: '#64748b',   badgeBg: t.inputBg,   badgeText: t.textMuted,   label: 'Slight'    },
      'elevated':  { bar: '#F59E0B',   badgeBg: t.warningBg, badgeText: t.warningText, label: 'Elevated'  },
      'high':      { bar: t.primary,   badgeBg: t.burnBg,    badgeText: t.burnText,    label: 'High'      },
      'very-high': { bar: t.errorText, badgeBg: t.errorBg,   badgeText: t.errorText,   label: 'Very High' },
    };
    return map[level];
  };

  // Log scale so even low-risk bars are visible (log base 32, max 30×)
  const barPct = (rr) => Math.round(Math.max(3, (Math.log(rr) / Math.log(32)) * 100));

  const allCancers = [
    { name: 'Lung', rr: lungRR, detail: `${packYears.toFixed(1)} pack-years — dose-response`, citation: '[P]', featured: true },
    ...CANCER_RISKS_BASE,
  ];

  // How many to show when collapsed
  const visibleCancers = expanded ? allCancers : allCancers.slice(0, 5);

  return (
    <div style={{
      background: t.cardBg, border: `1px solid ${t.border}`,
      borderRadius: 12, padding: '18px 18px 14px', marginBottom: 14
    }}>

      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 4 }}>
        <div>
          <p className="sl-label" style={{ fontSize: 11, color: t.sectionLabel, textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 3 }}>
            Cancer risk vs. never-smoker
          </p>
          <p className="sl-hint" style={{ fontSize: 12, color: t.textMuted }}>Population relative risk — not a personal diagnosis</p>
        </div>
        <div style={{ textAlign: 'right', flexShrink: 0, marginLeft: 12 }}>
          <div style={{ fontSize: 22, fontWeight: 700, fontFamily: "'DM Mono', monospace", color: t.textPrimary, lineHeight: 1 }}>
            {packYears.toFixed(1)}
          </div>
          <div className="sl-label" style={{ fontSize: 11, color: t.textMuted, marginTop: 2 }}>pack-years</div>
        </div>
      </div>

      {/* Cancer rows */}
      <div style={{ marginTop: 12 }}>
        {visibleCancers.map(cancer => {
          const s = riskStyle(cancer.rr);
          return (
            <div key={cancer.name} style={{ paddingTop: cancer.featured ? 14 : 10, paddingBottom: cancer.featured ? 2 : 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <span style={{
                    fontSize: cancer.featured ? 14 : 13,
                    fontWeight: cancer.featured ? 700 : 500,
                    color: t.textPrimary
                  }}>{cancer.name}</span>
                  {cancer.detail && (
                    <span className="sl-label" style={{ fontSize: 11, color: t.textMuted, marginLeft: 7 }}>{cancer.detail}</span>
                  )}
                </div>
                <span style={{
                  fontSize: cancer.featured ? 16 : 14, fontWeight: 700,
                  fontFamily: "'DM Mono', monospace", color: s.bar,
                  flexShrink: 0
                }}>~{cancer.rr}×</span>
                <span className="sl-xs" style={{
                  padding: '2px 8px', borderRadius: 20,
                  background: s.badgeBg, color: s.badgeText,
                  fontSize: 10, fontWeight: 700, textTransform: 'uppercase',
                  letterSpacing: '0.04em', flexShrink: 0, minWidth: 66, textAlign: 'center'
                }}>{s.label}</span>
                <span className="sl-xs" style={{ fontSize: 10, color: t.textMuted, flexShrink: 0 }}>{cancer.citation}</span>
              </div>
              <div style={{
                height: cancer.featured ? 7 : 4,
                background: t.sliderTrack, borderRadius: 4, overflow: 'hidden',
                marginBottom: cancer.featured ? 12 : 8
              }}>
                <div style={{ width: `${barPct(cancer.rr)}%`, height: '100%', background: s.bar, borderRadius: 4 }} />
              </div>
            </div>
          );
        })}
      </div>

      {/* Expand toggle */}
      {allCancers.length > 5 && (
        <button
          onClick={() => setExpanded(e => !e)}
          className="sl-hint"
          style={{
            background: 'none', border: 'none', cursor: 'pointer',
            fontSize: 12, color: t.primary, padding: '4px 0', marginBottom: 10,
            fontFamily: "'DM Sans', sans-serif"
          }}
        >
          {expanded ? '▲ Show fewer' : `▼ Show ${allCancers.length - 5} more cancers`}
        </button>
      )}

      {/* Quitting benefit */}
      <div style={{
        padding: '10px 12px', borderRadius: 8, marginBottom: 12,
        background: t.gainBg, border: `1px solid ${t.gain}30`
      }}>
        <p className="sl-hint" style={{ fontSize: 12, color: t.gainText, lineHeight: 1.65, margin: 0 }}>
          <strong>Quitting reduces risk.</strong> After 10 smoke-free years, lung cancer risk drops to roughly half a current smoker's. For most other cancers, excess risk continues to fall with time off cigarettes.
        </p>
      </div>

      {/* Citations */}
      <div style={{ borderTop: `1px solid ${t.border}`, paddingTop: 10 }}>
        {[
          '[P] Pesch B et al. Cigarette smoking and lung cancer — relative risk estimates for the major histological types from a pooled analysis of case-control studies. Br J Cancer. 2012;106(5):1029–1036.',
          '[G] Gandini S et al. Tobacco smoking and cancer: a meta-analysis. Int J Cancer. 2008;122(1):155–164.',
          '[SG] US Surgeon General\'s Report. The Health Consequences of Smoking — 50 Years of Progress. 2014.',
        ].map(ref => (
          <p key={ref} className="sl-label" style={{ fontSize: 11, color: t.textMuted, lineHeight: 1.6, marginBottom: 3, fontFamily: "'DM Mono', monospace" }}>
            {ref}
          </p>
        ))}
        <p className="sl-label" style={{ fontSize: 11, color: t.disclaimer, marginTop: 8, lineHeight: 1.6 }}>
          Relative risks are population-level estimates. Lung cancer uses pack-year dose-response data; other cancers show current smoker vs. never-smoker averages. Actual individual risk depends on age, genetics, family history, and other factors. This is not a medical assessment.
        </p>
      </div>
    </div>
  );
}

// ── Share Card (inline) ───────────────────────────────────────────────────────

function ShareCard({ results, theme: t }) {
  const canvasRef   = React.useRef(null);
  const bgCacheRef  = React.useRef({});
  const renderToken = React.useRef(0);  // incremented on each display render; stale calls abort
  const [cardBg, setCardBg] = React.useState('porscheM');

  async function loadBg(file) {
    if (bgCacheRef.current[file]) return bgCacheRef.current[file];
    return new Promise((res, rej) => {
      const img = new Image();
      img.onload  = () => { bgCacheRef.current[file] = img; res(img); };
      img.onerror = () => rej(new Error('Could not load ' + file));
      img.src = file;
    });
  }

  async function renderCard(bgKey, target) {
    const isDisplay = !target;
    const token = isDisplay ? ++renderToken.current : null;
    const canvas = target || canvasRef.current;
    if (!canvas) return;
    const cfg = CARD_CONFIGS[bgKey];

    await document.fonts.ready;
    const bg = await loadBg(cfg.file);
    if (isDisplay && token !== renderToken.current) return; // superseded by a newer call
    if (!bg.naturalWidth || !bg.naturalHeight) return;
    canvas.width  = bg.naturalWidth;
    canvas.height = bg.naturalHeight;
    const ctx = canvas.getContext('2d');  // get ctx after resize so state is fresh
    ctx.drawImage(bg, 0, 0);

    const P        = cfg.pos;
    const spent    = fmt(results.totalSpent);
    const sp500    = fmt(results.sp500Value);
    const cigs     = '~' + Math.round(results.totalCigs).toLocaleString('en-US');
    const carCount = (results.sp500Value / cfg.carPrice).toFixed(1) + '×';

    function drawText(text, x, y, font, color, shadow) {
      ctx.save();
      ctx.font = font; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
      ctx.fillStyle = color;
      if (shadow) {
        ctx.shadowColor   = shadow.color || 'rgba(0,0,0,0.6)';
        ctx.shadowBlur    = shadow.blur  || 18;
        ctx.shadowOffsetY = shadow.oy    || 3;
      }
      ctx.fillText(text, x, y);
      ctx.restore();
    }

    // Big headline — red gradient
    const { x: x0, y: y0, s: s0 } = P.mainSpent;
    const grad = ctx.createLinearGradient(0, y0 - s0 * 0.5, 0, y0 + s0 * 0.5);
    grad.addColorStop(0, '#FF3B30'); grad.addColorStop(0.45, '#E82010'); grad.addColorStop(1, '#B00000');
    ctx.save();
    ctx.font = `400 ${s0}px Anton, Impact, sans-serif`;
    ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
    ctx.strokeStyle = 'rgba(0,0,0,0.8)'; ctx.lineWidth = 3;
    ctx.shadowColor = 'rgba(0,0,0,0.7)'; ctx.shadowBlur = 22; ctx.shadowOffsetY = 5;
    ctx.strokeText(spent, x0, y0);
    ctx.fillStyle = grad; ctx.shadowColor = 'transparent';
    ctx.fillText(spent, x0, y0);
    ctx.restore();

    if (P.smokeSpent) drawText(spent,    P.smokeSpent.x, P.smokeSpent.y, `400 ${P.smokeSpent.s}px Anton, Impact, sans-serif`, '#FFFFFF', { blur: 14, oy: 3 });
    drawText(sp500,    P.sp500.x,      P.sp500.y,      `400 ${P.sp500.s}px Anton, Impact, sans-serif`,      '#45d657', { color: 'rgba(0,0,0,0.5)', blur: 12, oy: 3 });
    drawText(carCount, P.car.x,        P.car.y,        `400 ${P.car.s}px Anton, Impact, sans-serif`,        '#FFFFFF', { blur: 14, oy: 3 });
    drawText(cigs,     P.cigarettes.x, P.cigarettes.y, `400 ${P.cigarettes.s}px Anton, Impact, sans-serif`, '#FF3B30', { color: 'rgba(0,0,0,0.6)', blur: 10, oy: 2 });
  }

  React.useEffect(() => { renderCard(cardBg); }, [cardBg, results.totalSpent, results.sp500Value, results.totalCigs]);

  function fallbackDownload() {
    const a = document.createElement('a');
    a.download = 'smokeloss-report.png';
    a.href = canvasRef.current.toDataURL('image/png');
    a.click();
  }

  async function download() {
    const offscreen = document.createElement('canvas');
    await renderCard(cardBg, offscreen);
    const a = document.createElement('a');
    a.download = 'smokeloss-report.png';
    a.href = offscreen.toDataURL('image/png');
    a.click();
  }

  async function share() {
    // Render into a detached offscreen canvas — avoids display-canvas compositing issues
    const offscreen = document.createElement('canvas');
    await renderCard(cardBg, offscreen);

    function downloadFrom(c) {
      const a = document.createElement('a');
      a.download = 'smokeloss-report.png';
      a.href = c.toDataURL('image/png');
      a.click();
    }

    offscreen.toBlob(async blob => {
      if (!blob) { downloadFrom(offscreen); return; }
      const file = new File([blob], 'smokeloss-report.png', { type: 'image/png' });
      if (navigator.canShare && navigator.canShare({ files: [file] })) {
        try {
          await navigator.share({
            files: [file],
            title: 'My SmokeLoss Report',
            text: 'I calculated how much I\'ve spent on cigarettes — and what it could have been worth. Check yours 👇 https://smokeloss.com',
          });
        } catch (e) {
          if (e.name !== 'AbortError') downloadFrom(offscreen);
        }
      } else {
        downloadFrom(offscreen);
      }
    }, 'image/png');
  }

  return (
    <div style={{ marginBottom: 14 }}>
      {/* Row 1 — label + brand switcher */}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 8, flexWrap: 'wrap' }}>
        <span style={{ fontSize: 11, color: t.sectionLabel, textTransform: 'uppercase', letterSpacing: '0.07em' }}>
          Your Report Card
        </span>
        <div style={{ flex: 1 }} />
        {[['porsche', 'Porsche 911'], ['tesla', 'Tesla Model 3']].map(([brand, label]) => {
          const id     = brand + 'M';
          const active = cardBg === brand || cardBg === brand + 'M';
          return (
            <button key={brand} onClick={() => setCardBg(id)} style={{
              padding: '4px 14px', borderRadius: 20, cursor: 'pointer',
              fontSize: 11, fontWeight: 500, fontFamily: "'DM Sans', sans-serif",
              border: `1px solid ${active ? t.primary : t.border}`,
              background: active ? t.activeBg : 'transparent',
              color: active ? t.activeText : t.textMuted
            }}>{label}</button>
          );
        })}
      </div>

      {/* Row 2 — action buttons */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 10 }}>
        <button onClick={download} style={{
          padding: '6px 18px', borderRadius: 20, cursor: 'pointer',
          fontSize: 11, fontWeight: 500, fontFamily: "'DM Sans', sans-serif",
          border: `1px solid ${t.border}`,
          background: 'transparent', color: t.textMuted
        }}>⬇ Download</button>
        <button onClick={share} style={{
          padding: '6px 18px', borderRadius: 20, cursor: 'pointer',
          fontSize: 11, fontWeight: 600, fontFamily: "'DM Sans', sans-serif",
          border: `1px solid ${t.primary}`,
          background: t.primary, color: '#fff'
        }}>↗ Share</button>
      </div>

      {/* Canvas */}
      <canvas ref={canvasRef} style={{
        maxHeight: 750, width: 'auto', maxWidth: '100%',
        borderRadius: 10, boxShadow: '0 12px 40px rgba(0,0,0,0.35)', display: 'block'
      }} />
    </div>
  );
}

// ── App ───────────────────────────────────────────────────────────────────────

function App() {
  const [isDark,     setIsDark]     = useState(true);
  const [startYear,  setStartYear]  = useState(2000);
  const [cigsPerDay, setCigsPerDay] = useState(20);
  // ARCHIVED: const [activeTab, setActiveTab] = useState('sp500'); // gold toggle state

  const t       = THEMES[isDark ? 'dark' : 'light'];
  const results = useMemo(() => calculateResults(startYear, cigsPerDay), [startYear, cigsPerDay]);
  const roast   = getRoast(results.totalSpent);

  const investmentBudget = results.sp500Value;
  // ARCHIVED: const investmentBudget = activeTab === 'gold' ? results.goldValue : results.sp500Value;

  return (
    <div style={{
      background: t.bg, minHeight: '100vh',
      color: t.textPrimary, fontFamily: "'DM Sans', sans-serif",
      padding: '0 0 60px'
    }}>
      <style>{`
        body { background: ${t.bg}; }
        input[type=number]::-webkit-inner-spin-button,
        input[type=number]::-webkit-outer-spin-button { opacity: 0.4; }
        @media (max-width: 767px) {
          .sl-layout      { flex-direction: column !important; }
          .sl-sidebar     { width: 100% !important; border-right: none !important; border-bottom: 1px solid ${t.border} !important; }
          .sl-nav-links   { display: none !important; }
          .sl-assets      { grid-template-columns: repeat(2, 1fr) !important; }
          .sl-invest-row  { flex-wrap: wrap !important; gap: 8px !important; }
          .sl-invest-big  { font-size: 30px !important; }
          .sl-stat-card   { min-width: 90px !important; }
          input[type=range] { height: 44px !important; top: -19px !important; }
          .sl-label  { font-size: 15px !important; }
          .sl-hint   { font-size: 16px !important; }
          .sl-xs     { font-size: 14px !important; min-width: 56px !important; }
        }
      `}</style>

      {/* ── Nav ── */}
      <div style={{ borderBottom: `1px solid ${t.border}`, background: t.panelBg }}>
        <div style={{ display: 'flex', alignItems: 'center', height: 52, padding: '0 24px', gap: 24 }}>
          <a href="./" style={{ fontSize: 16, fontWeight: 700, color: t.primary, textDecoration: 'none', letterSpacing: '-0.01em' }}>
            SmokeLoss
          </a>
          <div className="sl-nav-links" style={{ display: 'flex', gap: 24 }}>
            {[
              { label: 'Calculator', href: './', active: true },
              { label: 'About',      href: 'about' },
              { label: 'FAQ',        href: 'faq' },
              { label: 'Privacy',    href: 'privacy' },
            ].map(({ label, href, active }) => (
              <a key={href} href={href} style={{
                fontSize: 14, textDecoration: 'none',
                color: active ? t.primary : t.textSecondary,
                fontWeight: active ? 500 : 400
              }}
                onMouseOver={e => e.target.style.color = t.primary}
                onMouseOut={e => e.target.style.color = active ? t.primary : t.textSecondary}
              >{label}</a>
            ))}
          </div>

          <div style={{ flex: 1 }} />

          <button
            onClick={() => setIsDark(d => !d)}
            style={{
              padding: '5px 14px', borderRadius: 20, cursor: 'pointer',
              border: `1px solid ${t.toggleBorder}`,
              background: t.toggleBg, color: t.toggleText,
              fontSize: 12, fontFamily: "'DM Sans', sans-serif",
              fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6
            }}
          >
            <span style={{
              display: 'inline-block', width: 10, height: 10, borderRadius: '50%',
              background: isDark ? '#FB923C' : '#EA580C',
              boxShadow: isDark ? '0 0 6px #FB923C' : '0 0 6px #EA580C'
            }} />
            {isDark ? 'Light mode' : 'Dark mode'}
          </button>
        </div>
      </div>

      {/* ── Two-column layout ── */}
      <div style={{ display: 'flex', flexWrap: 'wrap' }} className="sl-layout">

        {/* ── Left: Inputs ── */}
        <div className="sl-sidebar" style={{
          width: 284, flexShrink: 0,
          padding: '22px 20px',
          borderRight: `1px solid ${t.border}`,
          background: t.panelBg
        }}>
          <p className="sl-label" style={{ fontSize: 11, color: t.sectionLabel, textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 18 }}>
            Your smoking history
          </p>

          <Slider
            label="I started smoking in"
            value={startYear}
            min={1945}
            max={2024}
            onChange={setStartYear}
            hint={`${CURRENT_YEAR - startYear} years of smoking`}
            theme={t}
          />

          <Slider
            label="Cigarettes per day"
            value={cigsPerDay}
            min={1}
            max={60}
            unit="cigs"
            onChange={setCigsPerDay}
            hint={`~${((cigsPerDay / 20) * PACK_PRICES[Math.min(startYear, 2024)] * 365).toFixed(0)} in ${startYear} · ~${((cigsPerDay / 20) * PACK_PRICES[2024] * 365).toFixed(0)} in 2024`}
            theme={t}
          />

          <div style={{
            marginTop: 16, padding: '12px 14px',
            background: t.burnBg, border: `1px solid ${t.burnBorder}`,
            borderRadius: 10
          }}>
            <div style={{ fontSize: 22, fontWeight: 700, fontFamily: "'DM Mono', monospace", color: t.burnText, lineHeight: 1 }}>
              {fmt(results.totalSpent)}
            </div>
            <div className="sl-hint" style={{ fontSize: 12, color: t.textSecondary, marginTop: 4 }}>total spent on cigarettes</div>
            <div className="sl-hint" style={{ fontSize: 12, color: t.burnText, marginTop: 6, fontWeight: 500, lineHeight: 1.4 }}>
              {roast}
            </div>
          </div>

          <p className="sl-label" style={{ fontSize: 11, color: t.textMuted, marginTop: 14, lineHeight: 1.6 }}>
            Using US average pack prices 1964–2024. 20 cigarettes per pack.
          </p>
        </div>

        {/* ── Right: Results ── */}
        <div style={{ flex: 1, minWidth: 0, padding: '22px 20px', background: t.bg }}>

          {/* Report card + stats side by side on desktop */}
          <div className="sl-card-layout">
            <ShareCard results={results} theme={t} />
            <div className="sl-card-right">
              {/* Fun stats */}
              <FunStats results={results} theme={t} />

              {/* Investment panel */}
              <InvestmentPanel results={results} theme={t} />

              {/* Health risk */}
              <HealthRisk packYears={results.packYears} theme={t} />
            </div>
          </div>

          {/* Asset gallery */}
          <div style={{ marginBottom: 14 }}>
            <p style={{ fontSize: 11, color: t.sectionLabel, textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 10 }}>
              What your S&amp;P 500 portfolio could buy today
            </p>
            <div
              className="sl-assets"
              style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}
            >
              {ASSETS.map(asset => (
                <AssetCard key={asset.id} asset={asset} budget={investmentBudget} theme={t} />
              ))}
            </div>
          </div>

          {/* Cross-links */}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 10 }}>
            <a
              href="https://buymeacoffee.com/Wolfy82"
              target="_blank" rel="noopener noreferrer"
              style={{
                fontSize: 12, color: t.textMuted, textDecoration: 'none',
                padding: '5px 12px', borderRadius: 6, border: `1px solid ${t.border}`,
                display: 'flex', alignItems: 'center', gap: 5
              }}
            >☕ Buy me a coffee</a>
            <a
              href="https://inresrisk.com"
              style={{
                fontSize: 12, color: t.textMuted, textDecoration: 'none',
                padding: '5px 12px', borderRadius: 6, border: `1px solid ${t.border}`,
                display: 'flex', alignItems: 'center', gap: 5
              }}
            >→ Check your insulin resistance risk on InResRisk</a>
          </div>

          <p style={{ fontSize: 11, color: t.disclaimer, lineHeight: 1.6 }}>
            Investment values are illustrative. Past S&amp;P 500 returns do not guarantee future results. No taxes, fees, or inflation adjustments applied. Not financial advice.
          </p>
        </div>
      </div>

      {/* ── SEO / Content section ── */}
      <div style={{ maxWidth: 760, margin: '0 auto', padding: '56px 24px 0' }}>

        <h1 style={{ fontSize: 26, fontWeight: 700, color: t.textPrimary, letterSpacing: '-0.02em', marginBottom: 10, lineHeight: 1.3 }}>
          How Much Money Have You Spent on Cigarettes?
        </h1>
        <p style={{ fontSize: 15, color: t.textSecondary, marginBottom: 28, lineHeight: 1.8 }}>
          Most smokers never add it up. SmokeLoss uses actual US cigarette price data going back to 1964
          to calculate the exact amount you've spent on cigarettes — then shows you what that same money
          would be worth today if you'd put it in the S&amp;P 500 or gold instead. The numbers are often shocking.
        </p>

        <h2 style={{ fontSize: 19, fontWeight: 700, color: t.textPrimary, marginBottom: 14, letterSpacing: '-0.01em' }}>
          Why cigarette prices jumped so much around 2000
        </h2>
        <p style={{ fontSize: 15, color: t.textSecondary, lineHeight: 1.8, marginBottom: 24 }}>
          In November 1998, the four largest US tobacco companies signed the <strong style={{ color: t.textPrimary }}>Master Settlement Agreement (MSA)</strong> with 46 state attorneys general.
          The companies agreed to pay states hundreds of billions of dollars over 25 years to cover smoking-related
          healthcare costs. They passed this cost straight to consumers. Average US pack prices more than doubled
          between 1997 ($1.77) and 2001 ($3.91) — and have kept climbing with federal and state excise tax increases ever since.
        </p>

        <h2 style={{ fontSize: 19, fontWeight: 700, color: t.textPrimary, marginBottom: 14, letterSpacing: '-0.01em' }}>
          How the S&amp;P 500 calculation works
        </h2>
        <p style={{ fontSize: 15, color: t.textSecondary, lineHeight: 1.8, marginBottom: 12 }}>
          We assume you invest your annual cigarette budget at the start of each calendar year and apply
          that year's actual S&amp;P 500 <strong style={{ color: t.textPrimary }}>total return</strong> (price appreciation + dividends reinvested).
          We use real historical data for every year from 1964 through 2024 — including the brutal bear markets
          of 1974 (−26.5%), 2002 (−22.1%), and 2008 (−37.0%). The portfolio compounds year over year.
        </p>
        <p style={{ fontSize: 15, color: t.textSecondary, lineHeight: 1.8, marginBottom: 24 }}>
          This is a simplified model. It does not account for capital gains taxes on investment returns,
          brokerage fees, or the psychological difficulty of holding through market crashes. Monthly
          investing (dollar-cost averaging) would change the result slightly. But the order of magnitude
          is accurate, and the point stands: compounding returns over decades are powerful, and cigarettes
          are an exceptionally expensive alternative.
        </p>

        {/* FAQ */}
        <h2 style={{ fontSize: 19, fontWeight: 700, color: t.textPrimary, marginBottom: 22, letterSpacing: '-0.01em' }}>
          Frequently asked questions
        </h2>

        {[
          {
            q: "How much does the average smoker spend on cigarettes per year?",
            a: "The average American smoker consumes about 14 cigarettes per day. At the 2024 US average pack price of $8.24 (for a 20-cigarette pack), that works out to roughly $2,100 per year — or about $175 a month. A pack-a-day habit runs to around $3,010 per year in 2024. SmokeLoss lets you adjust for your actual daily cigarette count."
          },
          {
            q: "How accurate are the cigarette prices?",
            a: "We use US national average retail prices based on CDC tobacco reports and Bureau of Labor Statistics Consumer Price Index data. These are the all-in retail prices consumers paid, including federal, state, and local excise taxes as well as the MSA surcharge added in 2000. State-level prices vary significantly — New York averages over $12/pack while some Southern states are under $6. Our national averages are a reasonable middle ground."
          },
          {
            q: "What does 'if invested in S&P 500' actually mean?",
            a: "We assume you invest your annual cigarette spending in a total-market S&P 500 index fund at the start of each year and hold it until today. We apply actual historical annual total returns (including dividends) for every year from 1964 to 2024. The result compounds automatically — gains from earlier years grow for longer. We don't model taxes on gains, fund expense ratios, or inflation — this is illustrative, not a financial plan."
          },
          {
            q: "Why do pack prices jump so dramatically around 2000?",
            a: "The 1998 Master Settlement Agreement between tobacco companies and 46 states required tobacco companies to pay states approximately $246 billion over 25 years. The companies passed this cost directly to consumers. Average US pack prices jumped from about $1.77 in 1997 to $3.73 by 2000 and $3.91 by 2001 — more than doubling in three years. Federal excise taxes and state-level increases have pushed prices further every decade since."
          },
          {
            q: "What gold price is used?",
            a: "We accumulate ounces of gold at each year's historical annual average price (LBMA data), then value your total holdings at the current gold spot price of approximately $3,300/troy oz (June 2025). Gold has been near all-time highs in 2025, which makes the gold alternative look particularly good for people who smoked for many decades."
          },
          {
            q: "How many cigarettes are in a pack?",
            a: "The standard US cigarette pack contains 20 cigarettes — this is the legal standard and used for all calculations. Some premium brands and European packs contain 25. If you buy cartons, a carton contains 10 packs (200 cigarettes)."
          },
          {
            q: "Does this account for cigarette price differences by state?",
            a: "No — we use US national averages. State excise taxes add significant variation: New Yorkers pay some of the highest prices in the country (over $12/pack) while Missouri, Georgia, and Virginia smokers pay some of the lowest (under $6/pack). Your actual spend may be meaningfully higher or lower depending on where you live and smoked."
          },
          {
            q: "How is the 'days spent smoking' calculated?",
            a: "Research estimates the average cigarette takes about 7 minutes to smoke from first puff to end. We multiply your total cigarette count by 7 minutes and convert to days. This represents time physically spent smoking — not time affected by nicotine or health impacts, which is far greater."
          },
        ].map(({ q, a }) => (
          <div key={q} style={{ padding: '20px 0', borderTop: `1px solid ${t.border}` }}>
            <h3 style={{ fontSize: 15, fontWeight: 600, color: t.textPrimary, marginBottom: 10, lineHeight: 1.45 }}>{q}</h3>
            <p style={{ fontSize: 15, color: t.textSecondary, lineHeight: 1.85, margin: 0 }}>{a}</p>
          </div>
        ))}

        {/* Historical price reference table */}
        <div style={{ borderTop: `1px solid ${t.border}`, paddingTop: 28, marginTop: 0 }}>
          <h2 style={{ fontSize: 19, fontWeight: 700, color: t.textPrimary, marginBottom: 18, letterSpacing: '-0.01em' }}>
            US average cigarette pack price by decade
          </h2>
          <div style={{ overflowX: 'auto', marginBottom: 32 }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr>
                  {['Year', 'Avg Price / Pack', 'Annual cost (1 pack/day)', 'Key event'].map(h => (
                    <th key={h} style={{
                      background: t.panelBg, color: t.textMuted,
                      fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em',
                      padding: '8px 12px', border: `1px solid ${t.border}`,
                      textAlign: 'left', fontWeight: 600
                    }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {[
                  { year: '1964', price: '$0.27', annual: '$99',    note: 'Surgeon General first report on smoking' },
                  { year: '1970', price: '$0.35', annual: '$128',   note: 'TV cigarette ad ban takes effect' },
                  { year: '1980', price: '$0.63', annual: '$230',   note: 'Cigarette warning labels updated' },
                  { year: '1990', price: '$1.58', annual: '$577',   note: 'Federal excise tax increases begin' },
                  { year: '1998', price: '$1.86', annual: '$679',   note: 'MSA signed' },
                  { year: '2000', price: '$3.73', annual: '$1,361', note: 'MSA costs passed to consumers' },
                  { year: '2010', price: '$5.54', annual: '$2,022', note: 'FSPTCA federal regulation begins' },
                  { year: '2020', price: '$6.65', annual: '$2,427', note: 'COVID + state tax hikes' },
                  { year: '2024', price: '$8.24', annual: '$3,008', note: 'Record US average price' },
                ].map(row => (
                  <tr key={row.year} style={{ background: t.cardBg }}>
                    <td style={{ padding: '8px 12px', border: `1px solid ${t.border}`, color: t.textPrimary, fontWeight: 600, fontFamily: "'DM Mono', monospace" }}>{row.year}</td>
                    <td style={{ padding: '8px 12px', border: `1px solid ${t.border}`, color: t.burnText, fontWeight: 600, fontFamily: "'DM Mono', monospace" }}>{row.price}</td>
                    <td style={{ padding: '8px 12px', border: `1px solid ${t.border}`, color: t.textPrimary, fontFamily: "'DM Mono', monospace" }}>{row.annual}</td>
                    <td style={{ padding: '8px 12px', border: `1px solid ${t.border}`, color: t.textSecondary, fontSize: 12 }}>{row.note}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Data sources */}
        <div style={{ borderTop: `1px solid ${t.border}`, paddingTop: 20 }}>
          <p style={{ fontSize: 11, color: t.textMuted, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10 }}>
            Data sources
          </p>
          {[
            'CDC Office on Smoking and Health — Cigarette Brand Preference and Price Monitoring data',
            'Bureau of Labor Statistics — Consumer Price Index for Tobacco and Smoking Products',
            'Orzechowski & Walker — The Tax Burden on Tobacco (annual historical series)',
            'S&P 500 annual total returns: Bloomberg, Macrotrends (1964–2024)',
            'Gold prices: London Bullion Market Association (LBMA) annual averages (1964–2024)',
            'Current gold spot price: ~$3,300/troy oz (June 2025)',
            'MSA pricing: National Association of Attorneys General records',
          ].map(ref => (
            <p key={ref} style={{ fontSize: 12, color: t.textMuted, lineHeight: 1.7, marginBottom: 5 }}>{ref}</p>
          ))}
        </div>

      </div>

      {/* ── Footer ── */}
      <div style={{
        maxWidth: 760, margin: '0 auto', padding: '24px 24px 40px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        flexWrap: 'wrap', gap: 12
      }}>
        <span style={{ fontSize: 13, color: t.textMuted }}>© {new Date().getFullYear()} SmokeLoss — All rights reserved <span style={{ opacity: 0.5 }}>{VERSION}</span></span>
        <div style={{ display: 'flex', gap: 20 }}>
          {[
            { label: 'About',          href: 'about' },
            { label: 'FAQ',            href: 'faq' },
            { label: 'Privacy Policy', href: 'privacy' },
            { label: 'InResRisk',      href: 'https://inresrisk.com' },
          ].map(({ label, href }) => (
            <a key={href} href={href} style={{ fontSize: 13, color: t.textMuted, textDecoration: 'none' }}
              onMouseOver={e => e.target.style.color = t.primary}
              onMouseOut={e => e.target.style.color = t.textMuted}
            >{label}</a>
          ))}
        </div>
      </div>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
