/* global React, Container, Section, Eyebrow, Button, Reveal */
const { useState: useStateRR, useEffect: useEffectRR, useRef: useRefRR, useMemo: useMemoRR } = React;

/* ─── Market config ─── */
const MARKET_CONFIG = {
  india:     { currency: 'INR', symbol: '₹',   minBudget: '5,00,000',  minBudgetNum: 500000,  label: 'India' },
  uae:       { currency: 'AED', symbol: 'AED ', minBudget: '37,000',    minBudgetNum: 37000,   label: 'UAE & GCC' },
  uk:        { currency: 'GBP', symbol: '£',   minBudget: '8,000',     minBudgetNum: 8000,    label: 'United Kingdom' },
  usa:       { currency: 'USD', symbol: '$',   minBudget: '10,000',    minBudgetNum: 10000,   label: 'United States & Canada' },
  australia: { currency: 'AUD', symbol: 'A$',  minBudget: '15,000',    minBudgetNum: 15000,   label: 'Australia & New Zealand' },
  singapore: { currency: 'SGD', symbol: 'S$',  minBudget: '14,000',    minBudgetNum: 14000,   label: 'Singapore & SEA' },
  europe:    { currency: 'EUR', symbol: '€',   minBudget: '9,500',     minBudgetNum: 9500,    label: 'Europe' },
  other:     { currency: 'USD', symbol: '$',   minBudget: '10,000',    minBudgetNum: 10000,   label: 'Global' },
};

const COUNTRY_OPTIONS = [
  { key: 'india',     flag: '🇮🇳', label: 'India' },
  { key: 'uae',       flag: '🇦🇪', label: 'UAE & GCC' },
  { key: 'uk',        flag: '🇬🇧', label: 'United Kingdom' },
  { key: 'usa',       flag: '🇺🇸', label: 'United States & Canada' },
  { key: 'australia', flag: '🇦🇺', label: 'Australia & New Zealand' },
  { key: 'singapore', flag: '🇸🇬', label: 'Singapore & Southeast Asia' },
  { key: 'europe',    flag: '🇪🇺', label: 'Europe' },
  { key: 'other',     flag: '🌍', label: 'Other (defaults to USD)' },
];

const LOADING_STEPS = [
  'Analysing your business profile...',
  'Researching your market & category...',
  'Mapping your ideal customer...',
  'Running unit economics...',
  'Building your 90-day plan...',
  'Compiling your Daee Media brief...',
];

/* ─── Helper sub-components (RR-prefixed) ─── */

function FieldRR({ label, textarea, rows, error, hint, required, ...rest }) {
  const [focus, setFocus] = useStateRR(false);
  const isError = Boolean(error);
  const borderColor = isError ? 'var(--clay-600)' : focus ? 'var(--accent)' : 'var(--border-strong)';
  const shadowColor = isError ? 'var(--clay-600)' : 'var(--accent)';
  const common = {
    fontFamily: 'var(--font-sans)', fontSize: 15, padding: '12px 14px',
    background: 'var(--bg)', border: `1px solid ${borderColor}`,
    borderRadius: 4, color: 'var(--fg)', outline: 'none',
    boxShadow: focus ? `0 0 0 3px color-mix(in srgb, ${shadowColor} 15%, transparent)` : 'none',
    transition: 'border-color 120ms, box-shadow 120ms', resize: 'vertical', width: '100%',
    boxSizing: 'border-box', lineHeight: 1.55,
  };
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontSize: 12, color: 'var(--fg-subtle)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
        {label}{required && <span style={{ color: 'var(--clay-600)', marginLeft: 3 }}>*</span>}
      </span>
      {textarea
        ? <textarea rows={rows || 3} onFocus={() => setFocus(true)} onBlur={e => { setFocus(false); rest.onBlur?.(e); }} style={{ ...common, resize: 'vertical' }} {...rest}/>
        : <input onFocus={() => setFocus(true)} onBlur={e => { setFocus(false); rest.onBlur?.(e); }} style={{ ...common, resize: 'none' }} {...rest}/>}
      {error && <span style={{ fontSize: 12, color: 'var(--clay-600)' }}>{error}</span>}
      {hint && !error && <span style={{ fontSize: 12, color: 'var(--fg-subtle)' }}>{hint}</span>}
    </label>
  );
}

function SelectFieldRR({ label, options, required, error, ...rest }) {
  const [focus, setFocus] = useStateRR(false);
  const isError = Boolean(error);
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontSize: 12, color: 'var(--fg-subtle)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
        {label}{required && <span style={{ color: 'var(--clay-600)', marginLeft: 3 }}>*</span>}
      </span>
      <select onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{
          fontFamily: 'var(--font-sans)', fontSize: 15, padding: '12px 14px',
          background: 'var(--bg)',
          border: `1px solid ${isError ? 'var(--clay-600)' : focus ? 'var(--accent)' : 'var(--border-strong)'}`,
          borderRadius: 4, color: 'var(--fg)', outline: 'none',
          boxShadow: focus ? '0 0 0 3px color-mix(in srgb, var(--accent) 15%, transparent)' : 'none',
          appearance: 'none', width: '100%', boxSizing: 'border-box',
          backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6' fill='none'%3E%3Cpath d='M1 1L5 5L9 1' stroke='%236B6860' stroke-width='1.2'/%3E%3C/svg%3E\")",
          backgroundRepeat: 'no-repeat', backgroundPosition: 'right 16px center',
          transition: 'border-color 120ms, box-shadow 120ms',
        }} {...rest}>
        <option value="">Select one</option>
        {options.map(o => typeof o === 'string'
          ? <option key={o} value={o}>{o}</option>
          : <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
      {error && <span style={{ fontSize: 12, color: 'var(--clay-600)' }}>{error}</span>}
    </label>
  );
}

function ChipToggleRR({ on, onClick, children }) {
  return (
    <button type="button" onClick={onClick} style={{
      fontSize: 13, padding: '8px 14px', borderRadius: 999, cursor: 'pointer',
      background: on ? 'var(--accent)' : 'transparent',
      color: on ? 'var(--accent-fg)' : 'var(--fg-muted)',
      border: `1px solid ${on ? 'var(--accent)' : 'var(--border-strong)'}`,
      fontFamily: 'var(--font-sans)', fontWeight: 500,
      transition: 'all 140ms var(--ease-out)',
    }}>{children}</button>
  );
}

function DotRR({ on }) {
  return <span style={{
    width: 7, height: 7, borderRadius: 999,
    background: on ? 'var(--accent)' : 'var(--border-strong)',
    transition: 'background 180ms', display: 'inline-block',
  }}/>;
}

function RadioCard({ selected, onClick, children }) {
  return (
    <button type="button" onClick={onClick} style={{
      textAlign: 'left', padding: '16px 20px', borderRadius: 4, cursor: 'pointer',
      background: selected ? 'var(--accent)' : 'var(--bg)',
      color: selected ? 'var(--accent-fg)' : 'var(--fg)',
      border: `1.5px solid ${selected ? 'var(--accent)' : 'var(--border-strong)'}`,
      fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 500,
      transition: 'all 140ms var(--ease-out)', width: '100%', boxSizing: 'border-box',
    }}>{children}</button>
  );
}

function CountryCard({ selected, onClick, flag, label }) {
  return (
    <button type="button" onClick={onClick} style={{
      padding: '18px 16px', borderRadius: 4, cursor: 'pointer', textAlign: 'center',
      background: selected ? 'var(--accent)' : 'var(--bg)',
      color: selected ? 'var(--accent-fg)' : 'var(--fg)',
      border: `1.5px solid ${selected ? 'var(--accent)' : 'var(--border-strong)'}`,
      fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500,
      transition: 'all 140ms var(--ease-out)', boxSizing: 'border-box',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
    }}>
      <span style={{ fontSize: 28 }}>{flag}</span>
      <span>{label}</span>
    </button>
  );
}

function StepHeader({ step, total }) {
  if (step < 1) return null;
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 28 }}>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        {Array.from({ length: total }, (_, i) => <DotRR key={i} on={i < step}/>)}
      </div>
      <span style={{ fontSize: 12, color: 'var(--fg-subtle)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
        Step {step} of {total}
      </span>
    </div>
  );
}

function StepTitle({ title, subtitle }) {
  return (
    <div style={{ marginBottom: 28 }}>
      <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 400, lineHeight: 1.15, letterSpacing: '-0.01em', margin: '0 0 10px' }}>{title}</h3>
      {subtitle && <p style={{ fontSize: 15, color: 'var(--fg-muted)', margin: 0, lineHeight: 1.6 }}>{subtitle}</p>}
    </div>
  );
}

function SectionLabel({ children }) {
  return (
    <div style={{ fontSize: 12, color: 'var(--fg-subtle)', fontWeight: 500, marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
      {children}
    </div>
  );
}

function ChipGroup({ label, options, selected, onToggle }) {
  return (
    <div>
      <SectionLabel>{label}</SectionLabel>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {options.map(o => (
          <ChipToggleRR key={o} on={selected.includes(o)} onClick={() => onToggle(o)}>{o}</ChipToggleRR>
        ))}
      </div>
    </div>
  );
}

function BackBtn({ onClick }) {
  return (
    <button type="button" onClick={onClick} style={{
      background: 'transparent', border: 0, fontSize: 13, color: 'var(--fg-subtle)',
      cursor: 'pointer', padding: 0, textDecoration: 'underline', textUnderlineOffset: 3,
    }}>← Back</button>
  );
}

/* ─── Main component ─── */

function RevenueReport() {
  const [pageState, setPageState] = useStateRR('preview'); // preview | form | generating | teaser | done
  const [formStep, setFormStep] = useStateRR(0); // 0, 0.5, 1–7
  const [budgetDeclined, setBudgetDeclined] = useStateRR(false);
  const [touched, setTouched] = useStateRR({});
  const [teaserHtml, setTeaserHtml] = useStateRR('');
  const [reportUrl, setReportUrl] = useStateRR('');
  const [leadSubmitting, setLeadSubmitting] = useStateRR(false);
  const [leadError, setLeadError] = useStateRR('');
  const [copied, setCopied] = useStateRR(false);

  const [formData, setFormData] = useStateRR({
    // Step 0
    country: '',
    // Step 1
    businessName: '', industry: '', primaryService: '', businessStage: '', yearsInBusiness: '',
    // Step 2
    city: '', clientLocation: [], deliveryMode: [], expandingMarkets: '', expandingTo: '',
    // Step 3
    customerType: '', idealCustomer: '', problemSolved: '', salesObjections: [], discoveryChannels: [],
    // Step 4
    priceEntry: '', priceAvg: '', priceHigh: '', clientRetention: '', monthlyRevenue: '',
    clientsPerMonth: '', closeRate: '', costPerLead: '',
    // Step 5
    activePlatforms: [], whatsWorking: '', whatHasnt: '', website: '',
    crmTools: [], salesModel: '', currentFunnel: '',
    // Step 6
    primaryGoal: '', targetLeads: '', successLooks: '', startTimeline: '',
    // Step 7
    socialLinks: '', additionalContext: '',
    // Lead gate
    leadName: '', leadWhatsapp: '', leadEmail: '', leadBusiness: '', leadWebsite: '',
  });

  const market = MARKET_CONFIG[formData.country] || MARKET_CONFIG.other;
  const sym = market.symbol;

  const upd = k => e => setFormData(p => ({ ...p, [k]: e.target.value }));
  const set = (k, v) => setFormData(p => ({ ...p, [k]: v }));
  const mark = k => () => setTouched(p => ({ ...p, [k]: true }));
  const toggleArr = (k, v) => setFormData(p => ({
    ...p, [k]: p[k].includes(v) ? p[k].filter(x => x !== v) : [...p[k], v],
  }));

  /* ─── Step validity ─── */
  const step1Valid = useMemoRR(() => (
    formData.businessName.trim().length > 1 &&
    formData.industry &&
    formData.primaryService.trim().length >= 20 &&
    formData.businessStage &&
    formData.yearsInBusiness
  ), [formData]);

  const step2Valid = useMemoRR(() => (
    formData.city.trim().length > 0 &&
    formData.clientLocation.length > 0 &&
    formData.deliveryMode.length > 0
  ), [formData]);

  const step3Valid = useMemoRR(() => (
    formData.customerType &&
    formData.idealCustomer.trim().length >= 30 &&
    formData.problemSolved.trim().length >= 20
  ), [formData]);

  const step6Valid = useMemoRR(() => (
    formData.primaryGoal &&
    formData.targetLeads &&
    formData.successLooks.trim().length >= 20
  ), [formData]);

  /* ─── Step navigation ─── */
  const goStep = next => { setFormStep(next); window.scrollTo({ top: 0, behavior: 'smooth' }); };

  const canAdvance = step => {
    if (step === 1) return step1Valid;
    if (step === 2) return step2Valid;
    if (step === 3) return step3Valid;
    if (step === 6) return step6Valid;
    return true;
  };

  /* ─── Revenue options per currency ─── */
  const revenueOptions = useMemoRR(() => {
    const s = market.symbol;
    const c = market.currency;
    if (c === 'INR') return [`Under ${s}10L`, `${s}10L – ${s}50L`, `${s}50L – ${s}2Cr`, `${s}2Cr+`];
    if (c === 'AED') return [`Under ${s}500K`, `${s}500K – ${s}2M`, `${s}2M – ${s}10M`, `${s}10M+`];
    return [`Under ${s}250K`, `${s}250K – ${s}1M`, `${s}1M – ${s}5M`, `${s}5M+`];
  }, [market]);

  const stageOptions = useMemoRR(() => {
    const s = market.symbol;
    const c = market.currency;
    const t500 = c === 'INR' ? `${s}50L` : c === 'AED' ? `${s}1.8M` : `${s}500K`;
    const t2m = c === 'INR' ? `${s}2Cr` : c === 'AED' ? `${s}7M` : `${s}2M`;
    return [
      'Pre-revenue — validating',
      `Early revenue (under ${t500})`,
      `Growing (${t500}–${t2m})`,
      `Established (${t2m}+)`,
    ];
  }, [market]);

  /* ─── Generate report API call ─── */
  const generateReport = async () => {
    setPageState('generating');
    try {
      const res = await fetch('/api/generate-report', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...formData, market }),
      });
      if (!res.ok) throw new Error('API error ' + res.status);
      const data = await res.json();
      setTeaserHtml(data.teaserHtml || '');
      setReportUrl(data.reportUrl || '');
      setPageState('teaser');
    } catch (err) {
      console.error('[RevenueReport] generate-report error:', err);
      // Graceful fallback — still show teaser gate
      setTeaserHtml('<p style="color:var(--fg-muted);padding:24px">Report preview unavailable — your full report will be emailed once you submit your contact details below.</p>');
      setReportUrl('');
      setPageState('teaser');
    }
  };

  /* ─── Save lead API call ─── */
  const saveLead = async e => {
    e.preventDefault();
    const { leadName, leadWhatsapp, leadEmail, leadBusiness } = formData;
    if (!leadName.trim() || !leadWhatsapp.trim() || !leadEmail.trim() || !leadBusiness.trim()) {
      setLeadError('Please fill in all required fields.');
      return;
    }
    if (!/\S+@\S+\.\S+/.test(leadEmail.trim())) {
      setLeadError('Please enter a valid email address.');
      return;
    }
    setLeadSubmitting(true);
    setLeadError('');
    try {
      await fetch('/api/save-lead', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: leadName, whatsapp: leadWhatsapp, email: leadEmail,
          business: leadBusiness, website: formData.leadWebsite || formData.website,
          reportUrl, formData,
        }),
      });
    } catch (err) {
      console.error('[RevenueReport] save-lead error:', err);
    }
    if (reportUrl) window.open(reportUrl, '_blank');
    setPageState('done');
    setLeadSubmitting(false);
  };

  const copyLink = () => {
    navigator.clipboard.writeText(reportUrl).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  /* ════════════════════════════════════════════
     RENDER: preview
  ════════════════════════════════════════════ */
  if (pageState === 'preview') return (
    <Section id="intelligence" pad={120}>
      <Container>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 64 }}>
          <style>{`
            @media (min-width: 900px) {
              .rr-preview-grid { grid-template-columns: 3fr 2fr !important; gap: 80px !important; }
            }
          `}</style>
          <div className="rr-preview-grid" style={{ display: 'grid', gap: 64, alignItems: 'start' }}>
            {/* Left column */}
            <Reveal>
              <div>
                <Eyebrow>§ Revenue Intelligence</Eyebrow>
                <h2 style={{
                  fontFamily: 'var(--font-display)', fontSize: 'clamp(36px, 4.5vw, 60px)',
                  lineHeight: 1.05, letterSpacing: '-0.02em', margin: '16px 0 0', fontWeight: 400,
                }}>
                  What would your business look like<br/>
                  with a <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>system</em> behind it?
                </h2>
                <p style={{ fontSize: 17, lineHeight: 1.65, color: 'var(--fg-muted)', marginTop: 28, maxWidth: 520 }}>
                  Fill out your business details and our research engine generates a McKinsey-style Revenue Intelligence Report specific to your business — market sizing, ICP mapping, unit economics, funnel strategy, and a 90-day execution plan. In under 2 minutes.
                </p>

                <div style={{
                  marginTop: 28, padding: '18px 22px', borderRadius: 4,
                  border: '1px solid var(--olive-300)', background: 'var(--paper-50)',
                  fontSize: 14, color: 'var(--fg-muted)', lineHeight: 1.65,
                }}>
                  <strong style={{ color: 'var(--accent)', display: 'block', marginBottom: 6 }}>
                    The more specific you are → the more accurate your projections.
                  </strong>
                  One-line answers produce category averages. Detailed inputs produce your actual business, modelled.
                </div>

                <ul style={{ listStyle: 'none', padding: 0, margin: '32px 0 0', display: 'grid', gap: 10 }}>
                  {[
                    ['01', 'Ideal Customer Profile — segmented & data-backed'],
                    ['02', 'Market size & growth benchmarks (cited sources)'],
                    ['03', 'ICP psychology & purchase triggers'],
                    ['04', 'Offer structure & pricing logic'],
                    ['05', 'Full funnel map for your business type'],
                    ['06', 'Platform strategy with realistic CPL estimates'],
                    ['07', 'Assumptions & testable hypotheses'],
                    ['08', 'Channels & segments to avoid'],
                    ['09', 'Cited market insights & competitor benchmarks'],
                    ['10', '90-day KPI roadmap, month by month'],
                    ['11', 'Content strategy with pillars & formats'],
                    ['12', 'How Daee Media would execute this, specifically'],
                  ].map(([num, text]) => (
                    <li key={num} style={{ display: 'flex', gap: 14, fontSize: 15, color: 'var(--fg)', lineHeight: 1.5 }}>
                      <span style={{
                        fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--accent)',
                        fontWeight: 600, minWidth: 22, paddingTop: 2, letterSpacing: '0.04em',
                      }}>{num}</span>
                      <span style={{ color: 'var(--fg-muted)' }}>{text}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </Reveal>

            {/* Right column */}
            <Reveal delay={120}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
                {/* Sample report mockup */}
                <div style={{
                  border: '1px solid var(--border-strong)', borderRadius: 4,
                  overflow: 'hidden', background: 'var(--bg-elevated)',
                  boxShadow: '0 2px 12px rgba(20,19,15,0.07)',
                }}>
                  <div style={{
                    padding: '10px 18px', background: 'var(--ink-900)', color: 'var(--paper-50)',
                    fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', fontWeight: 500,
                  }}>SAMPLE · Revenue Intelligence Report</div>
                  <div style={{ padding: '20px 18px' }}>
                    {Array.from({ length: 8 }, (_, i) => (
                      <div key={i} style={{ display: 'flex', gap: 12, marginBottom: 14, alignItems: 'flex-start' }}>
                        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--accent)', fontWeight: 600, paddingTop: 3, minWidth: 20 }}>
                          {String(i + 1).padStart(2, '0')}
                        </span>
                        <div style={{ flex: 1 }}>
                          <div style={{
                            height: 10, borderRadius: 2, background: 'var(--paper-300)',
                            width: `${60 + (i * 13 % 35)}%`, marginBottom: 5,
                            filter: i > 1 ? 'blur(2px)' : 'none',
                            opacity: i > 1 ? 0.5 : 1,
                          }}/>
                          <div style={{
                            height: 8, borderRadius: 2, background: 'var(--paper-200)',
                            width: `${40 + (i * 17 % 40)}%`,
                            filter: i > 1 ? 'blur(2px)' : 'none',
                            opacity: i > 1 ? 0.4 : 0.8,
                          }}/>
                        </div>
                      </div>
                    ))}
                    <div style={{
                      marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--border)',
                      fontSize: 11, color: 'var(--fg-subtle)', lineHeight: 1.6,
                    }}>
                      Your version will be specific to your business, market, and budget.
                    </div>
                  </div>
                </div>

                {/* Stats */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                  {[
                    ['8 minutes', 'to complete'],
                    ['16 sections', 'in your report'],
                  ].map(([val, label]) => (
                    <div key={val} style={{
                      padding: '20px 18px', border: '1px solid var(--border)', borderRadius: 4,
                      background: 'var(--bg-elevated)', textAlign: 'center',
                    }}>
                      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 26, fontWeight: 600, color: 'var(--accent)', letterSpacing: '-0.02em' }}>{val}</div>
                      <div style={{ fontSize: 12, color: 'var(--fg-subtle)', marginTop: 4, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 500 }}>{label}</div>
                    </div>
                  ))}
                </div>

                {/* CTA */}
                <button type="button" onClick={() => setPageState('form')} style={{
                  width: '100%', padding: '18px 24px', borderRadius: 4, cursor: 'pointer',
                  background: 'var(--accent)', color: 'var(--accent-fg)',
                  border: '1px solid transparent', fontFamily: 'var(--font-sans)',
                  fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em',
                  transition: 'background 120ms', textAlign: 'center',
                }}>Generate My Free Report →</button>
                <p style={{ fontSize: 12, color: 'var(--fg-subtle)', textAlign: 'center', margin: 0 }}>
                  Free. No card required. Takes 8 minutes.
                </p>
              </div>
            </Reveal>
          </div>
        </div>
      </Container>
    </Section>
  );

  /* ════════════════════════════════════════════
     RENDER: generating
  ════════════════════════════════════════════ */
  if (pageState === 'generating') return (
    <Section id="intelligence" pad={120}>
      <Container narrow>
        <GeneratingScreen/>
      </Container>
    </Section>
  );

  /* ════════════════════════════════════════════
     RENDER: teaser + contact gate
  ════════════════════════════════════════════ */
  if (pageState === 'teaser') return (
    <Section id="intelligence" pad={80} topRule>
      <Container narrow>
        <Eyebrow color="var(--accent)">§ Your Report Preview</Eyebrow>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(28px, 3.5vw, 40px)', fontWeight: 400, lineHeight: 1.1, letterSpacing: '-0.015em', margin: '12px 0 32px' }}>
          Here's what we found.
        </h2>

        {/* Teaser HTML */}
        {teaserHtml && (
          <div style={{
            border: '1px solid var(--border)', borderRadius: 4, padding: '32px 36px',
            background: 'var(--bg-elevated)', marginBottom: 24,
            fontFamily: 'var(--font-sans)', fontSize: 15, lineHeight: 1.7, color: 'var(--fg-muted)',
          }} dangerouslySetInnerHTML={{ __html: teaserHtml }}/>
        )}

        {/* Locked preview */}
        <div style={{
          position: 'relative', marginBottom: 48, borderRadius: 4,
          border: '1px solid var(--border)', overflow: 'hidden',
        }}>
          <div style={{ padding: '24px 36px', filter: 'blur(4px)', userSelect: 'none', pointerEvents: 'none' }}>
            {Array.from({ length: 5 }, (_, i) => (
              <div key={i} style={{ marginBottom: 18 }}>
                <div style={{ height: 11, background: 'var(--paper-300)', borderRadius: 2, width: `${55 + i * 9}%`, marginBottom: 7 }}/>
                <div style={{ height: 8, background: 'var(--paper-200)', borderRadius: 2, width: `${40 + i * 7}%` }}/>
              </div>
            ))}
          </div>
          <div style={{
            position: 'absolute', inset: 0, display: 'flex', alignItems: 'center',
            justifyContent: 'center', background: 'rgba(250,248,244,0.7)',
          }}>
            <div style={{ textAlign: 'center', padding: 24 }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--accent)', fontWeight: 600, letterSpacing: '0.08em', marginBottom: 8 }}>SECTIONS 03–16 LOCKED</div>
              <div style={{ fontSize: 14, color: 'var(--fg-muted)' }}>Enter your details below to unlock the full report.</div>
            </div>
          </div>
        </div>

        {/* Contact gate */}
        <div style={{
          background: 'var(--bg-elevated)', border: '1px solid var(--border)',
          borderRadius: 4, padding: '40px 44px',
          boxShadow: '0 2px 16px rgba(20,19,15,0.06)',
        }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 400, lineHeight: 1.1, letterSpacing: '-0.015em', margin: '0 0 10px' }}>
            Your report is ready.
          </h3>
          <p style={{ fontSize: 16, color: 'var(--fg-muted)', margin: '0 0 32px', lineHeight: 1.6 }}>
            Enter your details to unlock the full 16-section report. We don't spam — Saad reads these himself.
          </p>

          <form onSubmit={saveLead} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
              <FieldRR label="Full name" required placeholder="Your full name" value={formData.leadName} onChange={upd('leadName')}/>
              <FieldRR label="WhatsApp number" required placeholder="+1 234 567 8900" value={formData.leadWhatsapp} onChange={upd('leadWhatsapp')}/>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
              <FieldRR label="Business name" required placeholder="Your company" value={formData.leadBusiness} onChange={upd('leadBusiness')}/>
              <FieldRR label="Email" required placeholder="you@company.com" value={formData.leadEmail} onChange={upd('leadEmail')}/>
            </div>
            <FieldRR label="Website" placeholder="company.com (optional)" value={formData.leadWebsite} onChange={upd('leadWebsite')}/>

            {leadError && (
              <div style={{ padding: '12px 16px', background: 'var(--clay-100)', border: '1px solid var(--clay-600)', borderRadius: 4, fontSize: 14, color: 'var(--clay-600)' }}>
                {leadError}
              </div>
            )}

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
              <p style={{ fontSize: 12, color: 'var(--fg-subtle)', margin: 0, maxWidth: 420 }}>
                By submitting, you agree to be contacted by Daee Media regarding your report.
              </p>
              <Button type="submit" style={{ opacity: leadSubmitting ? 0.6 : 1, pointerEvents: leadSubmitting ? 'none' : 'auto' }}>
                {leadSubmitting ? 'Unlocking…' : 'Unlock My Report →'}
              </Button>
            </div>
          </form>
        </div>
      </Container>
    </Section>
  );

  /* ════════════════════════════════════════════
     RENDER: done
  ════════════════════════════════════════════ */
  if (pageState === 'done') return (
    <Section id="intelligence" pad={120} topRule>
      <Container narrow>
        <div style={{ textAlign: 'center', maxWidth: 560, margin: '0 auto' }}>
          {/* Checkmark */}
          <div style={{
            width: 64, height: 64, borderRadius: 999, background: 'var(--olive-100)',
            border: '2px solid var(--accent)', display: 'flex', alignItems: 'center',
            justifyContent: 'center', margin: '0 auto 32px',
          }}>
            <span style={{ color: 'var(--accent)', fontSize: 28, lineHeight: 1 }}>✓</span>
          </div>

          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(28px, 3.5vw, 40px)', fontWeight: 400, lineHeight: 1.1, letterSpacing: '-0.015em', margin: '0 0 16px' }}>
            Your report is opening in a new tab.
          </h2>
          <p style={{ fontSize: 16, color: 'var(--fg-muted)', margin: '0 0 36px', lineHeight: 1.65 }}>
            We've received your details. Saad will follow up personally if there's a fit.
          </p>

          {reportUrl && (
            <div style={{ marginBottom: 32, textAlign: 'left' }}>
              <div style={{ fontSize: 12, color: 'var(--fg-subtle)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>
                Report URL (shareable link)
              </div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'stretch' }}>
                <div style={{
                  flex: 1, padding: '12px 14px', background: 'var(--paper-100)',
                  border: '1px solid var(--border-strong)', borderRadius: 4,
                  fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-muted)',
                  wordBreak: 'break-all', lineHeight: 1.5,
                }}>{reportUrl}</div>
                <button type="button" onClick={copyLink} style={{
                  padding: '12px 18px', borderRadius: 4, cursor: 'pointer',
                  background: copied ? 'var(--olive-100)' : 'var(--bg-elevated)',
                  border: '1px solid var(--border-strong)',
                  color: copied ? 'var(--accent)' : 'var(--fg-muted)',
                  fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 500,
                  transition: 'all 140ms', whiteSpace: 'nowrap',
                }}>{copied ? 'Copied!' : 'Copy link'}</button>
              </div>
              <div style={{ marginTop: 12, fontSize: 14, color: 'var(--fg-subtle)' }}>
                If the tab didn't open:{' '}
                <a href={reportUrl} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--accent)', textDecoration: 'underline', textUnderlineOffset: 3 }}>
                  Open Report →
                </a>
              </div>
            </div>
          )}

          <div style={{ paddingTop: 24, borderTop: '1px solid var(--border)', textAlign: 'center' }}>
            <a href="/#apply" style={{
              fontSize: 15, color: 'var(--fg-muted)', textDecoration: 'underline',
              textUnderlineOffset: 3,
            }}>Want to apply to work with Daee Media? →</a>
          </div>
        </div>
      </Container>
    </Section>
  );

  /* ════════════════════════════════════════════
     RENDER: multi-step form
  ════════════════════════════════════════════ */
  return (
    <Section id="intelligence" pad={80} topRule>
      <Container narrow>
        <div style={{ maxWidth: 680, margin: '0 auto' }}>
          {/* Step 0 — Country */}
          {formStep === 0 && (
            <div>
              <Eyebrow>§ Revenue Intelligence</Eyebrow>
              <StepTitle
                title="Where is your business based?"
                subtitle="This determines your currency, market benchmarks, and which data sources we reference."
              />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                {COUNTRY_OPTIONS.map(opt => (
                  <CountryCard
                    key={opt.key}
                    selected={formData.country === opt.key}
                    onClick={() => { set('country', opt.key); goStep(0.5); }}
                    flag={opt.flag}
                    label={opt.label}
                  />
                ))}
              </div>
            </div>
          )}

          {/* Step 0.5 — Budget gate */}
          {formStep === 0.5 && !budgetDeclined && (
            <div>
              <Eyebrow>§ One Qualifier</Eyebrow>
              <StepTitle title="One qualifier before we begin."/>
              <div style={{
                margin: '24px 0', padding: '24px 28px', borderRadius: 4,
                border: '1.5px solid var(--accent)', background: 'var(--olive-50)',
              }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 28, fontWeight: 600, color: 'var(--accent)', letterSpacing: '-0.02em', marginBottom: 6 }}>
                  {market.symbol}{market.minBudget}/month
                </div>
                <div style={{ fontSize: 14, color: 'var(--fg-muted)', fontWeight: 500 }}>
                  Minimum marketing investment · {market.label}
                </div>
              </div>
              <p style={{ fontSize: 16, color: 'var(--fg-muted)', lineHeight: 1.7, margin: '0 0 32px' }}>
                This tool is built for businesses with active or planned marketing investment at this level. The projections, platform recommendations, and unit economics only make sense above this threshold.
              </p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                <Button onClick={() => goStep(1)} size="lg" style={{ width: '100%', justifyContent: 'center' }}>
                  Yes, I meet this — let's go →
                </Button>
                <Button variant="secondary" onClick={() => setBudgetDeclined(true)} style={{ width: '100%', justifyContent: 'center' }}>
                  Not yet — let me see what's possible
                </Button>
              </div>
              <div style={{ marginTop: 20 }}>
                <BackBtn onClick={() => goStep(0)}/>
              </div>
            </div>
          )}

          {/* Budget declined state */}
          {formStep === 0.5 && budgetDeclined && (
            <div style={{ textAlign: 'center', maxWidth: 480, margin: '0 auto', padding: '40px 0' }}>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 400, lineHeight: 1.15, margin: '0 0 16px' }}>
                Come back when you're ready.
              </h3>
              <p style={{ fontSize: 16, color: 'var(--fg-muted)', lineHeight: 1.7, margin: '0 0 28px' }}>
                This tool is calibrated for businesses ready to invest at scale. When you're ready, come back — or email{' '}
                <a href="mailto:service@daeemedia.com" style={{ color: 'var(--accent)' }}>service@daeemedia.com</a>
                {' '}and we'll point you in the right direction.
              </p>
              <BackBtn onClick={() => { setBudgetDeclined(false); goStep(0.5); }}/>
            </div>
          )}

          {/* Steps 1–7 */}
          {formStep >= 1 && (
            <>
              <StepHeader step={formStep} total={7}/>

              {/* ─── Step 1: Business Basics ─── */}
              {formStep === 1 && (
                <div>
                  <StepTitle title="Business Basics" subtitle="Tell us about your business. Be specific — vague answers produce generic output."/>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                    <FieldRR label="Business name" required placeholder="e.g. Mirror Mental Health" value={formData.businessName} onChange={upd('businessName')} onBlur={mark('businessName')}
                      error={touched.businessName && formData.businessName.trim().length <= 1 ? 'Required' : null}/>
                    <SelectFieldRR label="Industry" required value={formData.industry} onChange={upd('industry')}
                      options={['Real Estate', 'Healthcare & Wellness', 'Education & Coaching', 'Legal & Financial Services', 'Home Services', 'Hospitality & F&B', 'SaaS & Tech', 'Consulting', 'Events & Entertainment', 'E-commerce & D2C', 'Other']}/>
                    <FieldRR label="Primary service — what do you offer?" required textarea rows={3}
                      placeholder="e.g. We help mid-market B2B companies build outbound sales pipelines through LinkedIn and cold email..."
                      value={formData.primaryService} onChange={upd('primaryService')} onBlur={mark('primaryService')}
                      hint={formData.primaryService.trim().length < 20 ? `${20 - formData.primaryService.trim().length} more characters needed` : null}
                      error={touched.primaryService && formData.primaryService.trim().length < 20 ? 'Please describe your service in at least 20 characters' : null}/>
                    <SelectFieldRR label="Business stage" required value={formData.businessStage} onChange={upd('businessStage')} options={stageOptions}/>
                    <SelectFieldRR label="Years in business" required value={formData.yearsInBusiness} onChange={upd('yearsInBusiness')}
                      options={['Under 1 year', '1–3 years', '3–5 years', '5+ years']}/>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 32 }}>
                    <BackBtn onClick={() => goStep(0.5)}/>
                    <Button onClick={() => step1Valid && goStep(2)} style={{ opacity: step1Valid ? 1 : 0.5, pointerEvents: step1Valid ? 'auto' : 'none' }}>
                      Continue →
                    </Button>
                  </div>
                </div>
              )}

              {/* ─── Step 2: Geography & Market ─── */}
              {formStep === 2 && (
                <div>
                  <StepTitle title="Geography & Market" subtitle="Where you operate shapes your platform strategy, CPL benchmarks, and market sizing."/>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                    <FieldRR label="Your city / region" required placeholder="e.g. Dubai, London, Sydney" value={formData.city} onChange={upd('city')} onBlur={mark('city')}
                      error={touched.city && !formData.city.trim() ? 'Required' : null}/>
                    <ChipGroup label="Where are your clients located? *" options={['Same city', 'State/Region-wide', 'Nationwide', 'International', 'Mix']}
                      selected={formData.clientLocation} onToggle={v => toggleArr('clientLocation', v)}/>
                    <ChipGroup label="How do you deliver your service? *" options={['In-person', 'Remotely', 'Hybrid']}
                      selected={formData.deliveryMode} onToggle={v => toggleArr('deliveryMode', v)}/>
                    <div>
                      <SectionLabel>Planning to expand to new markets?</SectionLabel>
                      <div style={{ display: 'flex', gap: 12, marginBottom: 12 }}>
                        <RadioCard selected={formData.expandingMarkets === 'yes'} onClick={() => set('expandingMarkets', 'yes')}>Yes</RadioCard>
                        <RadioCard selected={formData.expandingMarkets === 'no'} onClick={() => set('expandingMarkets', 'no')}>No</RadioCard>
                      </div>
                      {formData.expandingMarkets === 'yes' && (
                        <FieldRR label="Which markets?" placeholder="e.g. UK, UAE, Southeast Asia" value={formData.expandingTo} onChange={upd('expandingTo')}/>
                      )}
                    </div>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 32 }}>
                    <BackBtn onClick={() => goStep(1)}/>
                    <Button onClick={() => step2Valid && goStep(3)} style={{ opacity: step2Valid ? 1 : 0.5, pointerEvents: step2Valid ? 'auto' : 'none' }}>
                      Continue →
                    </Button>
                  </div>
                </div>
              )}

              {/* ─── Step 3: Your Customer ─── */}
              {formStep === 3 && (
                <div>
                  <StepTitle title="Your Customer" subtitle="Your ICP is the foundation of every projection, platform choice, and creative angle in the report."/>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                    <div>
                      <SectionLabel>Do you serve? *</SectionLabel>
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                        {['B2B', 'B2C', 'Both'].map(t => (
                          <RadioCard key={t} selected={formData.customerType === t} onClick={() => set('customerType', t)}>{t}</RadioCard>
                        ))}
                      </div>
                    </div>
                    <FieldRR label="Describe your ideal customer" required textarea rows={3}
                      placeholder={formData.customerType === 'B2B' ? 'e.g. Founders of professional services firms with 10–50 employees, $1M–$5M revenue, struggling to generate consistent inbound leads...' : 'e.g. Women 28–45, homeowners in major metros, earning $80K+, who value premium home design and have tried DIY but want professional results...'}
                      value={formData.idealCustomer} onChange={upd('idealCustomer')} onBlur={mark('idealCustomer')}
                      hint={formData.idealCustomer.trim().length < 30 ? `${30 - formData.idealCustomer.trim().length} more characters needed` : null}
                      error={touched.idealCustomer && formData.idealCustomer.trim().length < 30 ? 'Please describe in at least 30 characters' : null}/>
                    <FieldRR label="The biggest problem you solve for them" required textarea rows={3}
                      placeholder="e.g. They can't predictably fill their pipeline — they rely on referrals that are inconsistent and can't be scaled..."
                      value={formData.problemSolved} onChange={upd('problemSolved')} onBlur={mark('problemSolved')}
                      hint={formData.problemSolved.trim().length < 20 ? `${20 - formData.problemSolved.trim().length} more characters needed` : null}
                      error={touched.problemSolved && formData.problemSolved.trim().length < 20 ? 'Please describe in at least 20 characters' : null}/>
                    <ChipGroup label="Objections you face most in sales"
                      options={['Price too high', 'Trust / credibility', 'Not the right time', 'Already using someone else', "Don't understand the value", 'ROI uncertainty', 'Other']}
                      selected={formData.salesObjections} onToggle={v => toggleArr('salesObjections', v)}/>
                    <ChipGroup label="How do clients find you today?"
                      options={['Word of mouth', 'Referrals', 'Instagram', 'LinkedIn', 'Facebook', 'Google', 'Cold outreach', 'Events', 'Other']}
                      selected={formData.discoveryChannels} onToggle={v => toggleArr('discoveryChannels', v)}/>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 32 }}>
                    <BackBtn onClick={() => goStep(2)}/>
                    <Button onClick={() => step3Valid && goStep(4)} style={{ opacity: step3Valid ? 1 : 0.5, pointerEvents: step3Valid ? 'auto' : 'none' }}>
                      Continue →
                    </Button>
                  </div>
                </div>
              )}

              {/* ─── Step 4: Financials ─── */}
              {formStep === 4 && (
                <div>
                  <StepTitle title="Financials & Unit Economics" subtitle="Optional but critical — vague answers produce vague projections. The more specific, the more accurate your unit economics."/>
                  <div style={{
                    padding: '12px 16px', background: 'var(--olive-50)', borderRadius: 4,
                    border: '1px solid var(--olive-100)', fontSize: 13, color: 'var(--accent)',
                    marginBottom: 20, fontWeight: 500,
                  }}>
                    All fields optional. Each one improves accuracy significantly.
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
                      <FieldRR label="Entry-level price" placeholder={`${sym}X,XXX`} value={formData.priceEntry} onChange={upd('priceEntry')}/>
                      <FieldRR label="Average price" placeholder={`${sym}X,XXX`} value={formData.priceAvg} onChange={upd('priceAvg')}/>
                      <FieldRR label="Highest-ticket" placeholder={`${sym}XX,XXX`} value={formData.priceHigh} onChange={upd('priceHigh')}/>
                    </div>
                    <SelectFieldRR label="Typical client retention" value={formData.clientRetention} onChange={upd('clientRetention')}
                      options={['One-time', '1–3 months', '3–6 months', '6–12 months', '12+ months']}/>
                    <SelectFieldRR label="Monthly revenue range" value={formData.monthlyRevenue} onChange={upd('monthlyRevenue')} options={revenueOptions}/>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                      <SelectFieldRR label="New clients per month" value={formData.clientsPerMonth} onChange={upd('clientsPerMonth')}
                        options={['0–2', '3–5', '6–10', '11–20', '20+']}/>
                      <SelectFieldRR label="Current close rate" value={formData.closeRate} onChange={upd('closeRate')}
                        options={['Under 10%', '10–20%', '20–40%', '40–60%', 'Over 60%', "Don't track"]}/>
                    </div>
                    <FieldRR label="Current cost per lead (if running ads)" placeholder={`e.g. ${sym}XX per lead`} value={formData.costPerLead} onChange={upd('costPerLead')}/>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 32 }}>
                    <BackBtn onClick={() => goStep(3)}/>
                    <Button onClick={() => goStep(5)}>Continue →</Button>
                  </div>
                </div>
              )}

              {/* ─── Step 5: Marketing & Tech ─── */}
              {formStep === 5 && (
                <div>
                  <StepTitle title="Marketing & Tech" subtitle="Honest answers here — 'nothing works' is a valid and useful input."/>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                    <ChipGroup label="Active platforms"
                      options={['Meta (Facebook/Instagram)', 'Google Ads', 'LinkedIn', 'YouTube', 'TikTok', 'Twitter/X', 'Email marketing', 'WhatsApp Business', 'None yet']}
                      selected={formData.activePlatforms} onToggle={v => toggleArr('activePlatforms', v)}/>
                    <FieldRR label="What's working right now?" textarea rows={3}
                      placeholder="Be honest — even 'nothing' is a valid answer" value={formData.whatsWorking} onChange={upd('whatsWorking')}/>
                    <FieldRR label="What hasn't worked?" textarea rows={3}
                      placeholder="Platforms, campaigns, agencies, strategies that didn't deliver..." value={formData.whatHasnt} onChange={upd('whatHasnt')}/>
                    <FieldRR label="Your website" placeholder="company.com" value={formData.website} onChange={upd('website')}/>
                    <ChipGroup label="CRM or lead tracking"
                      options={['Zoho CRM', 'HubSpot', 'Salesforce', 'Monday.com', 'Excel/Google Sheets', 'Nothing', 'Other']}
                      selected={formData.crmTools} onToggle={v => toggleArr('crmTools', v)}/>
                    <SelectFieldRR label="Sales model" value={formData.salesModel} onChange={upd('salesModel')}
                      options={['Founder-led', 'Small sales team', 'Full sales team', 'Working on it']}/>
                    <SelectFieldRR label="Current funnel after someone sees your ad" value={formData.currentFunnel} onChange={upd('currentFunnel')}
                      options={['No funnel yet', 'Just a website homepage', 'Landing page with form', 'Landing page + call booking', 'Full funnel with nurture sequence']}/>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 32 }}>
                    <BackBtn onClick={() => goStep(4)}/>
                    <Button onClick={() => goStep(6)}>Continue →</Button>
                  </div>
                </div>
              )}

              {/* ─── Step 6: Goals ─── */}
              {formStep === 6 && (
                <div>
                  <StepTitle title="Goals" subtitle="What are you actually trying to achieve? This shapes the 90-day roadmap and KPI targets."/>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                    <div>
                      <SectionLabel>Primary goal *</SectionLabel>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                        {['More qualified leads', 'Better lead quality', 'Enter a new market', 'Increase close rate', 'Build brand awareness', 'All of the above'].map(g => (
                          <RadioCard key={g} selected={formData.primaryGoal === g} onClick={() => set('primaryGoal', g)}>{g}</RadioCard>
                        ))}
                      </div>
                    </div>
                    <SelectFieldRR label="Target monthly leads" required value={formData.targetLeads} onChange={upd('targetLeads')}
                      options={['10–20', '21–50', '51–100', '100–200', '200+']}/>
                    <FieldRR label="What does success look like in 90 days?" required textarea rows={3}
                      placeholder="Be specific — revenue numbers, lead volume, team size, markets entered..."
                      value={formData.successLooks} onChange={upd('successLooks')} onBlur={mark('successLooks')}
                      hint={formData.successLooks.trim().length < 20 ? `${20 - formData.successLooks.trim().length} more characters needed` : null}
                      error={touched.successLooks && formData.successLooks.trim().length < 20 ? 'Please describe in at least 20 characters' : null}/>
                    <SelectFieldRR label="When are you looking to start?" value={formData.startTimeline} onChange={upd('startTimeline')}
                      options={['Immediately', 'Within 1 month', '1–3 months', 'Just exploring']}/>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 32 }}>
                    <BackBtn onClick={() => goStep(5)}/>
                    <Button onClick={() => step6Valid && goStep(7)} style={{ opacity: step6Valid ? 1 : 0.5, pointerEvents: step6Valid ? 'auto' : 'none' }}>
                      Continue →
                    </Button>
                  </div>
                </div>
              )}

              {/* ─── Step 7: Final Context ─── */}
              {formStep === 7 && (
                <div>
                  <StepTitle title="Final Context" subtitle="Anything that would help us be more accurate and specific. This is your chance to write past the form's boxes."/>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                    <FieldRR label="Social media links" placeholder="Instagram, LinkedIn, Facebook — paste any links" value={formData.socialLinks} onChange={upd('socialLinks')}/>
                    <FieldRR label="Additional context" textarea rows={5}
                      placeholder="Anything about your business, competitors, past campaigns, team, challenges, or goals that would help us be more specific..."
                      value={formData.additionalContext} onChange={upd('additionalContext')}/>
                  </div>

                  <div style={{
                    marginTop: 36, paddingTop: 28, borderTop: '1px solid var(--border)',
                    display: 'flex', flexDirection: 'column', gap: 16, alignItems: 'center', textAlign: 'center',
                  }}>
                    <div style={{ fontSize: 15, color: 'var(--fg-muted)' }}>
                      Ready to generate your report.
                    </div>
                    <button type="button" onClick={generateReport} style={{
                      width: '100%', maxWidth: 480, padding: '18px 24px', borderRadius: 4, cursor: 'pointer',
                      background: 'var(--accent)', color: 'var(--accent-fg)',
                      border: '1px solid transparent', fontFamily: 'var(--font-sans)',
                      fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em',
                      transition: 'background 120ms',
                    }}>Generate My Revenue Intelligence Report →</button>
                    <p style={{ fontSize: 12, color: 'var(--fg-subtle)', margin: 0 }}>
                      This usually takes 60–90 seconds. Your report will open automatically.
                    </p>
                  </div>

                  <div style={{ marginTop: 20, display: 'flex', justifyContent: 'flex-start' }}>
                    <BackBtn onClick={() => goStep(6)}/>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </Container>
    </Section>
  );
}

/* ─── Generating screen (extracted for clarity) ─── */
function GeneratingScreen() {
  const [activeStep, setActiveStep] = useStateRR(0);
  const [progress, setProgress] = useStateRR(0);
  const intervalRef = useRefRR(null);
  const progressRef = useRefRR(null);

  useEffectRR(() => {
    // Advance loading steps every ~10 seconds
    intervalRef.current = setInterval(() => {
      setActiveStep(s => Math.min(s + 1, LOADING_STEPS.length - 1));
    }, 10000);

    // Progress bar: 0 → 95 over 60s
    const start = Date.now();
    const duration = 60000;
    progressRef.current = setInterval(() => {
      const elapsed = Date.now() - start;
      const pct = Math.min(95, (elapsed / duration) * 95);
      setProgress(pct);
      if (elapsed >= duration) clearInterval(progressRef.current);
    }, 200);

    return () => {
      clearInterval(intervalRef.current);
      clearInterval(progressRef.current);
    };
  }, []);

  return (
    <div style={{ maxWidth: 560, margin: '0 auto', textAlign: 'center', padding: '40px 0' }}>
      {/* Wordmark */}
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, letterSpacing: '-0.01em', color: 'var(--fg-muted)', marginBottom: 52 }}>
        Daee Media
      </div>

      <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 400, lineHeight: 1.1, letterSpacing: '-0.015em', margin: '0 0 40px' }}>
        Building your report…
      </h3>

      {/* Loading steps */}
      <div style={{ textAlign: 'left', marginBottom: 40, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {LOADING_STEPS.map((step, i) => {
          const done = i < activeStep;
          const active = i === activeStep;
          return (
            <div key={step} style={{ display: 'flex', gap: 14, alignItems: 'center', opacity: i > activeStep ? 0.35 : 1, transition: 'opacity 300ms' }}>
              <div style={{
                width: 20, height: 20, borderRadius: 999, flexShrink: 0,
                background: done ? 'var(--accent)' : 'transparent',
                border: `1.5px solid ${done ? 'var(--accent)' : active ? 'var(--accent)' : 'var(--border-strong)'}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                transition: 'all 300ms',
              }}>
                {done && <span style={{ color: 'var(--accent-fg)', fontSize: 11, lineHeight: 1 }}>✓</span>}
                {active && !done && (
                  <span style={{
                    width: 7, height: 7, borderRadius: 999, background: 'var(--accent)',
                    animation: 'rrPulse 1s ease-in-out infinite',
                    display: 'block',
                  }}/>
                )}
              </div>
              <span style={{
                fontSize: 15, color: done ? 'var(--fg-muted)' : active ? 'var(--fg)' : 'var(--fg-subtle)',
                fontWeight: active ? 500 : 400, transition: 'color 300ms',
              }}>{step}</span>
            </div>
          );
        })}
      </div>

      {/* Progress bar */}
      <div style={{ background: 'var(--border)', borderRadius: 999, height: 4, overflow: 'hidden', marginBottom: 20 }}>
        <div style={{
          height: '100%', background: 'var(--accent)', borderRadius: 999,
          width: `${progress}%`, transition: 'width 200ms linear',
        }}/>
      </div>

      <p style={{ fontSize: 14, color: 'var(--fg-subtle)', lineHeight: 1.6 }}>
        This usually takes 60–90 seconds. Please keep this tab open.
      </p>

      <style>{`
        @keyframes rrPulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.4; transform: scale(0.7); }
        }
      `}</style>
    </div>
  );
}

window.RevenueReport = RevenueReport;
