// OS Builder — Phases 1 through 6.
// Each phase reads/writes against `state` via get/set helpers.

/* ============================================================
   HELPERS — pain-point badges + agent name editing
   ============================================================ */
function osPainsTop(state) {
  return new Set((state.identity?.painsRanked || []).slice(0, 5));
}

/* ============================================================
   PHASE 1 — BUSINESS IDENTITY
   ============================================================ */
function OSPhase1({ state, set }) {
  const ident = state.identity || {};
  const u = (patch) => set('identity', { ...ident, ...patch });

  const [pfState, setPfState] = React.useState('idle'); // idle | searching | found | dismissed
  const [pfLabel, setPfLabel] = React.useState('');
  const pfFiredRef = React.useRef('');

  // Fire prefill when business name + city are both filled — debounced 1.2 s
  React.useEffect(() => {
    const name = ident.bizName || '';
    const city = ident.city    || '';
    if (name.length < 3 || city.length < 2) return;
    const key = `${name}|${city}`;
    if (key === pfFiredRef.current || pfState === 'searching') return;

    const t = setTimeout(async () => {
      pfFiredRef.current = key;
      setPfState('searching');
      try {
        const res = await fetch('/api/prefill', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            bizName: name,
            city,
            trade: (ident.trades || [])[0] || '',
          }),
        });
        if (!res.ok) { setPfState('idle'); return; }
        const data = await res.json();
        if (!data.ok || !data.prefill) { setPfState('idle'); return; }

        const pf = data.prefill;
        const id = pf.identity || {};

        // Soft-merge identity: only fill fields the user hasn't touched
        const patch = {};
        if (!ident.dba    && id.dba)          patch.dba    = id.dba;
        if (!ident.years  && id.years)         patch.years  = id.years;
        if (!ident.team   && id.team)          patch.team   = id.team;
        if (!ident.areas  && id.areas)         patch.areas  = id.areas;
        if (!(ident.tools?.length) && id.tools?.length) patch.tools = id.tools;
        if (!(ident.trades?.length) && id.trades?.length) patch.trades = id.trades;
        if (Object.keys(patch).length) u(patch);

        // Stash website URL in tech section if not already set
        if (pf.meta?.website_url && !state.tech?.url) {
          set('tech', { ...(state.tech || {}), url: pf.meta.website_url, phone: pf.welcome?.phone || state.tech?.phone || '', reply: pf.welcome?.email || state.tech?.reply || '' });
        }

        const filled = Object.keys(patch).length;
        const src = pf.meta?.website_url || pf.meta?.gmb_url || name;
        if (filled > 0) {
          setPfLabel(`Applied ${filled} field${filled !== 1 ? 's' : ''} from ${src}`);
          setPfState('found');
        } else {
          setPfLabel(`Found ${src} — no new fields to fill`);
          setPfState('found');
        }
      } catch { setPfState('idle'); }
    }, 1200);

    return () => clearTimeout(t);
  }, [ident.bizName, ident.city]);

  // Default mix on first interaction
  const mixVals = ident.mix || Object.fromEntries(MIX_STREAMS.map(m => [m.id, m.def]));

  // Default tools
  const tools = ident.tools || [];
  const toggleTool = (name) => {
    const next = tools.includes(name) ? tools.filter(t => t !== name) : [...tools, name];
    u({ tools: next });
  };

  return (
    <>
      {/* Prefill status banner */}
      {pfState === 'searching' && (
        <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:4, padding:'11px 16px', background:'var(--paper-3)', borderRadius:12, border:'1px solid var(--line-2)', fontSize:13, color:'var(--mute-1)' }}>
          <span style={{ display:'inline-block', animation:'spin 1.2s linear infinite' }}>⟳</span>
          Searching your website, GMB, and socials…
        </div>
      )}
      {(pfState === 'found') && (
        <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:4, padding:'11px 16px', background:'var(--chart-100)', borderRadius:12, border:'1px solid var(--chart-400)', fontSize:13 }}>
          <span>✓</span>
          <span style={{ flex:1, color:'var(--chart-900)', fontWeight:500 }}>{pfLabel}</span>
          <button type="button" onClick={() => setPfState('dismissed')} style={{ background:'transparent', border:0, cursor:'pointer', color:'var(--mute-2)', fontSize:18, lineHeight:1, padding:'0 4px' }}>×</button>
        </div>
      )}

      <OSSection num="1.1" kicker="Trade type" title="What do you actually do?" sub="Pick every trade you run. This drives every recommendation in every phase after this one.">
        <OSCardPicker tone="chart" items={TRADES} cols={4} multi value={ident.trades || []} onChange={v => u({ trades:v })}/>
      </OSSection>

      <OSSection num="1.2" kicker="Business name & basics" title="The label on the truck.">
        <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr 1fr', gap:14 }}>
          <OSField label="Business name" value={ident.bizName} onChange={v=>u({ bizName:v })} placeholder="Chapman's A/C & Heating"/>
          <OSField label="DBA / Doing business as" value={ident.dba} onChange={v=>u({ dba:v })} placeholder="optional"/>
          <OSField label="EIN" value={ident.ein} onChange={v=>u({ ein:v })} placeholder="XX-XXXXXXX" mono/>
        </div>
      </OSSection>

      <OSSection num="1.3" kicker="Structure" title="How are you organized?">
        <OSCardPicker tone="lilac" items={STRUCTURES} cols={5} value={ident.structure} onChange={v=>u({ structure:v })}/>
      </OSSection>

      <OSSection num="1.4" kicker="Years & stage" title="How long has this been your name?">
        <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
          {YEARS_BANDS.map(y => (
            <button key={y} type="button" onClick={()=>u({ years:y })} style={{
              padding:'10px 18px', borderRadius:99,
              background: ident.years===y ? 'var(--ink)' : 'var(--paper)',
              color: ident.years===y ? 'var(--chart-300)' : 'var(--ink)',
              border:'1px solid', borderColor: ident.years===y ? 'var(--ink)' : 'var(--line)',
              fontFamily:'var(--font-body)', fontWeight:600, fontSize:13, cursor:'pointer',
            }}>{y} years</button>
          ))}
        </div>
      </OSSection>

      <OSSection num="1.5" kicker="Revenue tier" title="Your last 12 months of revenue.">
        <OSCardPicker tone="chart" items={REVENUE_TIERS} cols={4} value={ident.revenue} onChange={v=>u({ revenue:v })} minH={60}/>
        <p style={{ fontSize:12.5, color:'var(--mute-1)', marginTop:10 }}>This sets your benchmark group and unlocks features at the right scale.</p>
      </OSSection>

      <OSSection num="1.6" kicker="Team size" title="How many people on the books?">
        <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
          {TEAM_BANDS.map(t => (
            <button key={t} type="button" onClick={()=>u({ team:t })} style={{
              padding:'10px 18px', borderRadius:99,
              background: ident.team===t ? 'var(--lilac-500)' : 'var(--paper)',
              color: ident.team===t ? '#fff' : 'var(--ink)',
              border:'1px solid', borderColor: ident.team===t ? 'var(--lilac-500)' : 'var(--line)',
              fontFamily:'var(--font-body)', fontWeight:600, fontSize:13, cursor:'pointer',
            }}>{t}</button>
          ))}
        </div>
      </OSSection>

      <OSSection num="1.7" kicker="Service area" title="Where do you work?" sub="Cities and counties you currently serve. This feeds competitor monitoring, GEO targeting, and real-estate triggers automatically.">
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
          <OSField label="Primary city" value={ident.city} onChange={v=>u({ city:v })} placeholder="Austin, TX"/>
          <OSField label="Service radius" value={ident.radius} onChange={v=>u({ radius:v })} placeholder="30" suffix="miles"/>
        </div>
        <div style={{ marginTop:12 }}>
          <div style={{ fontSize:12, fontWeight:600, color:'var(--mute-1)', textTransform:'uppercase', letterSpacing:'0.08em', marginBottom:8 }}>Additional cities & counties</div>
          <textarea
            value={ident.areas || ''}
            onChange={e => u({ areas: e.target.value })}
            placeholder="Round Rock · Cedar Park · Pflugerville · Georgetown"
            rows={3}
            style={{ width:'100%', padding:'10px 12px', border:'1px solid var(--line)', borderRadius:10, fontFamily:'var(--font-body)', fontSize:13, color:'var(--ink)', background:'var(--paper)', resize:'vertical', outline:'none', lineHeight:1.6 }}
          />
          <div style={{ fontSize:11.5, color:'var(--mute-2)', marginTop:6 }}>One per line or comma-separated. Feeds competitor monitoring and GEO targeting automatically.</div>
        </div>
      </OSSection>

      <OSSection num="1.8" kicker="Revenue mix" title="Where does the money come from?" sub="Sliders should add to 100%. Every percentage point changes which features get prioritized for you.">
        <OSMixSliders items={MIX_STREAMS} values={mixVals} onChange={v=>u({ mix:v })} tone="chart"/>
      </OSSection>

      <OSSection num="1.9" kicker="Existing stack" title="What tools are you already using?" sub="Check everything you actually log into. Nothing gets ripped out — we connect to it.">
        {TOOLS_STACK.map(g => (
          <div key={g.cat} style={{ marginBottom:14 }}>
            <div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--mute-1)', marginBottom:6 }}>{g.cat}</div>
            <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
              {g.items.map(t => {
                const active = tools.includes(t);
                return (
                  <button key={t} type="button" onClick={()=>toggleTool(t)} style={{
                    padding:'7px 13px', borderRadius:99,
                    background: active ? 'var(--lilac-100)' : 'var(--paper)',
                    color: active ? 'var(--lilac-800)' : 'var(--ink)',
                    border:'1px solid', borderColor: active ? 'var(--lilac-500)' : 'var(--line)',
                    fontSize:12.5, fontWeight: active ? 600 : 500, cursor:'pointer', fontFamily:'var(--font-body)',
                  }}>{active && '✓ '}{t}</button>
                );
              })}
            </div>
          </div>
        ))}
      </OSSection>

      <OSSection num="1.10" kicker="Pain ranking" title="What hurts the most?" sub="Drag your top 5 into priority order. Every feature that solves one of these gets a badge for the rest of your build.">
        <OSRankList items={PAIN_POINTS} value={ident.painsRanked || []} onChange={v=>u({ painsRanked:v })} max={5} tone="lilac"/>
      </OSSection>

      <OSSection num="1.11" kicker="12-month goals" title="What does winning look like in a year?" sub="Multi-select. Goals tag features throughout your build so the most relevant ones surface first.">
        <OSCardPicker tone="chart" items={GOALS_12MO} cols={3} multi value={ident.goals || []} onChange={v=>u({ goals:v })} minH={60}/>
      </OSSection>
    </>
  );
}

/* ============================================================
   PHASE 2 — DATA CONNECTIONS
   ============================================================ */
function OSPhase2({ state, set }) {
  const conns = state.connections || {};
  const u = (id, v) => set('connections', { ...conns, [id]: v });

  const grouped = CONNECTIONS.reduce((acc, c) => {
    acc[c.group] = acc[c.group] || [];
    acc[c.group].push(c);
    return acc;
  }, {});

  const connectedCount = Object.values(conns).filter(Boolean).length;
  const biSoFar = CONNECTIONS.filter(c => conns[c.id]).reduce((s,c)=>s+c.bi, 0);

  return (
    <>
      <OSSection num="2.0" kicker="One click per source" title="Connect the systems that already own your data." sub="Each OAuth takes about 30 seconds. As you connect, your business intelligence score climbs and the analysis engine starts reading.">
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12, padding:'14px 16px', background:'var(--ink)', borderRadius:14, color:'var(--paper)' }}>
          <Mini label="Sources connected" value={`${connectedCount} / ${CONNECTIONS.length}`}/>
          <Mini label="BI points earned" value={`+${biSoFar}`}/>
          <Mini label="Analysis status" value={connectedCount === 0 ? 'Idle' : connectedCount < 4 ? 'Building' : 'Diagnosis ready'}/>
        </div>
      </OSSection>

      {Object.entries(grouped).map(([group, items]) => (
        <OSSection key={group} kicker={group} title={group + ' integrations'}>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(240px, 1fr))', gap:12 }}>
            {items.map(c => (
              <OSConnectionTile key={c.id} conn={c} connected={!!conns[c.id]} onConnect={v=>u(c.id, v)}/>
            ))}
          </div>
        </OSSection>
      ))}

      <OSSection num="2.9" kicker="AI scraping layer" title="What we already know — without you connecting anything." sub="The moment you signed in, the scrapers started. Here's what's already happening in the background.">
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
          {SCRAPE_TARGETS.map(s => (
            <div key={s.label} style={{
              padding:'14px 16px', background:'var(--chart-50)', border:'1px solid var(--chart-200)', borderRadius:12,
              display:'flex', gap:12, alignItems:'flex-start',
            }}>
              <span style={{ width:8, height:8, borderRadius:99, background:'var(--chart-500)', marginTop:6, flexShrink:0 }} className="pulse-soft"/>
              <div>
                <div style={{ fontSize:13.5, fontWeight:600, color:'var(--ink)' }}>{s.label}</div>
                <div style={{ fontSize:12, color:'var(--chart-900)', marginTop:2, lineHeight:1.4 }}>{s.detail}</div>
              </div>
            </div>
          ))}
        </div>
      </OSSection>
    </>
  );
}

function Mini({ label, value }) {
  return (
    <div>
      <div style={{ fontSize:10, fontWeight:700, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--chart-200)', opacity:0.7 }}>{label}</div>
      <div style={{ fontFamily:'var(--font-display)', fontSize:22, fontWeight:500, color:'var(--chart-300)', marginTop:3, letterSpacing:'-0.02em' }}>{value}</div>
    </div>
  );
}

/* ============================================================
   PHASE 3 — DEPARTMENT & MODULE BUILDER
   ============================================================ */
function OSPhase3({ state, set }) {
  const modules = state.modules || {};
  const agents  = state.agentNames || {};
  const topPains = osPainsTop(state);
  const [openDept, setOpenDept] = React.useState(DEPARTMENTS[0].id);

  const u = (id, v) => set('modules', { ...modules, [id]: v });
  const renameAgent = (modId, name) => set('agentNames', { ...agents, [modId]: name });

  const activateDept = (dept, on) => {
    const next = { ...modules };
    dept.modules.forEach(m => { next[m.id] = on; });
    set('modules', next);
  };

  return (
    <>
      <OSSection num="3.0" kicker="Six departments · every module configurable" title="Build the back office that runs without you." sub="Activate whole departments or pick module by module. Anything that solves one of your top 5 problems gets a badge. Rename every agent — they're yours.">
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:10 }}>
          {DEPARTMENTS.map(d => {
            const active = d.modules.filter(m => modules[m.id]).length;
            const total = d.modules.length;
            const allOn = active === total;
            return (
              <button key={d.id} type="button" onClick={()=>setOpenDept(d.id)} style={{
                padding:'14px 16px', textAlign:'left', cursor:'pointer',
                background: openDept===d.id ? 'var(--ink)' : 'var(--paper)',
                color: openDept===d.id ? 'var(--paper)' : 'var(--ink)',
                border:'1px solid', borderColor: openDept===d.id ? 'var(--ink)' : 'var(--line)',
                borderRadius:14,
              }}>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
                  <span style={{ fontSize:14, fontWeight:600 }}>{d.name}</span>
                  <span style={{ fontFamily:'var(--font-mono)', fontSize:11, color: openDept===d.id ? 'var(--chart-300)' : allOn ? 'var(--chart-700)' : 'var(--mute-1)' }}>{active}/{total}</span>
                </div>
                <div style={{ fontSize:11.5, color: openDept===d.id ? 'var(--mute-3)' : 'var(--mute-1)', marginTop:3 }}>{d.tag}</div>
              </button>
            );
          })}
        </div>
      </OSSection>

      {DEPARTMENTS.filter(d => d.id === openDept).map(dept => (
        <OSSection key={dept.id} kicker={dept.name + ' modules'} title={`Configure ${dept.name.toLowerCase()}.`}>
          <div style={{ display:'flex', justifyContent:'flex-end', gap:8, marginBottom:10 }}>
            <button type="button" onClick={()=>activateDept(dept, true)} style={btnTinyDark}>Turn whole department on</button>
            <button type="button" onClick={()=>activateDept(dept, false)} style={btnTinyGhost}>Turn all off</button>
          </div>
          <div style={{ display:'grid', gap:10 }}>
            {dept.modules.map(m => {
              const hitsPain = m.pain.some(p => topPains.has(p));
              const agentName = agents[m.id] ?? m.agent;
              return (
                <div key={m.id} style={{
                  padding:'14px 16px',
                  background: modules[m.id] ? 'var(--paper)' : 'var(--paper-2)',
                  border:'1px solid', borderColor: modules[m.id] ? (dept.tone==='chart'?'var(--chart-500)':'var(--lilac-500)') : 'var(--line)',
                  borderRadius:12,
                  display:'grid', gridTemplateColumns:'1fr auto', gap:14, alignItems:'center',
                }}>
                  <div style={{ minWidth:0 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                      <span style={{ fontSize:14, fontWeight:600, color:'var(--ink)' }}>{m.name}</span>
                      <input value={agentName} onChange={e=>renameAgent(m.id, e.target.value)} style={{
                        fontFamily:'var(--font-mono)', fontSize:11.5, fontWeight:600,
                        padding:'1.5px 8px', borderRadius:99,
                        background: dept.tone==='chart' ? 'var(--chart-100)' : 'var(--lilac-100)',
                        color: dept.tone==='chart' ? 'var(--chart-900)' : 'var(--lilac-800)',
                        border:0, outline:'none', width:80, textAlign:'center',
                      }}/>
                      {hitsPain && <span style={{ fontSize:9.5, fontWeight:700, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--chart-900)', background:'var(--chart-300)', padding:'2px 7px', borderRadius:99 }}>solves a top-5</span>}
                    </div>
                    <div style={{ fontSize:12.5, color:'var(--mute-1)', marginTop:4 }}>{m.why}</div>
                  </div>
                  <div style={{ display:'flex', alignItems:'center', gap:14 }}>
                    <span style={{ fontFamily:'var(--font-mono)', fontSize:12, color:'var(--mute-1)', whiteSpace:'nowrap' }}>+${m.mo}/mo</span>
                    <OSSwitch value={!!modules[m.id]} onChange={v=>u(m.id, v)} tone={dept.tone}/>
                  </div>
                </div>
              );
            })}
          </div>
        </OSSection>
      ))}

      <OSSection num="3.7" kicker="Home Equipment Health Monitoring" title="Your customers' homes — tracked before they break." sub="Every customer's home gets a health profile built automatically from job history and CRM data. HomePro alerts you before equipment fails so you call the customer before they call a competitor.">
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:14 }}>
          {[
            { label:'HVAC System', detail:'Tracks age, last service, filter due', alert:'Replace Soon', alertColor:'var(--chart-300)', alertBg:'var(--chart-900)' },
            { label:'Water Heater', detail:'Tracks age, anode rod, flush history', alert:'Monitor', alertColor:'var(--lilac-300)', alertBg:'var(--lilac-900)' },
            { label:'Electrical Panel', detail:'Tracks age, inspection date, load', alert:'Inspection Due', alertColor:'#ff9a8a', alertBg:'#3a1010' },
            { label:'Roof', detail:'Tracks install year, last inspection', alert:'Healthy', alertColor:'var(--mute-3)', alertBg:'var(--ink-2)' },
          ].map(({ label, detail, alert, alertColor, alertBg }) => (
            <div key={label} style={{ padding:'14px 16px', background:'var(--ink)', borderRadius:12, display:'flex', alignItems:'center', gap:14 }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:'var(--paper)' }}>{label}</div>
                <div style={{ fontSize:11.5, color:'var(--mute-3)', marginTop:3 }}>{detail}</div>
              </div>
              <span style={{ flexShrink:0, fontSize:11, fontWeight:700, color:alertColor, background:alertBg, padding:'4px 10px', borderRadius:99, letterSpacing:'0.04em' }}>{alert}</span>
            </div>
          ))}
        </div>
        <div style={{ display:'grid', gap:10 }}>
          <OSToggleRow title="Enable Home Equipment Health Monitoring" desc="Build health profiles for every customer automatically from job history and CRM" value={!!state.modules?.['ehm']} onChange={v=>u('ehm', v)} tone="chart"/>
          <OSToggleRow title="Proactive outreach alerts" desc="Ping you before equipment fails — before the homeowner calls a competitor" value={!!state.modules?.['ehm-alerts']} onChange={v=>u('ehm-alerts', v)} tone="chart"/>
          <OSToggleRow title="Customer-facing Home Health portal" desc="Homeowners see their equipment health score after every visit" value={!!state.modules?.['ehm-portal']} onChange={v=>u('ehm-portal', v)} tone="lilac"/>
          <OSToggleRow title="Home Health Program upsell tier" desc="Premium maintenance program built on top of the monitoring layer" value={!!state.modules?.['ehm-program']} onChange={v=>u('ehm-program', v)} tone="lilac"/>
        </div>
        <div style={{ marginTop:14, padding:'12px 16px', background:'var(--chart-50)', border:'1px solid var(--chart-200)', borderRadius:10, fontSize:12.5, color:'var(--chart-900)' }}>
          The contractor who calls the homeowner first — before the breakdown — wins. Equipment health monitoring turns reactive service into proactive care. That is a completely different business.
        </div>
      </OSSection>
    </>
  );
}

const btnTinyDark = { padding:'7px 14px', background:'var(--ink)', color:'var(--chart-300)', border:0, borderRadius:99, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'var(--font-body)' };
const btnTinyGhost = { padding:'7px 14px', background:'transparent', color:'var(--ink)', border:'1px solid var(--line)', borderRadius:99, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'var(--font-body)' };

/* ============================================================
   PHASE 4 — AUTOMATION LIBRARY
   ============================================================ */
function OSPhase4({ state, set }) {
  const autos = state.automations || {};
  const u = (id, v) => set('automations', { ...autos, [id]: v });
  const [openCat, setOpenCat] = React.useState(AUTOMATION_CATEGORIES[0].id);

  const activeInCat = (cat) => cat.sample.filter((_, i) => autos[`${cat.id}-${i}`]).length;

  return (
    <>
      <OSSection num="4.0" kicker="230+ automations · plain English" title="Toggle on what you want running automatically." sub="Each automation is one sentence. We've ordered the ones most relevant to your trade and pain points first. Edit copy and timing once you launch.">
        <div style={{ display:'grid', gridTemplateColumns:'repeat(5, 1fr)', gap:8 }}>
          {AUTOMATION_CATEGORIES.map(c => {
            const open = openCat === c.id;
            const active = activeInCat(c);
            return (
              <button key={c.id} type="button" onClick={()=>setOpenCat(c.id)} style={{
                padding:'10px 12px', textAlign:'left', cursor:'pointer',
                background: open ? 'var(--lilac-500)' : 'var(--paper)',
                color: open ? '#fff' : 'var(--ink)',
                border:'1px solid', borderColor: open ? 'var(--lilac-500)' : 'var(--line)',
                borderRadius:12,
              }}>
                <div style={{ fontSize:12, fontWeight:600, lineHeight:1.25 }}>{c.name}</div>
                <div style={{ fontFamily:'var(--font-mono)', fontSize:11, color: open ? 'rgba(255,255,255,0.8)' : 'var(--mute-1)', marginTop:3 }}>
                  {active} on · {c.count} total
                </div>
              </button>
            );
          })}
        </div>
      </OSSection>

      {AUTOMATION_CATEGORIES.filter(c => c.id === openCat).map(cat => (
        <OSSection key={cat.id} kicker={cat.name} title={`${cat.count} automations available · ${activeInCat(cat)} on right now.`} sub="These are the first six in this category. Everything else unlocks at launch.">
          <div style={{ display:'grid', gap:8 }}>
            {cat.sample.map((s, i) => {
              const id = `${cat.id}-${i}`;
              return (
                <OSToggleRow key={id} title={s} value={!!autos[id]} onChange={v=>u(id, v)} tone="lilac"/>
              );
            })}
          </div>
          <button type="button" style={{ ...btnTinyGhost, marginTop:12 }}>+ Show all {cat.count} in this category</button>
        </OSSection>
      ))}
    </>
  );
}

/* ============================================================
   PHASE 5 — DASHBOARDS & PAGES
   ============================================================ */
function OSPhase5({ state, set }) {
  const dash = state.dashboards || { owner:[], office:[], tech:[] };
  const u = (view, list) => set('dashboards', { ...dash, [view]: list });
  const [openView, setOpenView] = React.useState('owner');

  const toggle = (view, id) => {
    const list = dash[view] || [];
    u(view, list.includes(id) ? list.filter(x => x !== id) : [...list, id]);
  };

  const views = [
    { id:'owner', label:'Owner Dashboard', desc:'What you look at every morning' },
    { id:'office', label:'Office Manager', desc:'Run the day without you' },
    { id:'tech',  label:'Tech Mobile App', desc:'What field crews see' },
  ];

  return (
    <>
      <OSSection num="5.0" kicker="Build your screens" title="No two HomePros look the same." sub="Pick the widgets you want on every dashboard. We arrange them into a layout that fits, but you can rearrange after launch.">
        <OSSegmented items={views.map(v => ({ id:v.id, label:v.label }))} value={openView} onChange={setOpenView} tone="lilac"/>
      </OSSection>

      {views.filter(v => v.id === openView).map(view => (
        <OSSection key={view.id} kicker={view.label} title={view.desc + '.'}>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
            {DASH_WIDGETS[view.id].map(w => {
              const active = (dash[view.id] || []).includes(w.id);
              return (
                <button key={w.id} type="button" onClick={()=>toggle(view.id, w.id)} style={{
                  textAlign:'left', padding:'12px 14px',
                  background: active ? 'var(--chart-50)' : 'var(--paper)',
                  border:'1px solid', borderColor: active ? 'var(--chart-500)' : 'var(--line)',
                  borderRadius:10, cursor:'pointer',
                  display:'flex', alignItems:'center', gap:10,
                }}>
                  <span style={{
                    width:18, height:18, borderRadius:5,
                    background: active ? 'var(--chart-500)' : 'var(--paper)',
                    border: '1.5px solid', borderColor: active ? 'var(--chart-500)' : 'var(--line)',
                    display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
                  }}>
                    {active && <IconCheck size={11} stroke="#fff" sw={3}/>}
                  </span>
                  <span style={{ fontSize:13, color:'var(--ink)' }}>{w.label}</span>
                </button>
              );
            })}
          </div>
          {(dash[view.id]||[]).length > 0 && (
            <div style={{ marginTop:14, padding:'14px 16px', background:'var(--chart-50)', border:'1px solid var(--chart-200)', borderRadius:12, display:'flex', alignItems:'center', justifyContent:'space-between' }}>
              <span style={{ fontSize:12.5, color:'var(--chart-900)', fontWeight:600 }}>{(dash[view.id]||[]).length} widget{(dash[view.id]||[]).length !== 1 ? 's' : ''} on this dashboard</span>
              <span style={{ fontSize:11.5, color:'var(--chart-700)', fontFamily:'var(--font-mono)' }}>Layout configured at launch</span>
            </div>
          )}
        </OSSection>
      ))}

      <OSSection num="5.4" kicker="Customer-facing pages" title="The pages your customers actually see.">
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
          {['Estimate request form','Online booking page','Customer portal','Review landing page','Payment page','Job-progress page'].map(p => (
            <OSToggleRow key={p} title={p} desc="Branded with your name, logo, and tone" value={!!state.pages?.[p]} onChange={v=>set('pages', { ...(state.pages||{}), [p]:v })} tone="chart"/>
          ))}
        </div>
      </OSSection>

      <OSSection num="5.5" kicker="Reports library" title="Scheduled reports — emailed without you remembering.">
        <div style={{ display:'grid', gap:10 }}>
          <OSToggleRow title="Morning owner briefing · daily" desc="Your 5 most important numbers at a chosen time" value={!!state.reports?.morn} onChange={v=>set('reports', { ...(state.reports||{}), morn:v })}/>
          <OSToggleRow title="Weekly performance summary · Monday" desc="To your office manager every Monday" value={!!state.reports?.weekly} onChange={v=>set('reports', { ...(state.reports||{}), weekly:v })}/>
          <OSToggleRow title="Monthly financial overview · 1st" desc="To your accountant on the 1st of every month" value={!!state.reports?.monthly} onChange={v=>set('reports', { ...(state.reports||{}), monthly:v })}/>
          <OSToggleRow title="Quarterly business review · 90 days" desc="To you · gaps, wins, next moves" value={!!state.reports?.quarterly} onChange={v=>set('reports', { ...(state.reports||{}), quarterly:v })}/>
        </div>
      </OSSection>
    </>
  );
}

/* ============================================================
   PHASE 6 — FINANCIAL CONFIGURATION
   ============================================================ */
function OSPhase6({ state, set }) {
  const fin = state.finance || {};
  const u = (patch) => set('finance', { ...fin, ...patch });

  return (
    <>
      <OSSection num="6.1" kicker="Revenue targets" title="How big do you want to be — and by when?" sub="We'll pressure-test these against your connected data and tell you honestly if they're aggressive, achievable, or unrealistic.">
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14 }}>
          <OSField label="90-day target" value={fin.t90} onChange={v=>u({ t90:v })} placeholder="$420,000" mono/>
          <OSField label="12-month target" value={fin.t12} onChange={v=>u({ t12:v })} placeholder="$1.6M" mono/>
          <OSField label="3-year target" value={fin.t3y} onChange={v=>u({ t3y:v })} placeholder="$4.5M" mono/>
        </div>
      </OSSection>

      <OSSection num="6.2" kicker="Gross margin targets" title="What margin should each service hit?">
        <div style={{ display:'grid', gap:12 }}>
          <OSSlider tone="chart" label="Service calls · target margin" value={fin.mService ?? 48} onChange={v=>u({ mService:v })} min={20} max={75} suffix="%"/>
          <OSSlider tone="chart" label="Installs · target margin" value={fin.mInstall ?? 32} onChange={v=>u({ mInstall:v })} min={15} max={55} suffix="%"/>
          <OSSlider tone="chart" label="Maintenance agreements · target margin" value={fin.mMaint ?? 58} onChange={v=>u({ mMaint:v })} min={30} max={80} suffix="%"/>
        </div>
      </OSSection>

      <OSSection num="6.3" kicker="Labor costs" title="The numbers that make every margin calc real.">
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14 }}>
          <OSField label="Avg tech hourly" value={fin.hr} onChange={v=>u({ hr:v })} placeholder="38" suffix="$/hr" mono/>
          <OSField label="Burden rate" value={fin.burden} onChange={v=>u({ burden:v })} placeholder="1.35" suffix="x" mono/>
          <OSField label="Drive-time policy" value={fin.drive} onChange={v=>u({ drive:v })} placeholder="paid > 15 min" />
        </div>
      </OSSection>

      <OSSection num="6.5" kicker="Cash rules" title="When should we ping you?">
        <div style={{ display:'grid', gap:12 }}>
          <OSSlider tone="lilac" label="Alert if cash drops below" value={fin.cashFloor ?? 45} onChange={v=>u({ cashFloor:v })} min={5} max={120} suffix="K"/>
          <OSSlider tone="lilac" label="Target months of operating reserve" value={fin.reserve ?? 3} onChange={v=>u({ reserve:v })} min={0.5} max={12} step={0.5} suffix=" mo"/>
        </div>
      </OSSection>

      <OSSection num="6.6" kicker="Maintenance program" title="Tier the recurring revenue."  sub="Set your tiers and what each includes. We'll calculate exactly how many agreements you need to hit recurring revenue targets.">
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12 }}>
          {['Standard','Premium','Elite'].map((tier, i) => (
            <div key={tier} style={{ padding:'14px', background:'var(--paper)', border:'1px solid var(--line)', borderRadius:14 }}>
              <div style={{ fontSize:13, fontWeight:700, color:'var(--ink)' }}>{tier}</div>
              <div style={{ marginTop:10 }}>
                <OSField label="Annual price" value={fin[`tier${i}Price`]} onChange={v=>u({ [`tier${i}Price`]:v })} placeholder={[180,320,520][i]} suffix="$/yr" mono/>
              </div>
              <div style={{ marginTop:8 }}>
                <OSField label="Visits per year" value={fin[`tier${i}Visits`]} onChange={v=>u({ [`tier${i}Visits`]:v })} placeholder={[1,2,4][i]} mono/>
              </div>
            </div>
          ))}
        </div>
      </OSSection>

      <OSSection num="6.7" kicker="Financing partners" title="So techs can offer the right plan at the right moment.">
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
          {['GreenSky','Synchrony','Service Finance','Wisetack','Hearth','EnerBank'].map(p => (
            <OSToggleRow key={p} title={p} desc="Active partner" value={!!fin.partners?.[p]} onChange={v=>u({ partners: { ...(fin.partners||{}), [p]:v } })} tone="chart"/>
          ))}
        </div>
      </OSSection>

      <OSSection num="6.8" kicker="Valuation baseline" title="What your business is worth — right now." sub="HomePro reads 6 factors that drive trades business valuation. This number updates every month so you always know where you stand.">
        <div style={{ padding:'18px 20px', background:'var(--ink)', color:'var(--paper)', borderRadius:16, display:'grid', gridTemplateColumns:'auto 1fr', gap:24, alignItems:'center' }}>
          <div>
            <div style={{ fontSize:10.5, fontWeight:700, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--chart-200)', opacity:0.7 }}>Estimated value</div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:38, fontWeight:500, color:'var(--chart-300)', letterSpacing:'-0.025em', marginTop:4 }}>$1.2M – $1.9M</div>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:6, fontSize:12 }}>
            {[
              ['Revenue scale','Strong'],
              ['Growth rate','Mid'],
              ['Net margin','Weak'],
              ['Recurring revenue %','Mid'],
              ['Owner dependence','High'],
              ['Documented systems','Weak'],
            ].map(([k,v]) => (
              <div key={k} style={{ display:'flex', justifyContent:'space-between', padding:'3px 0' }}>
                <span style={{ color:'var(--mute-3)' }}>{k}</span>
                <span style={{ color: v==='Strong' ? 'var(--chart-300)' : v==='Weak' ? '#ff9a8a' : 'var(--paper)' }}>{v}</span>
              </div>
            ))}
          </div>
        </div>
      </OSSection>

      <OSSection num="6.9" kicker="Business health biomarkers" title="Five vital signs. Always visible. From day one." sub="The moment you log into HomePro these five numbers are live at the top of your dashboard — updated daily from your bank connection, CRM, and review profiles. Not estimates. Live.">
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
          {[
            { label:'Close Rate', value:'68%', target:'Target 75%', desc:'What % of estimates convert to booked jobs. Industry top performers run 70+. HomePro shows the gap and the path.', dot:'var(--chart-300)' },
            { label:'Cash Runway', value:'47 days', target:'Alert at 30 days', desc:'Days until cash hits your minimum threshold. Updated daily. Projected 45–90 days out. No more surprises.', dot:'var(--lilac-400)' },
            { label:'Review Velocity', value:'+14 / mo', target:'Competitor avg 8', desc:'How fast your review count grows versus competitors in your zip. Falling behind is an early warning signal.', dot:'var(--chart-300)' },
            { label:'Team Retention', value:'91 / 100', target:'1 tech flagged', desc:'Composite signal tracking callback rate, ratings, hours consistency per tech. Drops before a resignation.', dot:'var(--lilac-400)' },
          ].map(({ label, value, target, desc, dot }) => (
            <div key={label} style={{ padding:'16px 18px', background:'var(--paper)', border:'1px solid var(--line)', borderRadius:14 }}>
              <div style={{ display:'flex', alignItems:'center', gap:7, marginBottom:8 }}>
                <span style={{ width:8, height:8, borderRadius:99, background:dot, flexShrink:0 }}/>
                <span style={{ fontSize:10.5, fontWeight:700, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--mute-1)' }}>{label}</span>
              </div>
              <div style={{ fontFamily:'var(--font-display)', fontSize:28, fontWeight:500, letterSpacing:'-0.025em', color:'var(--ink)', lineHeight:1 }}>{value}</div>
              <div style={{ fontSize:11.5, color:'var(--mute-2)', marginTop:4, fontFamily:'var(--font-mono)' }}>{target}</div>
              <div style={{ fontSize:12, color:'var(--mute-1)', marginTop:10, lineHeight:1.5 }}>{desc}</div>
            </div>
          ))}
        </div>
        <div style={{ marginTop:10, padding:'16px 18px', background:'var(--ink)', color:'var(--paper)', borderRadius:14, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <div>
            <div style={{ fontSize:10.5, fontWeight:700, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--chart-200)', opacity:0.7 }}>Business Valuation</div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:32, fontWeight:500, color:'var(--chart-300)', letterSpacing:'-0.025em', marginTop:4 }}>$1.4M</div>
            <div style={{ fontSize:11.5, color:'var(--mute-3)', marginTop:2, fontFamily:'var(--font-mono)' }}>Up $180K projected YTD</div>
          </div>
          <div style={{ fontSize:12.5, color:'var(--mute-3)', maxWidth:260, lineHeight:1.55 }}>
            6 factors: revenue, growth, margin, recurring %, owner dependence, systems quality. Updates monthly. Shows exactly what to fix to increase it.
          </div>
        </div>
        <div style={{ marginTop:10, padding:'12px 16px', background:'var(--chart-50)', border:'1px solid var(--chart-200)', borderRadius:10, fontSize:12.5, color:'var(--chart-900)' }}>
          These numbers are illustrative until your bank, CRM, and review profiles connect. Once connected they update themselves — no input required from you.
        </div>
      </OSSection>
    </>
  );
}

Object.assign(window, { OSPhase1, OSPhase2, OSPhase3, OSPhase4, OSPhase5, OSPhase6, btnTinyGhost, btnTinyDark });