// Extra step components (Certs, Equipment, Playbook, Market) + the LiveSystemPanel
// that visualizes the AI agent being trained in real-time.

const { useState: useStateOBX } = React;

/* ============== STEP · CERTIFICATIONS ============== */
function StepCerts({ cfg, get, update }) {
  const detail = getOnboardingDetail(cfg.cat);
  const licenses    = get('licenses', detail.licenses.slice(0, 2));
  const certs       = get('certs',    detail.certifications.slice(0, 3));
  const carriers    = get('carriers', detail.carriers.slice(0, 4));
  const setLicenses = (next) => update({ licenses: next });
  const setCerts    = (next) => update({ certs: next });
  const setCarriers = (next) => update({ carriers: next });
  const toggle = (list, item, setter) => setter(list.includes(item) ? list.filter(x => x !== item) : [...list, item]);

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <CardSection title="Licenses you hold" hint="Anything on the truck side panel. The system uses these to know what you can self-install vs. subcontract.">
        <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
          {detail.licenses.map(l => (
            <ToggleChip key={l} value={licenses.includes(l)} onClick={() => toggle(licenses, l, setLicenses)} label={l}/>
          ))}
        </div>
        <div style={{ marginTop:14 }}>
          <FreeAdder list={licenses} onAdd={(v) => setLicenses([...licenses, v])} placeholder="Add another license…"/>
        </div>
      </CardSection>

      <CardSection title="Manufacturer + trade certifications" hint="These unlock warranties, factory pricing, and credibility on the quote." accent="var(--chart-400)">
        {detail.certifications.length === 0 ? <Empty/> : (
          <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
            {detail.certifications.map(c => (
              <ToggleChip key={c} value={certs.includes(c)} onClick={() => toggle(certs, c, setCerts)} label={c}/>
            ))}
          </div>
        )}
      </CardSection>

      {detail.carriers.length > 0 && (
        <CardSection title="Insurance carriers you work with" hint="The system pre-fills supplements + claim language for these carriers." accent="var(--lilac-500)">
          <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
            {detail.carriers.map(c => (
              <ToggleChip key={c} value={carriers.includes(c)} onClick={() => toggle(carriers, c, setCarriers)} label={c}/>
            ))}
          </div>
          <div className="ob-grid-2col" style={{ marginTop:14, display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            <Field label="Insurance work · % of revenue">
              <TextInput type="number" value={get('insurancePct', 35)} onChange={v => update({ insurancePct:v })} suffix="%"/>
            </Field>
            <Field label="Average claim payout you see">
              <TextInput type="number" value={get('avgClaim', 12400)} onChange={v => update({ avgClaim:v })} prefix="$"/>
            </Field>
          </div>
        </CardSection>
      )}

      <CardSection title="Reputation signals" hint="The proof that lives on your website + Google. The AI cites these on the quote.">
        <div className="ob-grid-3col" style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14 }}>
          <Field label="Google review count"><TextInput type="number" value={get('reviewCount', 184)} onChange={v => update({ reviewCount:v })}/></Field>
          <Field label="Google rating"><TextInput type="number" value={get('reviewRating', 4.9)} onChange={v => update({ reviewRating:v })} suffix="stars"/></Field>
          <Field label="BBB rating"><SelectInput value={get('bbb')} onChange={v => update({ bbb:v })} options={['A+','A','B','Not rated']}/></Field>
          <Field label="Years in business"><TextInput type="number" value={get('years', 12)} onChange={v => update({ years:v })}/></Field>
          <Field label="Total jobs lifetime"><TextInput type="number" value={get('jobs', 2400)} onChange={v => update({ jobs:v })}/></Field>
          <Field label="NPS · last quarter"><TextInput type="number" value={get('nps', 78)} onChange={v => update({ nps:v })}/></Field>
        </div>
      </CardSection>
    </div>
  );
}

/* ============== STEP · EQUIPMENT ============== */
function StepEquipment({ cfg, get, update }) {
  const detail = getOnboardingDetail(cfg.cat);
  const fleet = get('fleet', Object.fromEntries(detail.equipment.map(e => [e.id, e.def])));
  const set = (id, v) => update({ fleet: { ...fleet, [id]: v } });
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <CardSection title="Fleet + field tools" hint="Drives dispatch logic — the system won't promise a crane in 90 min if you don't own one.">
        <div className="ob-grid-2col" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
          {detail.equipment.map(e => (
            <Field key={e.id} label={e.name}>
              {e.kind === 'number' && <TextInput type="number" value={fleet[e.id] ?? e.def} onChange={v => set(e.id, v)}/>}
              {e.kind === 'toggle' && <Toggle value={!!(fleet[e.id] ?? e.def)} onChange={v => set(e.id, v)} label={(fleet[e.id] ?? e.def) ? 'Yes, we own one' : 'No, we sub it out'}/>}
              {e.kind === 'select' && <SelectInput value={fleet[e.id] ?? e.def} onChange={v => set(e.id, v)} options={e.opts}/>}
            </Field>
          ))}
        </div>
      </CardSection>

      <CardSection title="Crew composition" hint="Specialty roles drive what kind of work the system routes to you.">
        <div className="ob-grid-4col" style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:14 }}>
          {[
            ['Lead estimators', 'leadEst', 2],
            ['Senior techs',    'seniorTechs', 4],
            ['Apprentices',     'apprentices', 3],
            ['Office / CSR',    'csr', 2],
            ['Sales / closers', 'sales', 1],
            ['Crew foremen',    'foremen', 3],
            ['Subcontractors',  'subs', 0],
            ['1099 day-labor',  'dayLabor', 0],
          ].map(([label, key, def]) => (
            <Field key={key} label={label}>
              <TextInput type="number" value={get(key, def)} onChange={v => update({ [key]:v })}/>
            </Field>
          ))}
        </div>
      </CardSection>

      <CardSection title="Service area constraints" hint="Boundaries the system respects when accepting / routing leads." accent="var(--lilac-500)">
        <div className="ob-grid-2col" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
          <Field label="ZIP codes you serve" hint="Comma-separated. The system rejects anything outside.">
            <TextInput value={get('zips')} onChange={v => update({ zips:v })} placeholder="33602, 33603, 33604, 33606…"/>
          </Field>
          <Field label="Outside-zip travel uplift">
            <TextInput type="number" value={get('outsideUp', 18)} onChange={v => update({ outsideUp:v })} suffix="%"/>
          </Field>
          <Field label="Max simultaneous jobs">
            <TextInput type="number" value={get('maxJobs', 6)} onChange={v => update({ maxJobs:v })}/>
          </Field>
          <Field label="Earliest start each day">
            <SelectInput value={get('startTime', '7:00 AM')} onChange={v => update({ startTime:v })} options={['6:00 AM','6:30 AM','7:00 AM','7:30 AM','8:00 AM','9:00 AM']}/>
          </Field>
        </div>
      </CardSection>
    </div>
  );
}

/* ============== STEP · PLAYBOOK (objections + rebuttals) ============== */
function StepPlaybook({ cfg, get, update }) {
  const detail = getOnboardingDetail(cfg.cat);
  const plays = get('plays', detail.objections.map((p, i) => ({ id:`p-${i}`, ...p, on:true })));
  const set = (next) => update({ plays: next });
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <CardSection title={`The ${cfg.industryLabel || cfg.serviceName} objections you hear weekly`} hint="The AI uses your exact rebuttals on chat. Edit them so they sound like you.">
        <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          {plays.map((p, i) => (
            <div key={p.id} style={{ padding:'14px 16px', background: p.on ? '#fff' : 'var(--paper-3)', border:'1px solid var(--line)', borderRadius:14, opacity: p.on ? 1 : 0.6 }}>
              <div style={{ display:'flex', alignItems:'flex-start', gap:12 }}>
                <button onClick={() => { plays[i] = { ...p, on:!p.on }; set([...plays]); }}
                  style={{ width:36, height:20, borderRadius:99, background: p.on ? 'var(--ink)' : 'var(--mute-3)', border:0, cursor:'pointer', position:'relative', flexShrink:0, marginTop:4 }}>
                  <span style={{ position:'absolute', top:2, left: p.on ? 18 : 2, width:16, height:16, borderRadius:99, background: p.on ? 'var(--chart-300)' : '#fff', transition:'left 0.2s' }}/>
                </button>
                <div style={{ flex:1, display:'flex', flexDirection:'column', gap:8 }}>
                  <div>
                    <div style={{ fontSize:9.5, fontWeight:700, letterSpacing:'0.14em', color:'var(--lilac-700)', marginBottom:2 }}>WHAT THE CUSTOMER SAYS</div>
                    <input value={p.o} onChange={e => { plays[i] = { ...p, o:e.target.value }; set([...plays]); }}
                      style={{ width:'100%', border:0, outline:0, background:'transparent', fontSize:14.5, fontStyle:'italic', color:'var(--ink)', fontFamily:'var(--font-body)' }}/>
                  </div>
                  <div>
                    <div style={{ fontSize:9.5, fontWeight:700, letterSpacing:'0.14em', color:'var(--chart-900)', marginBottom:2 }}>YOUR REBUTTAL</div>
                    <textarea value={p.r} onChange={e => { plays[i] = { ...p, r:e.target.value }; set([...plays]); }}
                      rows={2}
                      style={{ width:'100%', border:0, outline:0, background:'transparent', fontSize:13.5, color:'var(--ink)', fontFamily:'var(--font-body)', resize:'vertical', lineHeight:1.45 }}/>
                  </div>
                </div>
                <button onClick={() => set(plays.filter(x => x.id !== p.id))} style={{ background:'transparent', border:0, color:'var(--mute-3)', cursor:'pointer', fontSize:18, lineHeight:1, marginTop:2 }}>×</button>
              </div>
            </div>
          ))}
          <button onClick={() => set([...plays, { id:`p-${Date.now()}`, o:'New objection…', r:'Your rebuttal…', on:true }])}
            style={{ padding:'12px 16px', background:'transparent', border:'1.5px dashed var(--mute-3)', borderRadius:12, fontFamily:'var(--font-body)', fontSize:13, fontWeight:600, color:'var(--mute-1)', cursor:'pointer' }}>+ Add an objection</button>
        </div>
      </CardSection>

      <CardSection title="Common FAQs you get pre-quote" hint="These are the qs leads ask BEFORE they're serious. The AI handles them so your team doesn't." accent="var(--lilac-500)">
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {(get('faqs', [
            { q:'How long does a typical job take?',    a:'For your scope, usually 1–3 days start to finish.' },
            { q:'Do you offer financing?',              a:'Yes — 0% / 60 mo through GoodLeap for qualified buyers.' },
            { q:"What's your warranty?",                a:'25 years on workmanship, manufacturer covers materials separately.' },
            { q:'Are you licensed and insured?',        a:'Yes — license #CCC1330218, $2M GL + WC.' },
          ])).map((f, i, arr) => (
            <div key={i} style={{ padding:'10px 12px', background:'var(--paper-3)', borderRadius:10, border:'1px solid var(--line-2)' }}>
              <input value={f.q} onChange={e => { arr[i] = { ...f, q:e.target.value }; update({ faqs:[...arr] }); }}
                style={{ width:'100%', border:0, outline:0, background:'transparent', fontSize:13, fontWeight:600, fontFamily:'var(--font-body)' }}/>
              <input value={f.a} onChange={e => { arr[i] = { ...f, a:e.target.value }; update({ faqs:[...arr] }); }}
                style={{ width:'100%', border:0, outline:0, background:'transparent', fontSize:12.5, color:'var(--mute-1)', marginTop:3, fontFamily:'var(--font-body)' }}/>
            </div>
          ))}
        </div>
      </CardSection>
    </div>
  );
}

/* ============== STEP · LOCAL MARKET ============== */
function StepMarket({ cfg, get, update }) {
  const detail = getOnboardingDetail(cfg.cat);
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <CardSection title={`Ground truth · ${cfg.industryLabel || cfg.serviceName} in your market`} hint="Stuff nobody else gets right. This is what makes your AI smarter than your competitor's AI.">
        <div className="ob-grid-2col" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
          {(detail.localMarket || []).map((m) => (
            <Field key={m.id} label={m.q}>
              {m.kind === 'number' && <TextInput type="number" value={get(m.id, m.def)} onChange={v => update({ [m.id]:v })} prefix={m.prefix} suffix={m.suffix}/>}
              {m.kind === 'text'   && <TextInput value={get(m.id, m.def)} onChange={v => update({ [m.id]:v })}/>}
              {m.kind === 'select' && <SelectInput value={get(m.id, m.def)} onChange={v => update({ [m.id]:v })} options={m.opts}/>}
              {m.kind === 'multi'  && (
                <div style={{ display:'flex', flexWrap:'wrap', gap:4 }}>
                  {m.opts.map(o => {
                    const list = get(m.id, m.def);
                    const sel = list.includes(o);
                    return <ToggleChip key={o} value={sel} onClick={() => update({ [m.id]: sel ? list.filter(x=>x!==o) : [...list, o] })} label={o}/>;
                  })}
                </div>
              )}
            </Field>
          ))}
        </div>
      </CardSection>

      <CardSection title="Neighborhood notes" hint="The local language that signals 'we live here'. AI uses it on chat to build trust." accent="var(--chart-400)">
        <Field label="HOA-heavy / gated neighborhoods" hint="Comma-separated. The bot acknowledges these specifically on intake.">
          <TextInput value={get('hoaHoods')} onChange={v => update({ hoaHoods:v })} placeholder="Tampa Palms, Westchase, Avila…"/>
        </Field>
        <div style={{ marginTop:14 }}>
          <Field label="Tough-pricing zips" hint="Areas where you regularly get beat on price.">
            <TextInput value={get('toughZips')} onChange={v => update({ toughZips:v })} placeholder="33647, 33625…"/>
          </Field>
        </div>
        <div style={{ marginTop:14 }}>
          <Field label="High-margin zips" hint="Areas where premium positioning wins.">
            <TextInput value={get('premiumZips')} onChange={v => update({ premiumZips:v })} placeholder="33602, 33606, 33629…"/>
          </Field>
        </div>
      </CardSection>

      <CardSection title="Competitors you actually lose to" hint="The AI tunes positioning + pricing against named competition in your market." accent="var(--lilac-500)">
        <Field label="Top 3 competitors (comma-separated)">
          <TextInput value={get('competitors')} onChange={v => update({ competitors:v })} placeholder="Acme Roofing, BlueShield, North Star…"/>
        </Field>
      </CardSection>
    </div>
  );
}

/* ============== LIVE SYSTEM PANEL ============== */
function LiveSystemPanel({ config, answers, stepIdx }) {
  if (!config) return null;
  const sections = [
    { id:'identity',  label:'Company identity',  filled: !!(answers.welcome?.company || answers.welcome?.dba) },
    { id:'license',   label:'Licensing + credibility', filled: !!(answers.certs?.licenses?.length || answers.certs?.certs?.length) },
    { id:'mix',       label:'Service mix',       filled: !!(answers.services?.subTrades?.length) },
    { id:'fleet',     label:'Equipment + crew',  filled: !!(answers.equipment?.fleet) },
    { id:'price',     label:'Price model',       filled: !!(answers.pricing?.rate || answers.pricing?.margin) },
    { id:'form',      label:'Estimate form',     filled: !!(answers.fields?.fields?.length) },
    { id:'memory',    label:'Job memory',        filled: !!(answers.history?.uploaded?.length) },
    { id:'intake',    label:'Intake script',     filled: !!(answers.intake?.qs?.length) },
    { id:'voice',     label:'Voice + tone',      filled: !!(answers.voice?.tone !== undefined || answers.voice?.use?.length) },
    { id:'playbook',  label:'Objection playbook',filled: !!(answers.playbook?.plays?.length) },
    { id:'connect',   label:'Stack connected',   filled: !!(answers.connect?.connected) },
    { id:'market',    label:'Local-market layer',filled: !!(answers.market) },
  ];
  const filled = sections.filter(s => s.filled).length;
  const pct = Math.round((filled / sections.length) * 100);
  const persona = answers.welcome?.dba || answers.welcome?.company || `${config.industryLabel || config.serviceName} agent`;
  const tone = answers.voice?.tone ?? 55;
  const toneLabel = tone < 33 ? 'Formal' : tone > 66 ? 'Casual' : 'Friendly';

  return (
    <div style={{ position:'sticky', top:160 }}>
      <div style={{ position:'relative', background:'var(--ink)', borderRadius:22, padding:'22px 22px 18px', color:'#fff', overflow:'hidden', boxShadow:'0 24px 60px rgba(12,14,16,0.18)' }}>
        <div style={{ position:'absolute', top:-60, right:-60, width:200, height:200, borderRadius:'50%', background:'var(--chart-700)', opacity:0.4, filter:'blur(40px)' }}/>
        <div style={{ position:'absolute', bottom:-80, left:-50, width:160, height:160, borderRadius:'50%', background:'var(--lilac-700)', opacity:0.35, filter:'blur(40px)' }}/>
        <div style={{ position:'relative' }}>
          <div style={{ display:'flex', alignItems:'center', gap:9 }}>
            <span style={{ width:6, height:6, borderRadius:99, background:'var(--chart-300)' }} className="pulse-soft"/>
            <span style={{ fontSize:10, fontWeight:700, letterSpacing:'0.14em', color:'var(--chart-300)' }}>AI AGENT · TRAINING</span>
          </div>
          <div className="display" style={{ fontSize:24, fontWeight:600, letterSpacing:'-0.025em', lineHeight:1.05, marginTop:6 }}>
            {persona}
          </div>
          <div style={{ fontSize:11, color:'rgba(255,255,255,0.55)', marginTop:2 }}>
            {config.serviceName} · {toneLabel} tone · {filled}/{sections.length} systems wired
          </div>

          <div style={{ marginTop:18, background:'rgba(255,255,255,0.08)', height:8, borderRadius:99, overflow:'hidden' }}>
            <div style={{ width:`${pct}%`, height:'100%', background:'linear-gradient(90deg, var(--chart-300), var(--lilac-300))', transition:'width 0.5s', boxShadow:'0 0 18px rgba(196,240,0,0.6)' }}/>
          </div>
          <div style={{ marginTop:8, display:'flex', justifyContent:'space-between', fontSize:10, fontFamily:'var(--font-mono)' }}>
            <span style={{ color:'rgba(255,255,255,0.55)' }}>configured</span>
            <span style={{ color:'#fff', fontWeight:700 }}>{pct}%</span>
          </div>
        </div>
      </div>

      <div style={{ marginTop:14, background:'#fff', borderRadius:18, padding:'14px 16px', border:'1px solid var(--line-2)' }}>
        <div className="eyebrow" style={{ color:'var(--mute-1)', marginBottom:8 }}>What's been wired</div>
        <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
          {sections.map((s) => (
            <div key={s.id} style={{ display:'flex', alignItems:'center', gap:9, padding:'6px 4px' }}>
              <span style={{ width:14, height:14, borderRadius:99, background: s.filled ? 'var(--chart-300)' : 'var(--paper-3)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                {s.filled && <IconCheck size={9} stroke="var(--ink)" sw={3}/>}
              </span>
              <span style={{ fontSize:12.5, fontWeight: s.filled ? 600 : 500, color: s.filled ? 'var(--ink)' : 'var(--mute-2)' }}>{s.label}</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ marginTop:14 }}>
        <StepPreview stepIdx={stepIdx} config={config} answers={answers}/>
      </div>
    </div>
  );
}

function StepPreview({ stepIdx, config, answers }) {
  const step = (window.ONBOARDING_STEPS_V2 || ONBOARDING_STEPS)[stepIdx];
  if (!step) return null;
  const id = step.id;

  if (id === 'pricing') {
    const p = answers.pricing || {};
    const rate = p.rate || 95;
    const base = (config.pricingExample.rate / 95) * 8400 + rate * 18;
    const tiers = [
      { name:'Good',   uplift:0,  margin: p.margin || 30 },
      { name:'Better', uplift:18, margin: (p.margin || 30) + 6 },
      { name:'Best',   uplift:42, margin: (p.margin || 30) + 12 },
    ];
    return (
      <div style={{ background:'#fff', borderRadius:16, padding:'18px', border:'1px solid var(--line-2)' }}>
        <div className="eyebrow" style={{ color:'var(--chart-700)' }}>LIVE QUOTE · TIER MODEL</div>
        <div style={{ marginTop:10, display:'flex', flexDirection:'column', gap:5 }}>
          {tiers.map((t, i) => {
            const amount = Math.round(base * (1 + t.uplift/100));
            return (
              <div key={t.name} style={{ display:'flex', alignItems:'center', gap:10, padding:'9px 12px', background: i === 1 ? 'var(--chart-100)' : 'var(--paper-3)', borderRadius:10, border: i===1?'1.5px solid var(--chart-400)':'1px solid var(--line-2)' }}>
                <span style={{ fontFamily:'var(--font-display)', fontSize:13, fontWeight:700, width:50 }}>{t.name}</span>
                <span style={{ flex:1, fontSize:10, color:'var(--mute-1)', fontFamily:'var(--font-mono)' }}>+{t.uplift}% · {t.margin}% margin</span>
                <span style={{ fontFamily:'var(--font-display)', fontSize:16, fontWeight:600 }}>${amount.toLocaleString()}</span>
              </div>
            );
          })}
        </div>
        <div style={{ marginTop:8, fontSize:10.5, color:'var(--mute-1)', fontFamily:'var(--font-mono)' }}>Rate · ${p.rate || 95}/hr · markup {p.markup || 35}% · floor {p.margin || 30}%</div>
      </div>
    );
  }

  if (id === 'intake') {
    const qs = (answers.intake?.qs || config.leadQs).filter(q => q.on).slice(0, 5);
    return (
      <div style={{ background:'var(--ink)', borderRadius:16, padding:'14px', color:'#fff' }}>
        <div className="eyebrow" style={{ color:'var(--chart-300)' }}>LIVE INTAKE · CUSTOMER VIEW</div>
        <div style={{ marginTop:10, display:'flex', flexDirection:'column', gap:5 }}>
          {qs.map((q, i) => (
            <div key={q.id} style={{ background:'rgba(255,255,255,0.08)', padding:'7px 11px', borderRadius:12, fontSize:11.5, lineHeight:1.4 }}>{q.q}</div>
          ))}
          <div style={{ alignSelf:'flex-end', padding:'7px 11px', background:'var(--chart-300)', color:'var(--ink)', borderRadius:12, fontSize:11.5, fontWeight:600 }}>Sounds good</div>
        </div>
      </div>
    );
  }

  if (id === 'voice') {
    const tone = answers.voice?.tone ?? 55;
    const sample = tone < 33
      ? 'Thank you for reaching out. I would be glad to schedule an evaluation at your convenience.'
      : tone < 67
        ? "Hey — thanks for reaching out! Want me to pencil you in for tomorrow morning?"
        : "Heyo — got your message. Tomorrow morning work? I'll save you the spot.";
    const use = (answers.voice?.use || config.voiceVocab.use).slice(0, 6);
    return (
      <div style={{ background:'#fff', borderRadius:16, padding:'18px', border:'1px solid var(--line-2)' }}>
        <div className="eyebrow" style={{ color:'var(--lilac-700)' }}>SAMPLE LINE · {tone < 33 ? 'FORMAL' : tone > 66 ? 'CASUAL' : 'FRIENDLY'}</div>
        <div style={{ marginTop:10, fontFamily:'var(--font-display)', fontSize:15, lineHeight:1.4 }}>"{sample}"</div>
        {use.length > 0 && (
          <>
            <div className="eyebrow" style={{ color:'var(--mute-1)', marginTop:14 }}>Trade vocab</div>
            <div style={{ marginTop:6, display:'flex', flexWrap:'wrap', gap:4 }}>
              {use.map(w => <span key={w} style={{ background:'var(--chart-100)', color:'var(--chart-900)', padding:'3px 8px', borderRadius:99, fontSize:11, fontWeight:600 }}>{w}</span>)}
            </div>
          </>
        )}
      </div>
    );
  }

  if (id === 'playbook') {
    const plays = (answers.playbook?.plays || []).filter(p => p.on);
    if (plays.length === 0) return null;
    const p = plays[0];
    return (
      <div style={{ background:'#fff', borderRadius:16, padding:'14px', border:'1px solid var(--line-2)' }}>
        <div className="eyebrow" style={{ color:'var(--lilac-700)' }}>OBJECTION → REBUTTAL · LIVE</div>
        <div style={{ marginTop:10, padding:'9px 11px', background:'var(--lilac-100)', borderRadius:12, fontSize:12, fontStyle:'italic', color:'var(--lilac-800)' }}>"{p.o}"</div>
        <div style={{ marginTop:6, padding:'9px 11px', background:'var(--ink)', color:'#fff', borderRadius:12, fontSize:12, lineHeight:1.45 }}>{p.r}</div>
        <div style={{ marginTop:8, fontSize:10, fontFamily:'var(--font-mono)', color:'var(--mute-1)' }}>{plays.length} objections loaded into AI memory</div>
      </div>
    );
  }

  if (id === 'certs') {
    const certs = answers.certs?.certs || [];
    const reviews = answers.certs?.reviewCount || 0;
    const rating = answers.certs?.reviewRating || 0;
    return (
      <div style={{ background:'#fff', borderRadius:16, padding:'18px', border:'1px solid var(--line-2)' }}>
        <div className="eyebrow" style={{ color:'var(--chart-700)' }}>CREDIBILITY · APPEARS ON QUOTE</div>
        <div style={{ marginTop:10, display:'flex', flexWrap:'wrap', gap:4 }}>
          {certs.slice(0, 5).map(c => <span key={c} style={{ background:'var(--chart-100)', color:'var(--chart-900)', padding:'3px 8px', borderRadius:6, fontSize:10.5, fontWeight:700 }}>{c}</span>)}
        </div>
        {reviews > 0 && (
          <div style={{ marginTop:12, display:'flex', alignItems:'center', gap:6, fontSize:13 }}>
            <IconStar size={14} fill="var(--chart-400)" stroke="var(--chart-700)"/>
            <span style={{ fontWeight:700 }}>{rating}</span>
            <span style={{ color:'var(--mute-1)', fontSize:12 }}>· {reviews} Google reviews</span>
          </div>
        )}
      </div>
    );
  }

  if (id === 'equipment') {
    const crew = answers.equipment;
    const totalCrew = (crew?.leadEst || 0) + (crew?.seniorTechs || 0) + (crew?.apprentices || 0) + (crew?.foremen || 0);
    return (
      <div style={{ background:'#fff', borderRadius:16, padding:'18px', border:'1px solid var(--line-2)' }}>
        <div className="eyebrow" style={{ color:'var(--lilac-700)' }}>DISPATCH CAPACITY</div>
        <div style={{ marginTop:10, display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
          <div style={{ padding:'10px 12px', background:'var(--paper-3)', borderRadius:10 }}>
            <div style={{ fontSize:10, color:'var(--mute-1)', textTransform:'uppercase', letterSpacing:'0.08em' }}>Field staff</div>
            <div className="display" style={{ fontSize:24, fontWeight:600 }}>{totalCrew || '—'}</div>
          </div>
          <div style={{ padding:'10px 12px', background:'var(--paper-3)', borderRadius:10 }}>
            <div style={{ fontSize:10, color:'var(--mute-1)', textTransform:'uppercase', letterSpacing:'0.08em' }}>Max active jobs</div>
            <div className="display" style={{ fontSize:24, fontWeight:600 }}>{crew?.maxJobs || 6}</div>
          </div>
        </div>
      </div>
    );
  }

  if (id === 'market') {
    const m = answers.market || {};
    return (
      <div style={{ background:'#fff', borderRadius:16, padding:'18px', border:'1px solid var(--line-2)' }}>
        <div className="eyebrow" style={{ color:'var(--chart-700)' }}>LOCAL INTELLIGENCE · LOADED</div>
        <div style={{ marginTop:10, fontSize:12, color:'var(--mute-1)', lineHeight:1.6 }}>
          {m.hoaHoods && <>HOA-aware: <strong style={{ color:'var(--ink)' }}>{m.hoaHoods.split(',').slice(0,2).join(', ')}…</strong><br/></>}
          {m.competitors && <>Competing against: <strong style={{ color:'var(--ink)' }}>{m.competitors.split(',').slice(0,2).join(', ')}…</strong><br/></>}
          {m.hailcount && <>Hail events / yr: <strong style={{ color:'var(--ink)' }}>{m.hailcount}</strong><br/></>}
          {m.avgclaim && <>Avg claim: <strong style={{ color:'var(--ink)' }}>${Number(m.avgclaim).toLocaleString()}</strong></>}
        </div>
      </div>
    );
  }

  return (
    <div style={{ background:'#fff', borderRadius:16, padding:'18px', border:'1px solid var(--line-2)' }}>
      <div className="eyebrow" style={{ color:'var(--mute-1)' }}>What this trains</div>
      <div style={{ marginTop:8, fontSize:12.5, color:'var(--mute-1)', lineHeight:1.5 }}>
        Each answer here trains a different part of the AI. Skip nothing — even rough answers are better than blanks.
      </div>
    </div>
  );
}

/* ============== HELPERS ============== */
function ToggleChip({ value, onClick, label }) {
  return (
    <button onClick={onClick} style={{
      background: value ? 'var(--ink)' : '#fff',
      color: value ? 'var(--chart-300)' : 'var(--ink)',
      border:'1px solid '+(value ? 'var(--ink)' : 'var(--line)'),
      padding:'7px 13px', borderRadius:99, fontSize:12.5, fontWeight:600,
      cursor:'pointer', fontFamily:'var(--font-body)', transition:'all 0.12s',
    }}>{label}</button>
  );
}
function FreeAdder({ list, onAdd, placeholder }) {
  const [val, setVal] = useStateOBX('');
  return (
    <form onSubmit={e => { e.preventDefault(); if(val.trim()) { onAdd(val.trim()); setVal(''); } }} style={{ display:'flex', gap:8 }}>
      <input value={val} onChange={e => setVal(e.target.value)} placeholder={placeholder}
        style={{ flex:1, background:'#fff', border:'1px solid var(--line)', borderRadius:10, padding:'9px 13px', outline:0, fontFamily:'var(--font-body)', fontSize:13 }}/>
      <button type="submit" style={{ background:'var(--ink)', color:'#fff', border:0, padding:'9px 14px', borderRadius:10, fontWeight:600, fontSize:12, cursor:'pointer', fontFamily:'var(--font-body)' }}>Add</button>
    </form>
  );
}
function Empty() {
  return <div style={{ padding:'14px 16px', background:'var(--paper-3)', borderRadius:10, fontSize:13, color:'var(--mute-1)' }}>Doesn't apply to this trade — skip.</div>;
}

Object.assign(window, { StepCerts, StepEquipment, StepPlaybook, StepMarket, LiveSystemPanel });
