/* wizard.jsx — Generator wizard (8-step flow) for POA Forms
 * Loads any state/type from URL ?state=CA&type=durable or localStorage 'poa.draft'.
 * Mobile-first; persists to localStorage every change.
 */

const POWERS = [
  { id: 'realestate',  label: 'Real estate',           desc: 'Buy, sell, manage property' },
  { id: 'banking',     label: 'Banking',               desc: 'Accounts, transfers, deposits' },
  { id: 'investments', label: 'Investments',           desc: 'Brokerage, retirement accounts' },
  { id: 'taxes',       label: 'Tax matters',           desc: 'File and discuss with the IRS' },
  { id: 'business',    label: 'Business operations',   desc: 'Run or wind down a business' },
  { id: 'insurance',   label: 'Insurance',             desc: 'Claims, policies, beneficiaries' },
  { id: 'gifts',       label: 'Gifts',                 desc: '⚠️ Hot power — extra scrutiny' },
  { id: 'beneficiary', label: 'Change beneficiaries',  desc: '⚠️ Hot power' },
  { id: 'trusts',      label: 'Trusts',                desc: 'Create, fund, modify' },
  { id: 'claims',      label: 'Legal claims',          desc: 'Sue, settle, defend' },
  { id: 'personal',    label: 'Personal & family',     desc: 'Day-to-day matters' },
  { id: 'benefits',    label: 'Government benefits',   desc: 'SSA, Medicare, VA' },
];

const STEPS = [
  { n: 1, label: 'State' },
  { n: 2, label: 'Type' },
  { n: 3, label: 'You' },
  { n: 4, label: 'Agent' },
  { n: 5, label: 'Powers' },
  { n: 6, label: 'Options' },
  { n: 7, label: 'Review' },
  { n: 8, label: 'Done' },
];

// Read initial values from URL or localStorage
function loadInitial() {
  const params = new URLSearchParams(window.location.search);
  let initial = { state: '', type: '', principal: {}, agent: {}, powers: [], options: {} };
  try {
    const saved = JSON.parse(localStorage.getItem('poa.draft') || '{}');
    Object.assign(initial, saved);
  } catch (e) {}
  if (params.get('state')) initial.state = params.get('state');
  if (params.get('type'))  initial.type  = params.get('type');
  return initial;
}

function StepIndicator({ current, onJump, valid }) {
  return (
    <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
      {STEPS.map((s) => {
        const isActive = current === s.n;
        const isDone = current > s.n;
        return (
          <React.Fragment key={s.n}>
            <button onClick={() => isDone && onJump(s.n)}
              disabled={!isDone}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '6px 12px', borderRadius: 'var(--r-pill)',
                border: '1.5px solid var(--ink)',
                background: isActive ? 'var(--accent)' : (isDone ? 'var(--ink)' : 'transparent'),
                color: isActive ? 'var(--ink)' : (isDone ? 'var(--accent)' : 'var(--muted)'),
                fontWeight: 600, fontSize: 12, fontFamily: 'inherit',
                cursor: isDone ? 'pointer' : 'default',
                opacity: !isDone && !isActive ? 0.5 : 1,
              }}>
              <span style={{ fontFamily: 'Outfit', fontSize: 11, opacity: 0.85 }}>{s.n}</span>
              <span>{s.label}</span>
            </button>
            {s.n < STEPS.length && <span style={{ width: 8, height: 1, background: 'var(--line-cream)' }}/>}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function StepShell({ kicker, title, subtitle, children, footer, illo }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: illo ? '1.2fr 0.8fr' : '1fr', gap: 'var(--s-9)', alignItems: 'flex-start' }} className="wiz-grid">
      <div>
        <div className="eyebrow" style={{ marginBottom: 8, color: 'var(--muted)' }}>{kicker}</div>
        <h2 style={{ marginBottom: 12, maxWidth: '20ch' }}>{title}</h2>
        {subtitle && <p className="lede" style={{ marginBottom: 'var(--s-7)' }}>{subtitle}</p>}
        <div style={{ marginBottom: 'var(--s-8)' }}>{children}</div>
        {footer}
      </div>
      {illo && <div style={{ position: 'sticky', top: 100 }}>{illo}</div>}
      <style>{`@media (max-width: 900px) { .wiz-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

// ── Steps ──────────────────────────────────────────────────────────────
function Step1State({ data, set }) {
  const [picker, setPicker] = React.useState('map');
  return (
    <>
      <div role="tablist" style={{ display: 'inline-flex', borderRadius: 'var(--r-pill)', border: '1.5px solid var(--ink)', overflow: 'hidden', background: 'var(--paper)', padding: 3, marginBottom: 16 }}>
        {[['map','Map'],['list','List']].map(([k, label]) => (
          <button key={k} onClick={() => setPicker(k)} style={{
            border: 'none', background: picker === k ? 'var(--ink)' : 'transparent',
            color: picker === k ? 'var(--paper)' : 'var(--ink)',
            padding: '6px 14px', borderRadius: 'var(--r-pill)', fontWeight: 600, fontSize: 13,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>{label}</button>
        ))}
      </div>
      {picker === 'map'
        ? <USMap value={data.state} onChange={(s) => set({ state: s })}/>
        : <select className="select" value={data.state} onChange={(e) => set({ state: e.target.value })}>
            <option value="">Choose your state…</option>
            {US_STATES.map(([c, n]) => <option key={c} value={c}>{n}</option>)}
          </select>
      }
      {data.state && (
        <div style={{ marginTop: 16, padding: 16, background: 'var(--paper-2)', borderRadius: 'var(--r-md)', border: '1px solid var(--line-cream)' }}>
          <div className="eyebrow" style={{ color: 'var(--muted)', marginBottom: 6 }}>Selected state</div>
          <div style={{ fontFamily: 'Outfit', fontWeight: 600, fontSize: 22, letterSpacing: '-0.02em' }}>
            {(US_STATES.find(s => s[0] === data.state) || [])[1]}
          </div>
          <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>
            We'll auto-load {data.state}'s witness, notarization, and statutory rules.
          </div>
        </div>
      )}
    </>
  );
}

function Step2Type({ data, set }) {
  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {POA_TYPES.map((t) => {
          const active = data.type === t.id;
          return (
            <button key={t.id} type="button" onClick={() => set({ type: t.id })}
              style={{
                textAlign: 'left', padding: '20px 22px',
                border: '1.5px solid var(--ink)', borderRadius: 'var(--r-md)',
                background: active ? 'var(--accent)' : 'var(--surface)',
                color: 'var(--ink)', cursor: 'pointer', fontFamily: 'inherit',
                boxShadow: active ? '4px 4px 0 0 var(--ink)' : 'none',
                transform: active ? 'translate(-1px,-1px)' : 'none',
                display: 'flex', flexDirection: 'column', gap: 6,
              }}>
              <span style={{ fontFamily: 'Outfit', fontWeight: 700, fontSize: 19, letterSpacing: '-0.015em' }}>{t.name}</span>
              <span style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--ink-soft)' }}>{t.blurb}</span>
              <span style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4 }}>
                <strong style={{ color: 'var(--ink)' }}>Best for:</strong> {t.best}
              </span>
            </button>
          );
        })}
      </div>
      <button onClick={() => alert('Quiz: 4 quick questions to help you pick. (Demo)')}
        style={{ marginTop: 16, background: 'transparent', border: 'none', color: 'var(--ink)', textDecoration: 'underline', textUnderlineOffset: 3, cursor: 'pointer', fontWeight: 500, fontSize: 14, padding: 0, fontFamily: 'inherit' }}>
        Not sure which? Take the 30-second quiz →
      </button>
    </>
  );
}

function Field({ label, hint, children, full }) {
  return (
    <label style={{ display: 'block', gridColumn: full ? '1 / -1' : 'auto' }}>
      <span style={{ display: 'block', fontWeight: 600, fontSize: 13, marginBottom: 6 }}>{label}</span>
      {children}
      {hint && <span style={{ display: 'block', fontSize: 12, color: 'var(--muted)', marginTop: 6 }}>{hint}</span>}
    </label>
  );
}

function Step3Principal({ data, set }) {
  const p = data.principal || {};
  const upd = (k, v) => set({ principal: { ...p, [k]: v } });
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20, padding: '10px 14px', background: 'var(--paper-2)', border: '1px solid var(--line-cream)', borderRadius: 'var(--r-md)' }}>
        <Icon name="lock" size={16}/>
        <span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>
          <strong>AES-256 encrypted.</strong> Drafts auto-delete from our servers in 1 hour.
        </span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Field label="Full legal name" full>
          <input className="input" placeholder="Jane A. Smith" value={p.name || ''} onChange={(e) => upd('name', e.target.value)}/>
        </Field>
        <Field label="Date of birth">
          <input className="input" type="date" value={p.dob || ''} onChange={(e) => upd('dob', e.target.value)}/>
        </Field>
        <Field label="Last 4 of SSN" hint="Used to identify you in financial filings.">
          <input className="input" maxLength="4" placeholder="1234" value={p.ssn || ''} onChange={(e) => upd('ssn', e.target.value.replace(/\D/g, ''))}/>
        </Field>
        <Field label="Street address" full>
          <input className="input" placeholder="Start typing your address…" value={p.address || ''} onChange={(e) => upd('address', e.target.value)}/>
        </Field>
        <Field label="City">
          <input className="input" value={p.city || ''} onChange={(e) => upd('city', e.target.value)}/>
        </Field>
        <Field label="ZIP">
          <input className="input" maxLength="10" value={p.zip || ''} onChange={(e) => upd('zip', e.target.value)}/>
        </Field>
      </div>
    </>
  );
}

function Step4Agent({ data, set }) {
  const a = data.agent || {};
  const upd = (k, v) => set({ agent: { ...a, [k]: v } });
  return (
    <>
      {data.type === 'durable' && (
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 20, padding: '12px 14px', background: 'rgba(201,243,106,0.18)', border: '1.5px solid var(--ink)', borderRadius: 'var(--r-md)' }}>
          <Icon name="shield" size={18}/>
          <div style={{ fontSize: 13, lineHeight: 1.55 }}>
            <strong>Heads-up:</strong> Durable POAs stay valid even if you become incapacitated. Choose someone you trust deeply with both money and discretion.
          </div>
        </div>
      )}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Field label="Agent's full legal name" full>
          <input className="input" placeholder="John B. Doe" value={a.name || ''} onChange={(e) => upd('name', e.target.value)}/>
        </Field>
        <Field label="Relationship to you" full>
          <select className="select" value={a.relationship || ''} onChange={(e) => upd('relationship', e.target.value)}>
            <option value="">Select…</option>
            {['Spouse','Parent','Child','Sibling','Friend','Attorney','Other'].map(r => <option key={r} value={r}>{r}</option>)}
          </select>
        </Field>
        <Field label="Agent's address" full>
          <input className="input" value={a.address || ''} onChange={(e) => upd('address', e.target.value)}/>
        </Field>
        <Field label="Phone">
          <input className="input" placeholder="(555) 123-4567" value={a.phone || ''} onChange={(e) => upd('phone', e.target.value)}/>
        </Field>
        <Field label="Email">
          <input className="input" type="email" value={a.email || ''} onChange={(e) => upd('email', e.target.value)}/>
        </Field>
      </div>
      <label style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 20, cursor: 'pointer' }}>
        <input type="checkbox" checked={!!a.successor} onChange={(e) => upd('successor', e.target.checked)} style={{ width: 18, height: 18, accentColor: 'var(--ink)' }}/>
        <span style={{ fontSize: 14, fontWeight: 500 }}>Add a successor agent (steps in if my first agent can't serve)</span>
      </label>
    </>
  );
}

function Step5Powers({ data, set }) {
  const powers = data.powers || [];
  const toggle = (id) => set({ powers: powers.includes(id) ? powers.filter(p => p !== id) : [...powers, id] });
  const allOn = powers.length === POWERS.length;
  return (
    <>
      <button onClick={() => set({ powers: allOn ? [] : POWERS.map(p => p.id) })}
        style={{ marginBottom: 16, background: allOn ? 'var(--ink)' : 'var(--paper-2)', color: allOn ? 'var(--accent)' : 'var(--ink)', border: '1.5px solid var(--ink)', borderRadius: 'var(--r-pill)', padding: '8px 14px', fontFamily: 'inherit', fontWeight: 600, fontSize: 13, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 8 }}>
        <Icon name={allOn ? 'check' : 'plus'} size={14}/>
        {allOn ? 'All powers selected' : 'Grant all powers'}
      </button>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {POWERS.map(p => {
          const on = powers.includes(p.id);
          const isHot = p.desc.includes('Hot');
          return (
            <button key={p.id} onClick={() => toggle(p.id)}
              style={{
                textAlign: 'left', padding: '14px 16px',
                border: `1.5px solid ${on ? 'var(--ink)' : 'var(--line-cream)'}`,
                borderRadius: 'var(--r-md)',
                background: on ? 'var(--accent)' : 'var(--surface)',
                cursor: 'pointer', fontFamily: 'inherit',
                display: 'flex', gap: 12, alignItems: 'flex-start',
              }}>
              <span style={{
                width: 22, height: 22, borderRadius: 4,
                border: '1.5px solid var(--ink)',
                background: on ? 'var(--ink)' : 'transparent',
                color: on ? 'var(--accent)' : 'transparent',
                display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 1,
              }}>
                <Icon name="check" size={12}/>
              </span>
              <span style={{ flex: 1 }}>
                <span style={{ display: 'block', fontWeight: 700, fontSize: 14 }}>{p.label}</span>
                <span style={{ display: 'block', fontSize: 12, color: isHot ? 'var(--warn)' : 'var(--muted)', marginTop: 2 }}>{p.desc}</span>
              </span>
            </button>
          );
        })}
      </div>
    </>
  );
}

function Step6Options({ data, set }) {
  const o = data.options || {};
  const upd = (k, v) => set({ options: { ...o, [k]: v } });
  return (
    <>
      <Field label="When should this POA take effect?" full>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
          {[['immediate','Immediately'],['date','On a specific date'],['springing','Only on incapacity']].map(([v, l]) => (
            <label key={v} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '14px 14px',
              border: '1.5px solid var(--ink)', borderRadius: 'var(--r-md)',
              background: o.effective === v ? 'var(--accent)' : 'var(--surface)',
              cursor: 'pointer', fontWeight: 600, fontSize: 14,
            }}>
              <input type="radio" name="effective" checked={o.effective === v} onChange={() => upd('effective', v)}
                style={{ accentColor: 'var(--ink)' }}/>
              {l}
            </label>
          ))}
        </div>
      </Field>
      <div style={{ height: 16 }}/>
      <Field label="When does this POA terminate?" full>
        <select className="select" value={o.terminate || ''} onChange={(e) => upd('terminate', e.target.value)}>
          <option value="">Choose…</option>
          <option value="death">On my death (default)</option>
          <option value="revoke">When I revoke it in writing</option>
          <option value="date">On a specific date</option>
        </select>
      </Field>
      <div style={{ height: 16 }}/>
      <Field label="Custom instructions (optional)" hint="Anything else your agent should know — e.g., 'Coordinate with my accountant Maria Lopez before any major financial moves.'" full>
        <textarea className="input" rows="4" value={o.notes || ''} onChange={(e) => upd('notes', e.target.value)}
          style={{ resize: 'vertical', minHeight: 100, fontFamily: 'inherit' }}/>
      </Field>
    </>
  );
}

function PreviewPDF({ data }) {
  const stateName = (US_STATES.find(s => s[0] === data.state) || [])[1] || '—';
  const typeName = (POA_TYPES.find(t => t.id === data.type) || {}).name || '—';
  return (
    <div style={{
      background: '#fff', border: '1.5px solid var(--ink)', borderRadius: 6,
      padding: 28, boxShadow: '6px 6px 0 0 var(--ink)',
      fontFamily: 'Inter', fontSize: 11, lineHeight: 1.6, color: 'var(--ink)',
      aspectRatio: '8.5 / 11', overflow: 'hidden', position: 'relative',
    }}>
      <div style={{ borderBottom: '2px solid var(--ink)', paddingBottom: 8, marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
        <span style={{ fontFamily: 'Outfit', fontWeight: 700, fontSize: 16, letterSpacing: '-0.02em' }}>{stateName.toUpperCase()} {typeName.toUpperCase()} POWER OF ATTORNEY</span>
      </div>
      <p style={{ marginBottom: 10, fontSize: 10 }}>
        I, <strong>{(data.principal && data.principal.name) || '___________________'}</strong>, of <strong>{(data.principal && data.principal.address) || '_______________'}</strong>, {(data.principal && data.principal.city) || '___________'}, {data.state || '__'}, being of sound mind, do hereby appoint my agent under this {typeName} Power of Attorney.
      </p>
      <p style={{ fontFamily: 'Outfit', fontWeight: 600, fontSize: 12, marginTop: 14, marginBottom: 6 }}>1. AGENT</p>
      <p style={{ marginBottom: 10, fontSize: 10 }}>
        I appoint <strong>{(data.agent && data.agent.name) || '___________________'}</strong> ({(data.agent && data.agent.relationship) || '_______'}), of <strong>{(data.agent && data.agent.address) || '_______________'}</strong>, as my Attorney-in-Fact.
      </p>
      <p style={{ fontFamily: 'Outfit', fontWeight: 600, fontSize: 12, marginTop: 14, marginBottom: 6 }}>2. POWERS GRANTED</p>
      <p style={{ marginBottom: 8, fontSize: 10 }}>
        My agent shall have authority over the following matters:
      </p>
      <ul style={{ paddingLeft: 18, fontSize: 10, marginBottom: 12 }}>
        {(data.powers || []).slice(0, 6).map(pid => {
          const p = POWERS.find(x => x.id === pid);
          return p ? <li key={pid}>{p.label}</li> : null;
        })}
        {(data.powers || []).length > 6 && <li><em>+{(data.powers || []).length - 6} more</em></li>}
        {(data.powers || []).length === 0 && <li style={{ color: 'var(--muted)' }}>(no powers selected yet)</li>}
      </ul>
      <p style={{ fontFamily: 'Outfit', fontWeight: 600, fontSize: 12, marginTop: 14, marginBottom: 6 }}>3. EFFECTIVE DATE</p>
      <p style={{ fontSize: 10 }}>
        This Power of Attorney shall take effect <strong>{
          data.options && data.options.effective === 'immediate' ? 'immediately upon signing' :
          data.options && data.options.effective === 'springing' ? 'only upon a written determination of my incapacity' :
          data.options && data.options.effective === 'date' ? 'on the date specified' :
          '___________'
        }</strong>.
      </p>
      <div style={{ position: 'absolute', bottom: 24, left: 28, right: 28, fontSize: 9, color: 'var(--muted)', display: 'flex', justifyContent: 'space-between', borderTop: '1px solid var(--line-cream)', paddingTop: 8 }}>
        <span>Page 1 of 4 · Generated by POA Forms · {new Date().toLocaleDateString()}</span>
        <span>{stateName} statute compliant</span>
      </div>
    </div>
  );
}

function Step7Review({ data, jumpTo }) {
  const stateName = (US_STATES.find(s => s[0] === data.state) || [])[1] || '—';
  const typeName = (POA_TYPES.find(t => t.id === data.type) || {}).name || '—';
  const sections = [
    { step: 1, label: 'State', value: stateName },
    { step: 2, label: 'Type', value: typeName + ' POA' },
    { step: 3, label: 'You', value: (data.principal && data.principal.name) || '—' },
    { step: 4, label: 'Agent', value: (data.agent && data.agent.name) || '—' },
    { step: 5, label: 'Powers', value: `${(data.powers || []).length} of ${POWERS.length} selected` },
    { step: 6, label: 'Effective', value: (data.options && data.options.effective) || '—' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 'var(--s-7)', alignItems: 'flex-start' }} className="rev-grid">
      <div>
        <div style={{ display: 'grid', gap: 1, background: 'var(--ink)', border: '1.5px solid var(--ink)', borderRadius: 'var(--r-md)', overflow: 'hidden' }}>
          {sections.map(s => (
            <div key={s.step} style={{ background: 'var(--surface)', padding: '14px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
              <div>
                <div className="eyebrow" style={{ color: 'var(--muted)', fontSize: 11 }}>Step {s.step} · {s.label}</div>
                <div style={{ fontWeight: 600, fontSize: 15, marginTop: 2 }}>{s.value}</div>
              </div>
              <button onClick={() => jumpTo(s.step)} style={{ background: 'transparent', border: '1.5px solid var(--ink)', borderRadius: 'var(--r-pill)', padding: '6px 12px', fontFamily: 'inherit', fontWeight: 600, fontSize: 12, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <Icon name="edit" size={12}/> Edit
              </button>
            </div>
          ))}
        </div>
      </div>
      <div>
        <div className="eyebrow" style={{ marginBottom: 10, color: 'var(--muted)' }}>Live preview</div>
        <PreviewPDF data={data}/>
      </div>
      <style>{`@media (max-width: 1000px) { .rev-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

function Step8Output({ data }) {
  const [emailed, setEmailed] = React.useState(false);
  const stateName = (US_STATES.find(s => s[0] === data.state) || [])[1] || 'Your';
  const typeName = (POA_TYPES.find(t => t.id === data.type) || {}).name || 'POA';
  return (
    <div>
      {/* Moment 1 — immediate */}
      <div style={{
        background: 'var(--accent)', color: 'var(--ink)',
        borderRadius: 'var(--r-xl)', padding: 'var(--s-8)',
        border: '1.5px solid var(--ink)', boxShadow: '8px 8px 0 0 var(--ink)',
        marginBottom: 'var(--s-7)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
          <span style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--ink)', color: 'var(--accent)', display: 'grid', placeItems: 'center' }}>
            <Icon name="check" size={16}/>
          </span>
          <span className="eyebrow">Moment 01 — Your file is ready</span>
        </div>
        <h2 style={{ marginBottom: 8 }}>Your {stateName} {typeName} POA is ready.</h2>
        <p style={{ marginBottom: 24, fontSize: 16, color: 'var(--ink-soft)', maxWidth: '50ch' }}>
          No email gate. No upsell. Download in PDF or editable Word — both are clean, watermark-free, and statute-compliant for {stateName}.
        </p>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <a href="#" className="btn" style={{ background: 'var(--ink)', color: 'var(--accent)' }}>
            <Icon name="download" size={16}/> Download PDF
          </a>
          <a href="#" className="btn ghost" style={{ background: 'var(--paper)', borderColor: 'var(--ink)' }}>
            <Icon name="download" size={16}/> Download Word
          </a>
        </div>
      </div>

      {/* Moment 2 — soft email capture */}
      <div style={{ background: 'var(--surface)', borderRadius: 'var(--r-xl)', padding: 'var(--s-7)', border: '1.5px solid var(--line-cream)', marginBottom: 'var(--s-7)' }}>
        <div className="eyebrow" style={{ marginBottom: 10, color: 'var(--muted)' }}>Moment 02 — Optional</div>
        <h3 style={{ marginBottom: 8 }}>Want a backup copy emailed to you?</h3>
        <p style={{ color: 'var(--muted)', fontSize: 14, marginBottom: 16 }}>
          Stored at AES-256. Max 1 email/week. Unsubscribe in 1 click.
        </p>
        {emailed ? (
          <div style={{ color: 'var(--ok)', fontWeight: 600 }}>✓ Sent to your inbox.</div>
        ) : (
          <form onSubmit={(e) => { e.preventDefault(); setEmailed(true); }} style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <input className="input" type="email" placeholder="you@example.com" required style={{ flex: 1, minWidth: 220 }}/>
            <button className="btn" type="submit">Send to email</button>
            <button type="button" className="btn ghost" style={{ borderColor: 'transparent' }}>No thanks</button>
          </form>
        )}
      </div>

      {/* Moment 3 — BN funnel */}
      <div style={{ background: 'var(--ink)', color: 'var(--paper)', borderRadius: 'var(--r-xl)', padding: 'var(--s-8)' }}>
        <div className="eyebrow" style={{ color: 'var(--accent)', marginBottom: 10 }}>Moment 03 — Notarize</div>
        <h2 style={{ color: 'var(--paper)', marginBottom: 8 }}>You're not done yet.</h2>
        <p style={{ color: 'rgba(245,241,232,0.78)', fontSize: 16, lineHeight: 1.55, maxWidth: '54ch', marginBottom: 24 }}>
          Your POA needs to be notarized to be legally enforceable in {stateName}. Pick how:
        </p>
        <div style={{ display: 'grid', gap: 10 }}>
          <a href="#" style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '20px 22px', border: `2px solid var(--accent)`,
            borderRadius: 'var(--r-md)', textDecoration: 'none', color: 'var(--paper)',
            background: 'rgba(201,243,106,0.08)',
          }}>
            <div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}>
                <span style={{ background: 'var(--accent)', color: 'var(--ink)', fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', padding: '3px 8px', borderRadius: 4 }}>RECOMMENDED</span>
              </div>
              <div style={{ fontFamily: 'Outfit', fontWeight: 700, fontSize: 18 }}>Online — BlueNotary, $25</div>
              <div style={{ fontSize: 13, color: 'rgba(245,241,232,0.7)', marginTop: 2 }}>~10 min · 24/7 · ID-verified</div>
            </div>
            <Icon name="arrow" size={18}/>
          </a>
          <a href="#" style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '20px 22px', border: '1.5px solid rgba(245,241,232,0.2)',
            borderRadius: 'var(--r-md)', textDecoration: 'none', color: 'var(--paper)',
          }}>
            <div>
              <div style={{ fontFamily: 'Outfit', fontWeight: 600, fontSize: 17 }}>In-person — bank or local notary</div>
              <div style={{ fontSize: 13, color: 'rgba(245,241,232,0.6)', marginTop: 2 }}>$5–25 · Find one near you</div>
            </div>
            <Icon name="arrow" size={18}/>
          </a>
          <a href="#" style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '20px 22px', border: '1.5px solid rgba(245,241,232,0.2)',
            borderRadius: 'var(--r-md)', textDecoration: 'none', color: 'var(--paper)',
          }}>
            <div>
              <div style={{ fontFamily: 'Outfit', fontWeight: 600, fontSize: 17 }}>DIY — print and find your own notary</div>
              <div style={{ fontSize: 13, color: 'rgba(245,241,232,0.6)', marginTop: 2 }}>Free · You handle the legwork</div>
            </div>
            <Icon name="arrow" size={18}/>
          </a>
        </div>
      </div>
    </div>
  );
}

// ── Wizard host ────────────────────────────────────────────────────────
function Wizard() {
  const [step, setStep] = React.useState(1);
  const [data, setData] = React.useState(loadInitial);
  const [autoSaved, setAutoSaved] = React.useState(false);

  const set = (patch) => setData((d) => ({ ...d, ...patch }));

  // jump to first incomplete step on mount if URL had params
  React.useEffect(() => {
    if (data.state && data.type && step === 1) setStep(3);
    else if (data.state && step === 1) setStep(2);
  }, []);

  // persist + auto-save indicator
  React.useEffect(() => {
    try {
      localStorage.setItem('poa.draft', JSON.stringify(data));
      setAutoSaved(true);
      const t = setTimeout(() => setAutoSaved(false), 1400);
      return () => clearTimeout(t);
    } catch (e) {}
  }, [data]);

  const canAdvance = (() => {
    if (step === 1) return !!data.state;
    if (step === 2) return !!data.type;
    if (step === 3) return data.principal && data.principal.name && data.principal.address;
    if (step === 4) return data.agent && data.agent.name;
    if (step === 5) return (data.powers || []).length > 0;
    if (step === 6) return data.options && data.options.effective;
    if (step === 7) return true;
    return true;
  })();

  const next = () => setStep(s => Math.min(8, s + 1));
  const prev = () => setStep(s => Math.max(1, s - 1));
  const jumpTo = (n) => setStep(n);

  const stepProps = { data, set };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--paper)' }}>
      {/* Wizard topbar */}
      <header style={{ position: 'sticky', top: 0, zIndex: 30, background: 'rgba(245,241,232,0.92)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)', borderBottom: '1px solid var(--line-cream)' }}>
        <div className="container" style={{ padding: '14px var(--s-6)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
          <BrandMark/>
          <div style={{ flex: 1, minWidth: 280, display: 'flex', justifyContent: 'center' }} className="wiz-stepper-wrap">
            <StepIndicator current={step} onJump={jumpTo}/>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 12, color: 'var(--muted)' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: autoSaved ? 'var(--ok)' : 'var(--line-cream)', transition: 'background 200ms' }}/>
              {autoSaved ? 'Auto-saved' : 'Saved to your browser'}
            </span>
            <span style={{ fontWeight: 600, color: 'var(--ink)' }}>{step}/8</span>
          </div>
        </div>
      </header>

      <main className="container" style={{ padding: 'var(--s-9) var(--s-6) var(--s-11)' }}>
        {/* Step content */}
        <div style={{ maxWidth: step === 7 || step === 8 ? '100%' : 880, marginInline: step === 7 || step === 8 ? '0' : 'auto' }}>
          {step === 1 && (
            <StepShell kicker="Step 1 of 8" title="Where do you live?" subtitle="POA rules vary by state. Pick yours and we'll preload the right witness, notarization, and statutory rules.">
              <Step1State {...stepProps}/>
            </StepShell>
          )}
          {step === 2 && (
            <StepShell kicker="Step 2 of 8" title="What kind of POA do you need?" subtitle="The most common is Durable. If you're not sure, we can ask a few questions to pick for you.">
              <Step2Type {...stepProps}/>
            </StepShell>
          )}
          {step === 3 && (
            <StepShell kicker="Step 3 of 8" title="Tell us about you (the Principal)." subtitle="This is the legal full name and address that will appear on the document.">
              <Step3Principal {...stepProps}/>
            </StepShell>
          )}
          {step === 4 && (
            <StepShell kicker="Step 4 of 8" title="Who is your agent?" subtitle="Your agent (also called Attorney-in-Fact) is the trusted person you're empowering to act on your behalf.">
              <Step4Agent {...stepProps}/>
            </StepShell>
          )}
          {step === 5 && (
            <StepShell kicker="Step 5 of 8" title="What can your agent do?" subtitle="Pick which categories of decisions your agent has authority over. You can grant all, or only what's needed.">
              <Step5Powers {...stepProps}/>
            </StepShell>
          )}
          {step === 6 && (
            <StepShell kicker="Step 6 of 8" title="A few final options." subtitle="Effective date, termination, and any custom instructions.">
              <Step6Options {...stepProps}/>
            </StepShell>
          )}
          {step === 7 && (
            <>
              <div className="eyebrow" style={{ color: 'var(--muted)', marginBottom: 8 }}>Step 7 of 8</div>
              <h2 style={{ marginBottom: 12 }}>Quick review.</h2>
              <p className="lede" style={{ marginBottom: 'var(--s-7)' }}>Click any field to jump back and edit. Your live preview is on the right.</p>
              <Step7Review data={data} jumpTo={jumpTo}/>
            </>
          )}
          {step === 8 && (
            <>
              <Step8Output data={data}/>
            </>
          )}
        </div>

        {/* Footer nav */}
        {step < 8 && (
          <div style={{
            position: 'sticky', bottom: 0, marginTop: 'var(--s-9)',
            background: 'var(--paper)', borderTop: '1.5px solid var(--ink)',
            padding: '16px 0',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap',
          }}>
            <button onClick={prev} disabled={step === 1}
              className="btn ghost" style={{ borderColor: step === 1 ? 'transparent' : 'var(--ink)', opacity: step === 1 ? 0.4 : 1 }}>
              <Icon name="chevL" size={14}/> Back
            </button>
            <div style={{ fontSize: 13, color: 'var(--muted)' }}>
              {step < 7 ? 'Auto-saves every change · Resume within 24 hrs' : ''}
            </div>
            <button onClick={next} disabled={!canAdvance}
              className="btn primary" style={{ opacity: canAdvance ? 1 : 0.5, cursor: canAdvance ? 'pointer' : 'not-allowed' }}>
              {step === 6 ? 'Review' : (step === 7 ? 'Generate my POA' : 'Continue')}
              <Icon name="chevR" size={14}/>
            </button>
          </div>
        )}

        {step === 8 && (
          <div style={{ marginTop: 'var(--s-9)', textAlign: 'center' }}>
            <a href="index.html" className="btn ghost" style={{ borderColor: 'var(--ink)' }}>
              ← Back to POA Forms home
            </a>
          </div>
        )}
      </main>
      <style>{`
        @media (max-width: 720px) {
          .wiz-stepper-wrap { display: none !important; }
        }
      `}</style>
    </div>
  );
}

window.Wizard = Wizard;
