// TearSheet.jsx — "Position Tear Sheet" — personalised financial document.
// Visitor enters 5 numbers + name. Site renders an on-brand tear sheet on the
// page in real-time. Downloadable as PNG (html-to-image).

// Industry benchmark CPL bands — used to compute DP's "target" CPL and to
// position the visitor on the distribution chart.
const INDUSTRY_BENCH = {
  'Healthcare':         { lo:  800, mid: 1200, hi: 1800, name: 'Healthcare clinics' },
  'Real-estate':        { lo: 2000, mid: 2800, hi: 4200, name: 'Real-estate brokers' },
  'Coaching':           { lo:  450, mid:  700, hi: 1000, name: 'Coaching & education' },
  'B2B services':       { lo: 2500, mid: 3800, hi: 5500, name: 'B2B services / D2C' },
  'Other':              { lo: 1200, mid: 2200, hi: 3800, name: 'Other' },
};

// Verdict logic.
function computeVerdict({ spend, cpl, closeRate, ticket, industry }) {
  const bench = INDUSTRY_BENCH[industry] || INDUSTRY_BENCH['Other'];
  const leads = spend / cpl;
  const customers = leads * (closeRate / 100);
  const revenue = customers * ticket;
  const roas = revenue / spend;

  // DP's target CPL — what they'd aim for after 6 weeks.
  // If current is above benchmark hi, target the benchmark mid. Otherwise hold the floor.
  const targetCpl = cpl > bench.hi ? bench.mid : Math.max(bench.lo, Math.round(cpl * 0.65));
  const targetLeads = Math.round(spend / targetCpl);
  const targetCustomers = targetLeads * (closeRate / 100);
  const targetRevenue = targetCustomers * ticket;
  const targetRoas = targetRevenue / spend;
  const lift = (targetRoas / roas - 1) * 100;

  // Reasoning — find the dominant weakness.
  const notes = [];
  if (cpl > bench.hi * 1.5) {
    notes.push(`CPL is ${((cpl / bench.mid - 1) * 100).toFixed(0)}% above ${bench.name} benchmark. Likely cause: wrong geo radius or stale creative.`);
  } else if (cpl > bench.hi) {
    notes.push(`CPL is high for ${bench.name}. Tight geography + a single-hook test should pull it down.`);
  } else if (cpl < bench.lo) {
    notes.push(`CPL is below benchmark — make sure lead quality holds before scaling.`);
  } else {
    notes.push(`CPL sits inside the ${bench.name} band. Headroom exists on creative refresh.`);
  }
  if (closeRate < 8) {
    notes.push(`Close rate ${closeRate}% is the binding constraint — fix the funnel before scaling spend.`);
  } else if (closeRate > 25) {
    notes.push(`Close rate ${closeRate}% is unusually strong. Bigger spend should compound cleanly.`);
  } else {
    notes.push(`Close rate ${closeRate}% is workable. Lead quality matters more than volume here.`);
  }
  if (spend < 50000) {
    notes.push(`Spend below ₹50k/mo is too thin to read signal. Get to ₹40k/wk first.`);
  }

  // Verdict.
  let verdict, verdictNote;
  if (spend < 50000) {
    verdict = 'PASS';
    verdictNote = 'Spend is below our floor. Come back when you can deploy ₹50k+/mo.';
  } else if (roas >= 3.5 || (targetRoas >= 4.0 && cpl > bench.lo)) {
    verdict = 'TAKE';
    verdictNote = `Numbers fit our book. Six-week target ROAS ${targetRoas.toFixed(1)}× from ${roas.toFixed(1)}×.`;
  } else if (roas >= 2.0 || targetRoas >= 2.5) {
    verdict = 'MARGINAL';
    verdictNote = `Fixable but tight. We'd want a 30-min look at the funnel before agreeing.`;
  } else {
    verdict = 'PASS';
    verdictNote = `Even after a CPL cut, the unit economics don't clear. Fix offer or pricing first.`;
  }

  return { leads, customers, revenue, roas, targetCpl, targetLeads, targetCustomers, targetRevenue, targetRoas, lift, notes, verdict, verdictNote, bench };
}

const VERDICT_COLORS = {
  TAKE:     { fg: 'var(--vault-700)', bg: 'var(--vault-50)',   accent: 'var(--vault-500)' },
  MARGINAL: { fg: 'var(--ink-1000)',  bg: 'var(--powder-50)',  accent: 'var(--powder-500)' },
  PASS:     { fg: 'var(--loss-700)',  bg: 'var(--loss-100)',   accent: 'var(--loss-500)' },
};

const tsStyles = {
  section: { padding: '96px 0', borderTop: '1px solid var(--border)' },
  container: { maxWidth: 'var(--container-max)', margin: '0 auto', padding: '0 var(--container-pad)' },
  head: { display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 64, alignItems: 'end', marginBottom: 48 },
  eyebrow: { fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--fg-muted)', fontWeight: 500, marginBottom: 12 },
  h: {
    fontFamily: 'var(--font-display)', fontWeight: 400,
    fontSize: 'clamp(36px, 5vw, 60px)',
    lineHeight: 0.92, letterSpacing: '-0.015em',
    textTransform: 'uppercase', margin: 0, maxWidth: '14ch',
  },
  sub: { fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.55, color: 'var(--fg-muted)', maxWidth: '46ch', margin: 0, paddingBottom: 6 },

  wrap: { display: 'grid', gridTemplateColumns: '1fr 1.5fr', gap: 24, alignItems: 'start' },

  // Form
  form: {
    background: 'var(--bg-elevated)',
    border: '1px solid var(--border)',
    borderRadius: 'var(--r-md)',
    padding: '24px 26px',
    position: 'sticky',
    top: 80,
  },
  formTitle: { fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 16, marginBottom: 6 },
  formSub: { fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--fg-muted)', marginBottom: 20 },
  fld: { display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 },
  label: { fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--fg-muted)', fontWeight: 500 },
  input: { fontFamily: 'var(--font-sans)', fontSize: 14, padding: '10px 12px', background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', color: 'var(--fg)', outline: 'none' },
  inputRow: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 },
  submitBtn: {
    fontFamily: 'var(--font-sans)', fontWeight: 500, fontSize: 14,
    padding: '12px 16px', background: 'var(--ink-1000)', color: 'var(--ink-0)',
    border: 'none', borderRadius: 'var(--r-md)', cursor: 'pointer',
    width: '100%', marginTop: 8,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
  },

  // Sheet
  sheetWrap: { position: 'relative' },
  actionBar: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    marginBottom: 14,
    fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em',
    color: 'var(--fg-muted)', textTransform: 'uppercase',
  },
  downloadBtn: {
    fontFamily: 'var(--font-sans)', fontWeight: 500, fontSize: 12,
    padding: '8px 12px', background: 'transparent', color: 'var(--ink-1000)',
    border: '1px solid var(--border-strong)', borderRadius: 'var(--r-md)',
    cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
    textTransform: 'none', letterSpacing: 0,
  },

  // Sheet visuals
  sheet: {
    background: 'var(--bg-elevated)',
    border: '1px solid var(--ink-1000)',
    borderRadius: 0,
    overflow: 'hidden',
    boxShadow: 'var(--shadow-lg)',
  },
  sheetTopBar: {
    background: 'var(--ink-1000)',
    color: 'var(--ink-0)',
    padding: '14px 28px',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em',
    textTransform: 'uppercase',
  },
  sheetBody: { padding: '28px 28px 24px' },
  subjectRow: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
    paddingBottom: 22,
    borderBottom: '1px solid var(--ink-1000)',
    marginBottom: 22,
    gap: 24, flexWrap: 'wrap',
  },
  subjectName: { fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 32, lineHeight: 1, textTransform: 'uppercase', letterSpacing: '-0.015em', marginBottom: 4 },
  subjectMeta: { fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.12em', color: 'var(--fg-muted)', textTransform: 'uppercase' },
  refBlock: { textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', color: 'var(--fg-muted)', textTransform: 'uppercase', lineHeight: 1.6 },
  refNum: { color: 'var(--ink-1000)', fontWeight: 600, fontSize: 11 },

  // Sections of the sheet
  sec: { marginBottom: 22 },
  secH: { fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--fg-muted)', fontWeight: 500, paddingBottom: 8, borderBottom: '1px solid var(--border)', marginBottom: 10 },
  kvGrid: { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, borderTop: '1px solid var(--border)' },
  kvTile: {
    padding: '12px 14px',
    borderRight: '1px solid var(--border)',
    borderBottom: '1px solid var(--border)',
  },
  kvLabel: { fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--fg-muted)' },
  kvVal: { fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums', fontSize: 18, color: 'var(--ink-1000)', marginTop: 4 },

  // Verdict block
  verdictBlock: (v) => ({
    display: 'grid', gridTemplateColumns: '160px 1fr', gap: 18,
    padding: '18px 20px',
    background: VERDICT_COLORS[v].bg,
    border: '1px solid ' + VERDICT_COLORS[v].accent,
    borderRadius: 'var(--r-sm)',
    margin: '6px 0 22px',
  }),
  verdictWord: (v) => ({
    fontFamily: 'var(--font-display)', fontWeight: 400,
    fontSize: 48, lineHeight: 1, textTransform: 'uppercase',
    letterSpacing: '-0.02em',
    color: VERDICT_COLORS[v].fg,
  }),
  verdictTag: { fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.14em', color: 'var(--fg-muted)', textTransform: 'uppercase', marginBottom: 4 },
  verdictNote: { fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--ink-1000)', lineHeight: 1.5, marginTop: 8, fontWeight: 500 },
  verdictNotes: { listStyle: 'none', padding: 0, margin: '10px 0 0' },
  verdictLi: { fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.5, paddingLeft: 14, position: 'relative', marginBottom: 4 },
  verdictBullet: { position: 'absolute', left: 0, top: 0, color: VERDICT_COLORS.MARGINAL.accent },

  // Plan section — projection
  projRow: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 },
  projL: {},
  projR: {},
  projLabel: { fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--fg-muted)', marginBottom: 6 },
  projBig: { fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums', fontSize: 28, color: 'var(--ink-1000)', letterSpacing: '-0.015em' },
  projDelta: { fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--vault-500)', marginTop: 2, letterSpacing: '0.06em' },

  footer: {
    marginTop: 22,
    paddingTop: 14,
    borderTop: '1px solid var(--border)',
    fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.14em',
    textTransform: 'uppercase', color: 'var(--fg-faint)',
    display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12,
  },

  // Empty state
  empty: {
    background: 'var(--bg-elevated)',
    border: '1px dashed var(--border-strong)',
    borderRadius: 'var(--r-md)',
    padding: '64px 32px',
    textAlign: 'center',
    color: 'var(--fg-muted)',
    fontFamily: 'var(--font-sans)',
    minHeight: 360,
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 10,
  },
  emptyMark: { color: 'var(--powder-500)', fontFamily: 'var(--font-display)', fontSize: 48, lineHeight: 1 },
  emptyTitle: { fontFamily: 'var(--font-display)', fontSize: 22, textTransform: 'uppercase', color: 'var(--ink-1000)', letterSpacing: '-0.01em' },
  emptySub: { fontSize: 14, maxWidth: '36ch', textWrap: 'pretty' },
};

const fmtINR = (n) => '₹' + Math.round(n).toLocaleString('en-IN');
const fmtINRcompact = (n) => {
  if (n >= 1e7) return '₹' + (n/1e7).toFixed(2) + ' Cr';
  if (n >= 1e5) return '₹' + (n/1e5).toFixed(1) + ' L';
  if (n >= 1000) return '₹' + (n/1000).toFixed(0) + 'k';
  return '₹' + Math.round(n).toLocaleString('en-IN');
};

// Distribution chart — visitor's CPL plotted against the industry band.
function DistChart({ cpl, bench }) {
  const W = 360, H = 56;
  // X-axis: 0 to bench.hi * 2 (cap to fit visitor's CPL if it's higher).
  const xMax = Math.max(bench.hi * 2, cpl * 1.15);
  const x = v => (v / xMax) * W;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{width:'100%', height: 'auto', display: 'block'}}>
      {/* Bench band */}
      <rect x={x(bench.lo)} y="18" width={x(bench.hi) - x(bench.lo)} height="20" fill="var(--vault-100)" />
      {/* Mid line */}
      <line x1={x(bench.mid)} y1="14" x2={x(bench.mid)} y2="42" stroke="var(--vault-500)" strokeWidth="1.5" />
      {/* Axis */}
      <line x1="0" y1="38" x2={W} y2="38" stroke="var(--border-strong)" strokeWidth="0.5" />
      {/* Ticks */}
      {[bench.lo, bench.mid, bench.hi].map((t, i) => (
        <g key={i}>
          <line x1={x(t)} y1="38" x2={x(t)} y2="42" stroke="var(--border-strong)" strokeWidth="0.5"/>
          <text x={x(t)} y="52" fontSize="8" fill="var(--fg-muted)" fontFamily="JetBrains Mono" textAnchor="middle">
            {t >= 1000 ? `₹${(t/1000).toFixed(1)}k` : `₹${t}`}
          </text>
        </g>
      ))}
      {/* Visitor's dot */}
      <circle cx={x(cpl)} cy="28" r="6" fill="var(--powder-500)"/>
      <circle cx={x(cpl)} cy="28" r="10" fill="none" stroke="var(--powder-500)" strokeWidth="1" opacity="0.5"/>
      <text x={x(cpl)} y="12" fontSize="9" fill="var(--ink-1000)" fontFamily="JetBrains Mono" textAnchor="middle" fontWeight="600">
        YOU · ₹{cpl.toLocaleString('en-IN')}
      </text>
    </svg>
  );
}

// 6-week CPL projection chart — current CPL decays toward target CPL.
function ProjectionChart({ cpl, targetCpl }) {
  const W = 360, H = 90;
  const weeks = 7; // week 0 to week 6
  const pad = 8;
  const xs = (i) => pad + ((W - pad * 2) * i / (weeks - 1));
  const ys = (v) => {
    const yMax = Math.max(cpl, targetCpl) * 1.1;
    return H - pad - ((v / yMax) * (H - pad * 2));
  };
  // Decay curve: cpl -> targetCpl with two-step pattern (faster early)
  const points = Array.from({length: weeks}, (_, i) => {
    const t = i / (weeks - 1);
    const eased = 1 - Math.pow(1 - t, 1.6);
    return cpl + (targetCpl - cpl) * eased;
  });
  const pathD = points.map((p, i) => `${i===0?'M':'L'} ${xs(i)} ${ys(p)}`).join(' ');
  const areaD = pathD + ` L ${xs(weeks-1)} ${H - pad} L ${xs(0)} ${H - pad} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{width:'100%', height:'auto', display:'block'}}>
      {/* Grid */}
      {[0, 0.5, 1].map((t, i) => {
        const yMax = Math.max(cpl, targetCpl) * 1.1;
        const v = yMax * (1 - t);
        return <line key={i} x1={pad} x2={W-pad} y1={ys(v)} y2={ys(v)} stroke="var(--border)" strokeWidth="0.5" strokeDasharray="2 3"/>;
      })}
      {/* Area */}
      <path d={areaD} fill="var(--powder-50)" />
      {/* Line */}
      <path d={pathD} fill="none" stroke="var(--powder-500)" strokeWidth="2" />
      {/* Endpoints */}
      <circle cx={xs(0)} cy={ys(cpl)} r="3" fill="var(--ink-1000)"/>
      <circle cx={xs(weeks-1)} cy={ys(targetCpl)} r="3" fill="var(--powder-500)"/>
      {/* Labels */}
      <text x={xs(0)} y={ys(cpl) - 8} fontSize="9" fontFamily="JetBrains Mono" fill="var(--ink-1000)" fontWeight="600">
        ₹{cpl.toLocaleString('en-IN')}
      </text>
      <text x={xs(weeks-1)} y={ys(targetCpl) - 8} fontSize="9" fontFamily="JetBrains Mono" fill="var(--powder-500)" textAnchor="end" fontWeight="600">
        ₹{targetCpl.toLocaleString('en-IN')}
      </text>
      {/* X-axis ticks */}
      {Array.from({length: weeks}, (_, i) => (
        <text key={i} x={xs(i)} y={H - 1} fontSize="8" fontFamily="JetBrains Mono" fill="var(--fg-muted)" textAnchor="middle">
          W{i}
        </text>
      ))}
    </svg>
  );
}

function TearSheet() {
  const [form, setForm] = React.useState({
    name: '',
    business: '',
    industry: 'Healthcare',
    spend: '150000',
    cpl: '2200',
    closeRate: '15',
    ticket: '25000',
  });
  const [result, setResult] = React.useState(null);
  const [downloading, setDownloading] = React.useState(false);
  const sheetRef = React.useRef(null);

  const update = (k, v) => setForm(f => ({...f, [k]: v}));

  const onGenerate = (e) => {
    e.preventDefault();
    const parsed = {
      industry: form.industry,
      spend:     +form.spend     || 0,
      cpl:       +form.cpl       || 0,
      closeRate: +form.closeRate || 0,
      ticket:    +form.ticket    || 0,
    };
    if (parsed.spend && parsed.cpl && parsed.ticket && parsed.closeRate) {
      setResult({
        ...computeVerdict(parsed),
        input: parsed,
        meta: {
          name: form.name || 'Confidential subject',
          business: form.business || '—',
          ref: 'DP-' + Math.floor(Math.random() * 9000 + 1000) + '-2026',
          prepared: new Date().toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }),
        },
      });
      // Scroll the sheet into the viewport on small screens
      setTimeout(() => {
        sheetRef.current && sheetRef.current.scrollIntoView({behavior:'smooth', block:'start'});
      }, 60);
    }
  };

  const onDownload = async () => {
    if (!sheetRef.current || !window.htmlToImage) return;
    setDownloading(true);
    try {
      const dataUrl = await window.htmlToImage.toPng(sheetRef.current, {
        pixelRatio: 2,
        backgroundColor: getComputedStyle(document.body).getPropertyValue('--bg').trim() || '#FAF8F4',
      });
      const link = document.createElement('a');
      link.download = `dry-powder-tear-sheet-${result?.meta?.ref || 'export'}.png`;
      link.href = dataUrl;
      link.click();
    } catch (err) {
      console.error('download failed', err);
    } finally {
      setDownloading(false);
    }
  };

  return (
    <section id="tearsheet" style={tsStyles.section}>
      <div style={tsStyles.container}>
        <div style={tsStyles.head}>
          <div>
            <div style={tsStyles.eyebrow}>07 · Diligence</div>
            <h2 style={tsStyles.h}>The tear sheet we write before saying yes.</h2>
          </div>
          <p style={tsStyles.sub}>
            Plug in your numbers. Get the same one-page document our partners
            stare at on a Monday morning before agreeing to take a client. Yours
            takes 4 seconds.
          </p>
        </div>

        <div style={tsStyles.wrap} data-tearsheet-wrap>
          {/* Form */}
          <form style={tsStyles.form} onSubmit={onGenerate} data-tearsheet-form>
            <div style={tsStyles.formTitle}>Your position</div>
            <div style={tsStyles.formSub}>Nothing is stored. Generates entirely in your browser.</div>

            <div style={tsStyles.inputRow}>
              <div style={tsStyles.fld}>
                <label style={tsStyles.label}>Your name</label>
                <input style={tsStyles.input} value={form.name} onChange={e => update('name', e.target.value)} placeholder="optional"/>
              </div>
              <div style={tsStyles.fld}>
                <label style={tsStyles.label}>Business</label>
                <input style={tsStyles.input} value={form.business} onChange={e => update('business', e.target.value)} placeholder="optional"/>
              </div>
            </div>

            <div style={tsStyles.fld}>
              <label style={tsStyles.label}>Industry</label>
              <select style={tsStyles.input} value={form.industry} onChange={e => update('industry', e.target.value)}>
                {Object.keys(INDUSTRY_BENCH).map(k => <option key={k} value={k}>{INDUSTRY_BENCH[k].name}</option>)}
              </select>
            </div>

            <div style={tsStyles.inputRow}>
              <div style={tsStyles.fld}>
                <label style={tsStyles.label}>Monthly spend (₹)</label>
                <input style={tsStyles.input} type="number" value={form.spend} onChange={e => update('spend', e.target.value)} min="0"/>
              </div>
              <div style={tsStyles.fld}>
                <label style={tsStyles.label}>Current CPL (₹)</label>
                <input style={tsStyles.input} type="number" value={form.cpl} onChange={e => update('cpl', e.target.value)} min="0"/>
              </div>
            </div>
            <div style={tsStyles.inputRow}>
              <div style={tsStyles.fld}>
                <label style={tsStyles.label}>Avg ticket (₹)</label>
                <input style={tsStyles.input} type="number" value={form.ticket} onChange={e => update('ticket', e.target.value)} min="0"/>
              </div>
              <div style={tsStyles.fld}>
                <label style={tsStyles.label}>Close rate (%)</label>
                <input style={tsStyles.input} type="number" value={form.closeRate} onChange={e => update('closeRate', e.target.value)} min="0" max="100"/>
              </div>
            </div>

            <button type="submit" style={tsStyles.submitBtn}>
              <Mark size={13} color="var(--ink-0)"/> Generate tear sheet
            </button>
          </form>

          {/* Sheet */}
          <div style={tsStyles.sheetWrap}>
            {!result ? (
              <div style={tsStyles.empty}>
                <span style={tsStyles.emptyMark}>*</span>
                <div style={tsStyles.emptyTitle}>Awaiting position</div>
                <div style={tsStyles.emptySub}>
                  Fill in the form to the left. Your sheet will be drafted live —
                  with a verdict, a target CPL, and a six-week projection.
                </div>
              </div>
            ) : (
              <>
                <div style={tsStyles.actionBar}>
                  <span>Draft · ref {result.meta.ref}</span>
                  <button style={tsStyles.downloadBtn} onClick={onDownload} disabled={downloading}>
                    {downloading ? 'Rendering…' : 'Save as PNG'} <span aria-hidden="true">↓</span>
                  </button>
                </div>

                <div ref={sheetRef} style={tsStyles.sheet}>
                  <div style={tsStyles.sheetTopBar}>
                    <span>Position tear sheet · Dry Powder</span>
                    <span>Confidential · DP-internal</span>
                  </div>
                  <div style={tsStyles.sheetBody}>
                    <div style={tsStyles.subjectRow}>
                      <div>
                        <div style={tsStyles.subjectName}>{result.meta.name}</div>
                        <div style={tsStyles.subjectMeta}>
                          {result.meta.business} · {result.bench.name}
                        </div>
                      </div>
                      <div style={tsStyles.refBlock}>
                        <div>Ref · <span style={tsStyles.refNum}>{result.meta.ref}</span></div>
                        <div>Prepared · {result.meta.prepared}</div>
                        <div>Author · partners' desk</div>
                      </div>
                    </div>

                    {/* Inputs */}
                    <div style={tsStyles.sec}>
                      <div style={tsStyles.secH}>01 · Current position</div>
                      <div style={tsStyles.kvGrid}>
                        <div style={tsStyles.kvTile}>
                          <div style={tsStyles.kvLabel}>Monthly spend</div>
                          <div style={tsStyles.kvVal}>{fmtINRcompact(result.input.spend)}</div>
                        </div>
                        <div style={tsStyles.kvTile}>
                          <div style={tsStyles.kvLabel}>Current CPL</div>
                          <div style={tsStyles.kvVal}>{fmtINR(result.input.cpl)}</div>
                        </div>
                        <div style={tsStyles.kvTile}>
                          <div style={tsStyles.kvLabel}>Close rate</div>
                          <div style={tsStyles.kvVal}>{result.input.closeRate}%</div>
                        </div>
                        <div style={{...tsStyles.kvTile, borderRight: 'none'}}>
                          <div style={tsStyles.kvLabel}>Avg ticket</div>
                          <div style={tsStyles.kvVal}>{fmtINRcompact(result.input.ticket)}</div>
                        </div>
                        <div style={tsStyles.kvTile}>
                          <div style={tsStyles.kvLabel}>Implied leads / mo</div>
                          <div style={tsStyles.kvVal}>{Math.round(result.leads).toLocaleString('en-IN')}</div>
                        </div>
                        <div style={tsStyles.kvTile}>
                          <div style={tsStyles.kvLabel}>New customers / mo</div>
                          <div style={tsStyles.kvVal}>{Math.round(result.customers).toLocaleString('en-IN')}</div>
                        </div>
                        <div style={tsStyles.kvTile}>
                          <div style={tsStyles.kvLabel}>Revenue / mo</div>
                          <div style={tsStyles.kvVal}>{fmtINRcompact(result.revenue)}</div>
                        </div>
                        <div style={{...tsStyles.kvTile, borderRight: 'none'}}>
                          <div style={tsStyles.kvLabel}>Current ROAS</div>
                          <div style={tsStyles.kvVal}>{result.roas.toFixed(1)}×</div>
                        </div>
                      </div>
                    </div>

                    {/* Where you sit in the book */}
                    <div style={tsStyles.sec}>
                      <div style={tsStyles.secH}>02 · Where you sit · {result.bench.name} CPL distribution</div>
                      <DistChart cpl={result.input.cpl} bench={result.bench}/>
                    </div>

                    {/* Verdict */}
                    <div style={tsStyles.sec}>
                      <div style={tsStyles.secH}>03 · Verdict</div>
                      <div style={tsStyles.verdictBlock(result.verdict)}>
                        <div>
                          <div style={tsStyles.verdictTag}>Our call</div>
                          <div style={tsStyles.verdictWord(result.verdict)}>{result.verdict}</div>
                        </div>
                        <div>
                          <div style={tsStyles.verdictTag}>Reasoning</div>
                          <p style={tsStyles.verdictNote}>{result.verdictNote}</p>
                          <ul style={tsStyles.verdictNotes}>
                            {result.notes.map((n, i) => (
                              <li key={i} style={tsStyles.verdictLi}>
                                <span style={tsStyles.verdictBullet}>·</span>{n}
                              </li>
                            ))}
                          </ul>
                        </div>
                      </div>
                    </div>

                    {/* 6-week plan */}
                    <div style={tsStyles.sec}>
                      <div style={tsStyles.secH}>04 · Six-week plan · CPL trajectory</div>
                      <div style={tsStyles.projRow}>
                        <div style={tsStyles.projL}>
                          <ProjectionChart cpl={result.input.cpl} targetCpl={result.targetCpl}/>
                        </div>
                        <div style={tsStyles.projR}>
                          <div style={tsStyles.projLabel}>Target CPL · week 6</div>
                          <div style={tsStyles.projBig}>{fmtINR(result.targetCpl)}</div>
                          <div style={tsStyles.projDelta}>▼ ₹{(result.input.cpl - result.targetCpl).toLocaleString('en-IN')} · {((1 - result.targetCpl/result.input.cpl) * 100).toFixed(0)}% cut</div>
                          <div style={{...tsStyles.projLabel, marginTop: 16}}>Implied ROAS · post-cut</div>
                          <div style={tsStyles.projBig}>{result.targetRoas.toFixed(1)}×</div>
                          <div style={tsStyles.projDelta}>▲ +{(result.targetRoas - result.roas).toFixed(1)}× · same spend</div>
                        </div>
                      </div>
                    </div>

                    <div style={tsStyles.footer}>
                      <span>Not a contract. Indicative numbers only.</span>
                      <span>* Dry Powder · drypowder.in</span>
                    </div>
                  </div>
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { TearSheet });
