// OS Builder — main shell.
// Top nav · left phase rail · main content · right live build summary · bottom nav.

const OS_PHASES = [
  { id:'identity',  num:'01', title:'Identity',       sub:'Trade · structure · tier · pain', component:'OSPhase1' },
  { id:'data',      num:'02', title:'Connections',    sub:'OAuth · scraping · BI score',     component:'OSPhase2' },
  { id:'depts',     num:'03', title:'Departments',    sub:'6 depts · every AI module',        component:'OSPhase3' },
  { id:'auto',      num:'04', title:'Automations',    sub:'230+ workflows · one-sentence',     component:'OSPhase4' },
  { id:'dash',      num:'05', title:'Dashboards',     sub:'Owner · office · tech · customer', component:'OSPhase5' },
  { id:'fin',       num:'06', title:'Finance',        sub:'Targets · margin · valuation',     component:'OSPhase6' },
  { id:'compl',     num:'07', title:'Compliance',     sub:'Licenses · insurance · continuity', component:'OSPhase7' },
  { id:'team',      num:'08', title:'Team & roles',   sub:'Roster · permissions · routing',    component:'OSPhase8' },
  { id:'growth',    num:'09', title:'Growth',         sub:'Voice · sources · calendar',       component:'OSPhase9' },
  { id:'intel',     num:'10', title:'Intelligence',   sub:'Anomalies · predictive · pricing',  component:'OSPhase10' },
  { id:'tech',      num:'11', title:'Tech setup',     sub:'Web · phone · email · apps',       component:'OSPhase11' },
  { id:'launch',    num:'12', title:'Launch',         sub:'Summary · investment · go-live',    component:'OSPhase12' },
];

function OSBuilder({ initialState } = {}) {
  const [state, setState] = React.useState(() => {
    let base = {};
    try { base = JSON.parse(localStorage.getItem('hp-os-builder') || '{}'); } catch {}
    if (initialState && typeof initialState === 'object') {
      // Soft-merge: only fill keys the user hasn't already touched
      const merged = { ...initialState };
      for (const [k, v] of Object.entries(base)) {
        if (v && typeof v === 'object' && Object.keys(v).length) merged[k] = { ...(initialState[k] || {}), ...v };
      }
      return merged;
    }
    return base;
  });
  const [phase, setPhase] = React.useState(() => {
    try { return parseInt(localStorage.getItem('hp-os-builder-phase') || '0', 10); } catch { return 0; }
  });
  const [launching, setLaunching] = React.useState(false);

  React.useEffect(() => { try { localStorage.setItem('hp-os-builder', JSON.stringify(state)); } catch {} }, [state]);
  React.useEffect(() => {
    try { localStorage.setItem('hp-os-builder-phase', String(phase)); } catch {}
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [phase]);

  const set = (key, value) => setState(prev => ({ ...prev, [key]: value }));
  const cur = OS_PHASES[phase];
  const Comp = window[cur.component];
  const isLastPhase = phase === OS_PHASES.length - 1;

  function handleNext() {
    if (isLastPhase) {
      handleLaunch();
      return;
    }
    // Phase 0 (identity) exit: fire scraper in background — non-blocking
    if (phase === 0 && state.identity?.bizName) {
      fetch('/api/run-agent', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ agent: 'scrape', state }),
      }).catch(() => {});
    }
    setPhase(p => Math.min(OS_PHASES.length - 1, p + 1));
  }

  async function handleLaunch() {
    setLaunching(true);
    try {
      await fetch('/api/run-agent', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ agent: 'launch', state }),
      });
    } catch (_) {}
    // Clear saved progress and redirect to confirmation
    try { localStorage.removeItem('hp-os-builder'); localStorage.removeItem('hp-os-builder-phase'); } catch {}
    window.location.href = '/os-launched.html';
  }

  return (
    <div style={{ minHeight:'100vh', background:'var(--paper-2)', fontFamily:'var(--font-body)', color:'var(--ink)' }}>
      <OSNav state={state} phase={phase} totalPhases={OS_PHASES.length}/>
      <OSPhaseRail phases={OS_PHASES} current={phase} onJump={setPhase} state={state}/>

      <main style={{ maxWidth:1500, margin:'0 auto', padding:'40px 56px 120px', display:'flex', gap:32, alignItems:'flex-start' }}>
        {/* MAIN COLUMN */}
        <div style={{ flex:1, minWidth:0 }}>
          <OSPhaseHeader phase={cur} idx={phase} total={OS_PHASES.length} state={state}/>
          <div style={{ marginTop:24 }}>
            {Comp ? <Comp state={state} set={set}/> : <div style={{ padding:60, textAlign:'center', color:'var(--mute-1)' }}>Phase under construction.</div>}
          </div>
          <OSPhaseFooter
            phase={phase} total={OS_PHASES.length} phaseObj={cur} nextObj={OS_PHASES[phase+1]}
            onBack={()=>setPhase(Math.max(0, phase-1))}
            onNext={handleNext}
            launching={launching}
          />
        </div>

        {/* SIDEBAR */}
        <OSBuildSummary state={state} currentPhase={phase} totalPhases={OS_PHASES.length} jumpToPhase={setPhase}/>
      </main>
    </div>
  );
}

/* ============== TOP NAV ============== */
function OSNav({ state, phase, totalPhases }) {
  const bizName = state.identity?.bizName;
  const pct = Math.round(((phase+1) / totalPhases) * 100);
  return (
    <nav style={{
      position:'sticky', top:0, zIndex:60,
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding:'14px 56px',
      background:'rgba(255,255,255,0.88)', backdropFilter:'blur(20px) saturate(180%)',
      borderBottom:'1px solid var(--line-2)',
    }}>
      <div style={{ display:'flex', alignItems:'center', gap:18 }}>
        <a href="/for-owners" style={{ display:'flex', alignItems:'center', gap:10, textDecoration:'none', color:'var(--ink)' }}>
          <Logo size={32}/>
          <Wordmark size={18}/>
        </a>
        <div style={{ width:1, height:24, background:'var(--line)' }}/>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontFamily:'var(--font-mono)', fontSize:10, fontWeight:700, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--lilac-700)', background:'var(--lilac-100)', padding:'3px 9px', borderRadius:99 }}>
            OS Builder
          </span>
          {bizName && <span style={{ fontSize:13, color:'var(--ink)', fontWeight:500 }}>· {bizName}</span>}
        </div>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:18 }}>
        <div style={{ display:'flex', alignItems:'center', gap:10, fontSize:12, color:'var(--mute-1)' }}>
          <span style={{ fontFamily:'var(--font-mono)' }}>{pct}% built</span>
          <div style={{ width:80, height:4, background:'var(--paper-3)', borderRadius:99, overflow:'hidden' }}>
            <div style={{ width:`${pct}%`, height:'100%', background:'var(--ink)' }}/>
          </div>
        </div>
        <a href="/for-owners" style={{ fontSize:13, fontWeight:500, color:'var(--mute-1)', textDecoration:'none' }}>Save & exit</a>
        <button type="button" style={{ background:'var(--ink)', color:'var(--chart-300)', border:0, padding:'9px 16px', borderRadius:99, fontWeight:600, fontSize:13, cursor:'pointer', fontFamily:'var(--font-body)' }}>Get help →</button>
      </div>
    </nav>
  );
}

/* ============== PHASE RAIL (horizontal) ============== */
function OSPhaseRail({ phases, current, onJump, state }) {
  // Highlight which phases have data in them
  const filled = (p, i) => {
    const map = {
      identity:'identity', data:'connections', depts:'modules', auto:'automations',
      dash:'dashboards', fin:'finance', compl:'compliance', team:'team',
      growth:'growth', intel:'intel', tech:'tech', launch:null,
    };
    const k = map[p.id];
    if (!k) return false;
    const v = state[k];
    if (!v) return false;
    if (Array.isArray(v)) return v.length > 0;
    if (typeof v === 'object') return Object.keys(v).length > 0;
    return !!v;
  };
  return (
    <div style={{
      position:'sticky', top:61, zIndex:50,
      background:'rgba(250,250,250,0.88)', backdropFilter:'blur(20px)',
      borderBottom:'1px solid var(--line-2)',
    }}>
      <div style={{ maxWidth:1500, margin:'0 auto', padding:'14px 56px', display:'flex', alignItems:'center', gap:4, overflowX:'auto' }}>
        {phases.map((p, i) => {
          const done = i < current;
          const active = i === current;
          const has = filled(p, i);
          return (
            <button key={p.id} type="button" onClick={()=>onJump(i)} style={{
              flex:'0 0 auto', display:'flex', alignItems:'center', gap:8,
              padding:'8px 12px', borderRadius:10,
              background: active ? 'var(--ink)' : 'transparent',
              color: active ? 'var(--paper)' : done || has ? 'var(--ink)' : 'var(--mute-2)',
              border:'1px solid', borderColor: active ? 'var(--ink)' : 'transparent',
              cursor:'pointer', fontFamily:'var(--font-body)', textAlign:'left',
              transition:'all .15s ease',
            }}>
              <span style={{
                fontFamily:'var(--font-mono)', fontSize:10, fontWeight:700,
                color: active ? 'var(--chart-300)' : done || has ? 'var(--lilac-700)' : 'var(--mute-3)',
              }}>{p.num}</span>
              <div style={{ display:'flex', flexDirection:'column' }}>
                <span style={{ fontSize:12, fontWeight: active ? 700 : 500, lineHeight:1.1 }}>{p.title}</span>
                {active && <span style={{ fontSize:10, color:'var(--chart-200)', opacity:0.7, marginTop:2 }}>{p.sub}</span>}
              </div>
              {has && !active && <span style={{ width:6, height:6, borderRadius:99, background:'var(--chart-500)' }}/>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ============== PHASE HEADER ============== */
function OSPhaseHeader({ phase, idx, total, state }) {
  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', gap:14 }}>
        <span style={{ fontFamily:'var(--font-mono)', fontSize:11, fontWeight:700, color:'var(--lilac-700)', letterSpacing:'0.08em' }}>
          Phase {phase.num} of 12
        </span>
        <div style={{ flex:1, height:1, background:'var(--line)' }}/>
        <span style={{ fontSize:11, color:'var(--mute-1)', fontFamily:'var(--font-mono)' }}>
          {idx === 0 ? '0%' : Math.round((idx / (total-1)) * 100) + '%'} built
        </span>
      </div>
      <h1 className="display" style={{ fontSize:60, fontWeight:500, letterSpacing:'-0.04em', lineHeight:0.98, margin:'18px 0 0', color:'var(--ink)' }}>
        {OS_PHASE_HEADLINES[phase.id]?.title || phase.title}
      </h1>
      <p style={{ fontSize:17, color:'var(--mute-1)', lineHeight:1.45, marginTop:14, maxWidth:720 }}>
        {OS_PHASE_HEADLINES[phase.id]?.sub || phase.sub}
      </p>
    </div>
  );
}

const OS_PHASE_HEADLINES = {
  identity: { title:'Tell us who you actually are.', sub:'The foundation that makes every other phase intelligent. Every recommendation, every default, every highlight after this is powered by what you define here.' },
  data:     { title:'Connect what you already use.', sub:'One click per source. ~30 seconds each. As you connect, your business intelligence score rises and the analysis engine starts reading — automatically.' },
  depts:    { title:'Build the back office that runs itself.', sub:'Six departments. Every AI module configurable. Name every agent. We badge anything that solves one of your top 5 problems.' },
  auto:     { title:'Pick what should happen automatically.', sub:'230+ pre-built automations in plain English. Toggle on what you want running. Customize the numbers, timing, and copy after launch.' },
  dash:     { title:'Build every screen you\'ll look at.', sub:'Owner. Office. Tech mobile. Customer-facing. No two HomePros look the same — yours is yours.' },
  fin:      { title:'Set how money is supposed to work.', sub:'Targets. Margins. Cash rules. Maintenance program. Financing partners. Valuation baseline. This runs the finance department for the next 5 years.' },
  compl:    { title:'The infrastructure that prevents shutdowns.', sub:'Licenses. Insurance. Sub COIs. Certifications. Continuity. Track it once — alerts fire forever at 90, 60, and 30 days.' },
  team:     { title:'Roles, permissions, and who hears about what.', sub:'The most detailed permissions system ever built for a trades company. Set it once. Run it forever.' },
  growth:   { title:'Voice, sources, calendar, referrals.', sub:'How HomePro talks on your behalf. Where leads come from. The 12-month marketing calendar that runs itself.' },
  intel:    { title:'Turn on the predictive layer.', sub:'Anomalies. Forecasts. Dynamic pricing. Knowledge capture. Every AI capability configured with your thresholds and your risk tolerance.' },
  tech:     { title:'Glue the pieces together.', sub:'One line of code on the website. Phone routing. Email signatures. SMS opt-in. App invites to your team. Everything plumbed.' },
  launch:   { title:'Your operating system is ready.', sub:'Everything you built — in one summary. Investment. ROI projection. 90-day targets. One button.' },
};

/* ============== PHASE FOOTER ============== */
function OSPhaseFooter({ phase, total, phaseObj, nextObj, onBack, onNext, launching }) {
  const isLast = phase === total - 1;
  return (
    <div style={{
      position:'sticky', bottom:0, marginTop:64,
      padding:'14px 0',
      background:'rgba(250,250,250,0.92)', backdropFilter:'blur(20px)',
      borderTop:'1px solid var(--line-2)',
      display:'flex', justifyContent:'space-between', alignItems:'center', gap:18,
    }}>
      <button type="button" onClick={onBack} disabled={phase === 0 || launching} style={{
        background:'transparent',
        border:'1px solid var(--line)',
        color: phase === 0 ? 'var(--mute-3)' : 'var(--ink)',
        padding:'12px 22px', borderRadius:99,
        fontWeight:600, fontSize:14, cursor: phase === 0 ? 'default' : 'pointer',
        fontFamily:'var(--font-body)',
      }}>← Back</button>

      <div style={{ display:'flex', alignItems:'center', gap:8, fontSize:12, color:'var(--mute-1)', fontFamily:'var(--font-mono)' }}>
        <span>Phase {phaseObj.num} · {phaseObj.title}</span>
        <span style={{ opacity:0.5 }}>·</span>
        <span style={{ display:'flex', alignItems:'center', gap:4 }}>
          <span style={{ width:6, height:6, borderRadius:99, background:'var(--chart-500)' }} className="pulse-soft"/> auto-saved
        </span>
      </div>

      <button type="button" onClick={onNext} disabled={launching} style={{
        background: isLast ? 'var(--chart-300)' : 'var(--ink)',
        color: isLast ? 'var(--ink)' : 'var(--chart-300)',
        border:0, padding:'14px 26px', borderRadius:99,
        fontWeight:700, fontSize:14, cursor: launching ? 'default' : 'pointer',
        fontFamily:'var(--font-body)', display:'flex', alignItems:'center', gap:10,
        boxShadow: isLast ? '0 10px 30px rgba(196,240,0,0.4)' : '0 10px 30px rgba(12,14,16,0.18)',
        opacity: launching ? 0.7 : 1,
      }}>
        {isLast
          ? launching
            ? <>Building your OS… <span style={{ display:'inline-block', animation:'spin 1s linear infinite' }}>⚙</span></>
            : <>Launch my business <IconArrow size={14} stroke="var(--ink)"/></>
          : <span style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap:0 }}>
              <span style={{ fontSize:10, opacity:0.65, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase' }}>Next · {nextObj?.num}</span>
              <span style={{ fontSize:14 }}>{nextObj?.title} →</span>
            </span>
        }
      </button>
    </div>
  );
}

Object.assign(window, { OSBuilder, OS_PHASES });