// Onboarding wizard shell — manages step state, persists answers, renders the right step.

function Onboarding({ prefillData, initialService, initialStep } = {}) {
  const [service, setService] = React.useState(() => {
    if (initialService) {
      try { localStorage.setItem('hp-owner-service', initialService); } catch {}
      return initialService;
    }
    try {
      const sp = new URLSearchParams(window.location.search).get('s');
      if (sp) { localStorage.setItem('hp-owner-service', sp); return sp; }
      return localStorage.getItem('hp-owner-service') || null;
    } catch { return null; }
  });
  const [pickerOpen, setPickerOpen] = React.useState(() => {
    if (initialService) return false;
    try {
      const sp = new URLSearchParams(window.location.search).get('s');
      return !sp && !localStorage.getItem('hp-owner-service');
    } catch { return true; }
  });

  const [answers, setAnswers] = React.useState(() => {
    let base = {};
    try { base = JSON.parse(localStorage.getItem('hp-onboarding-answers') || '{}'); } catch {}
    if (prefillData) {
      const stepMap = { welcome: 'welcome', certs: 'certs', services: 'services', voice: 'voice' };
      for (const [key, patch] of Object.entries(prefillData)) {
        const stepId = stepMap[key];
        if (!stepId || !patch || typeof patch !== 'object') continue;
        const existing = base[stepId] || {};
        const safe = Object.fromEntries(Object.entries(patch).filter(([k, v]) => v != null && !existing[k]));
        if (Object.keys(safe).length > 0) base[stepId] = { ...existing, ...safe };
      }
    }
    return base;
  });
  React.useEffect(() => {
    try { localStorage.setItem('hp-onboarding-answers', JSON.stringify(answers)); } catch {}
  }, [answers]);

  const [stepIdx, setStepIdx] = React.useState(() => {
    if (initialStep != null) return initialStep;
    try { return parseInt(localStorage.getItem('hp-onboarding-step') || '0', 10); } catch { return 0; }
  });
  React.useEffect(() => {
    try { localStorage.setItem('hp-onboarding-step', String(stepIdx)); } catch {}
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [stepIdx]);

  const [submitting, setSubmitting] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const partialSavedRef = React.useRef(false);

  const _SB_URL = 'https://xbckptknojjqrurjxhlq.supabase.co';
  const _SB_HDR = {
    'Content-Type': 'application/json',
    'apikey': 'sb_publishable_QunIi9f_LeCR0vbbgqR7Gw_N8nQoexd',
    'Authorization': 'Bearer sb_publishable_QunIi9f_LeCR0vbbgqR7Gw_N8nQoexd',
  };

  // Auto-save partial lead to Supabase + email when user advances past welcome step
  React.useEffect(() => {
    if (stepIdx > 0 && !partialSavedRef.current) {
      const w = answers.welcome || {};
      if (w.email) {
        partialSavedRef.current = true;
        const existingId = (() => { try { return localStorage.getItem('hp-operator-id'); } catch { return null; } })();
        if (existingId) {
          fetch(`${_SB_URL}/rest/v1/operators?id=eq.${existingId}`, {
            method: 'PATCH', headers: _SB_HDR,
            body: JSON.stringify({ email: w.email, company: w.dba || w.company || null, trade: service || null, status: 'partial' }),
          }).catch(() => {});
        } else {
          fetch(`${_SB_URL}/rest/v1/operators`, {
            method: 'POST', headers: { ..._SB_HDR, 'Prefer': 'return=representation' },
            body: JSON.stringify({
              email: w.email, owner_name: w.ownerName || null,
              company: w.dba || w.company || null, trade: service || null,
              city: w.city ? `${w.city}${w.state ? ', ' + w.state : ''}` : null,
              phone: w.phone || null, plan_tier: 'estimates', status: 'partial',
            }),
          })
          .then(r => r.ok ? r.json() : null)
          .then(data => { if (data?.[0]?.id) { try { localStorage.setItem('hp-operator-id', data[0].id); } catch {} } })
          .catch(() => {});
        }
        fetch('/api/send-onboarding', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ type: 'partial', service, answers }),
        }).catch(() => {});
      }
    }
  }, [stepIdx]);

  const handleSubmit = async () => {
    setSubmitting(true);
    const w = answers.welcome || {};
    const existingOpId = (() => { try { return localStorage.getItem('hp-operator-id'); } catch { return null; } })();
    const payload = {
      email:              w.email      || null,
      owner_name:         w.ownerName  || null,
      company:            w.dba        || w.company || null,
      trade:              service      || null,
      city:               w.city ? `${w.city}${w.state ? ', ' + w.state : ''}` : null,
      phone:              w.phone      || null,
      plan_tier:          'estimates',
      onboarding_answers: answers,
      status:             'pending',
    };
    try {
      if (existingOpId) {
        await fetch(`${_SB_URL}/rest/v1/operators?id=eq.${existingOpId}`, {
          method: 'PATCH', headers: _SB_HDR, body: JSON.stringify(payload),
        });
      } else {
        const res = await fetch(`${_SB_URL}/rest/v1/operators`, {
          method: 'POST', headers: { ..._SB_HDR, 'Prefer': 'return=representation' },
          body: JSON.stringify(payload),
        });
        if (res.ok) {
          const [op] = await res.json();
          if (op?.id) { try { localStorage.setItem('hp-operator-id', op.id); } catch {} }
        }
      }
    } catch {}
    fetch('/api/send-onboarding', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ type: 'wizard', service, answers }),
    }).catch(() => {});
    try { localStorage.removeItem('hp-onboarding-answers'); localStorage.removeItem('hp-onboarding-step'); } catch {}
    setSubmitting(false);
    setSubmitted(true);
  };

  const STEPS = window.ONBOARDING_STEPS_V2 || ONBOARDING_STEPS;
  const config = service ? getOnboardingConfig(service) : null;
  const step = STEPS[stepIdx];
  const total = STEPS.length;

  const handlePick = (name) => {
    setService(name);
    try { localStorage.setItem('hp-owner-service', name); } catch {}
    setPickerOpen(false);
  };

  const update = (patch) => setAnswers(prev => ({ ...prev, [step.id]: { ...(prev[step.id] || {}), ...patch } }));
  const get = (key, fallback) => (answers[step.id] || {})[key] ?? fallback;

  // Applies prefill data to multiple steps at once — called from StepWelcome after web scrape
  const prefillAll = React.useCallback((patches) => {
    setAnswers(prev => {
      const next = { ...prev };
      for (const [stepId, patch] of Object.entries(patches)) {
        // Only fill fields the user hasn't already typed into
        const existing = prev[stepId] || {};
        const safe = Object.fromEntries(
          Object.entries(patch).filter(([k, v]) => v != null && !existing[k])
        );
        if (Object.keys(safe).length > 0) next[stepId] = { ...existing, ...safe };
      }
      return next;
    });
  }, []);

  if (submitted) {
    const bizName = (answers.welcome || {}).dba || (answers.welcome || {}).company || '';
    return (
      <div className="ob-root" style={{ width:'100%', minHeight:'100vh', background:'var(--paper-2)', fontFamily:'var(--font-body)', color:'var(--ink)', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center', padding:'60px 24px' }}>
        <div style={{ width:64, height:64, borderRadius:'50%', background:'var(--chart-300)', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 28px' }}>
          <IconCheck size={28} stroke="var(--ink)" sw={2.5}/>
        </div>
        <h1 className="display" style={{ fontSize:'clamp(36px, 5vw, 52px)', fontWeight:500, letterSpacing:'-0.04em', lineHeight:1.05, margin:'0 0 20px', maxWidth:560 }}>
          {bizName ? `${bizName} is` : 'You\'re'} in the <span style={{ color:'var(--lilac-700)', fontStyle:'italic' }}>queue.</span>
        </h1>
        <p style={{ fontSize:17, color:'var(--mute-1)', maxWidth:460, lineHeight:1.6, margin:'0 0 12px' }}>
          Application received for <strong style={{ color:'var(--ink)' }}>{service}</strong> instant estimates. Someone from our team will reach out within 24 hours to confirm your setup and schedule your install call.
        </p>
        <p style={{ fontSize:13, color:'var(--mute-2)', maxWidth:400, lineHeight:1.55, margin:'0 0 36px' }}>Real human, not a bot. We configure the system specifically for your trade, crew size, and the way you close jobs.</p>
        <a href="/for-owners" style={{ background:'var(--ink)', color:'var(--chart-300)', padding:'14px 28px', borderRadius:99, fontWeight:700, fontSize:14, textDecoration:'none', display:'inline-flex', alignItems:'center', gap:8 }}>
          Back to HomePro <IconArrow size={14} stroke="var(--chart-300)"/>
        </a>
      </div>
    );
  }

  return (
    <div className="ob-root" style={{ width:'100%', minHeight:'100vh', background:'var(--paper-2)', fontFamily:'var(--font-body)', color:'var(--ink)', overflowX:'hidden' }}>
      <ServicePicker open={pickerOpen} onPick={handlePick} onClose={service ? () => setPickerOpen(false) : null} current={service}/>

      <OnboardingNav config={config} onSwitch={() => setPickerOpen(true)}/>
      <OnboardingProgress steps={STEPS} stepIdx={stepIdx} onJump={(i) => setStepIdx(i)}/>

      <main className="ob-main" style={{ position:'relative', padding:'48px 56px 80px', maxWidth:1240, margin:'0 auto', boxSizing:'border-box' }}>
        <OnboardingHeader stepIdx={stepIdx} total={total} step={step} config={config}/>
        <div className="ob-content-grid" style={{ marginTop:42, display:'grid', gridTemplateColumns:'minmax(0,1.55fr) minmax(0,1fr)', gap:28, alignItems:'flex-start' }}>
          <div style={{ minWidth:0 }}>
            <OnboardingStepBody stepId={step.id} config={config} get={get} update={update} answers={answers} prefillAll={prefillAll}/>
          </div>
          <div className="ob-panel" style={{ minWidth:0 }}>
            <LiveSystemPanel config={config} answers={answers} stepIdx={stepIdx}/>
          </div>
        </div>
        <OnboardingFooter stepIdx={stepIdx} total={total} onBack={() => setStepIdx(Math.max(0, stepIdx-1))} onNext={() => setStepIdx(Math.min(total-1, stepIdx+1))} onSubmit={handleSubmit} submitting={submitting}/>
      </main>
    </div>
  );
}

/* ============== NAV ============== */
function OnboardingNav({ config, onSwitch }) {
  return (
    <nav className="ob-nav-bar" style={{ position:'sticky', top:0, zIndex:60, display:'flex', alignItems:'center', justifyContent:'space-between', padding:'14px 56px', background:'rgba(255,255,255,0.9)', backdropFilter:'blur(20px) saturate(180%)', borderBottom:'1px solid var(--line-2)' }}>
      <div style={{ display:'flex', alignItems:'center', gap:24 }}>
        <a href="/for-owners" style={{ display:'flex', alignItems:'center', gap:10, textDecoration:'none', color:'var(--ink)', flexShrink:0 }}>
          <Logo size={32}/>
          <Wordmark size={18}/>
          <span className="ob-install-badge" style={{ fontFamily:'var(--font-display)', fontWeight:600, fontSize:11, letterSpacing:'0.1em', textTransform:'uppercase', padding:'3px 9px', borderRadius:99, background:'var(--ink)', color:'var(--chart-300)', marginLeft:4 }}>Install</span>
        </a>
        {config && (
          <button onClick={onSwitch} className="ob-nav-trade" style={{
            display:'flex', alignItems:'center', gap:7,
            background:'var(--paper-3)', color:'var(--ink)', border:'1px solid var(--line)',
            padding:'7px 14px', borderRadius:99, cursor:'pointer',
            fontFamily:'var(--font-body)', fontSize:12.5, fontWeight:600,
          }}>
            <span style={{ opacity:.55 }}>Trade ·</span>
            <span>{config.serviceName}</span>
            <span style={{ color:'var(--lilac-700)', fontSize:11 }}>switch</span>
          </button>
        )}
      </div>
      <div className="ob-nav-right" style={{ display:'flex', gap:14, alignItems:'center' }}>
        <a href="/for-owners" className="ob-nav-exit" style={{ fontSize:13, fontWeight:500, color:'var(--mute-1)', textDecoration:'none', whiteSpace:'nowrap' }}>Save & exit</a>
        <a href="mailto:support@thehomeproaiapp.com" 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)', whiteSpace:'nowrap', textDecoration:'none' }}>Get help →</a>
      </div>
    </nav>
  );
}

/* ============== PROGRESS BAR ============== */
function OnboardingProgress({ steps, stepIdx, onJump }) {
  return (
    <div className="ob-progress-bar" style={{ position:'sticky', top:60, zIndex:50, background:'rgba(250,250,250,0.85)', backdropFilter:'blur(20px)', borderBottom:'1px solid var(--line-2)' }}>
      <div className="ob-progress-inner" style={{ maxWidth:1180, margin:'0 auto', padding:'16px 56px', display:'flex', alignItems:'center', gap:6, boxSizing:'border-box' }}>
        {steps.map((s, i) => {
          const done = i < stepIdx;
          const active = i === stepIdx;
          return (
            <div key={s.id} onClick={() => done && onJump(i)} style={{ flex:1, cursor: done ? 'pointer' : 'default', minWidth:0 }}>
              <div style={{ height:4, borderRadius:99, background: active ? 'var(--ink)' : done ? 'var(--chart-400)' : 'var(--paper-3)' }}/>
              <div className="ob-step-label" style={{ marginTop:6, fontSize:10, fontWeight: active ? 700 : 500, letterSpacing:'0.06em', textTransform:'uppercase',
                color: active ? 'var(--ink)' : done ? 'var(--mute-1)' : 'var(--mute-3)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                <span style={{ fontFamily:'var(--font-mono)', fontSize:9, marginRight:3 }}>{String(i+1).padStart(2,'0')}</span>{s.title}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ============== HEADER (per step) ============== */
function OnboardingHeader({ stepIdx, total, step, config }) {
  return (
    <div style={{ position:'relative' }}>
      <div style={{ display:'flex', alignItems:'center', gap:14 }}>
        <span style={{ fontSize:11, fontWeight:700, letterSpacing:'0.18em', color:'var(--lilac-700)', textTransform:'uppercase', whiteSpace:'nowrap' }}>
          Step {stepIdx+1} of {total}
        </span>
        <div style={{ flex:1, height:1, background:'var(--line)' }}/>
        {config && <span className="ob-trade-label" style={{ fontSize:11, fontFamily:'var(--font-mono)', color:'var(--mute-1)', whiteSpace:'nowrap' }}>Trade · {config.serviceName}</span>}
      </div>
      <h1 className="display ob-heading" style={{ fontSize:72, fontWeight:500, letterSpacing:'-0.045em', lineHeight:0.98, margin:'24px 0 0', color:'var(--ink)' }}>
        {step.heading}
      </h1>
      <p className="ob-heading-sub" style={{ fontSize:18, color:'var(--mute-1)', lineHeight:1.45, marginTop:18, maxWidth:680 }}>{step.sub}</p>
    </div>
  );
}

/* ============== FOOTER (back/next) ============== */
function OnboardingFooter({ stepIdx, total, onBack, onNext, onSubmit, submitting }) {
  const isLast = stepIdx === total - 1;
  return (
    <div className="ob-footer" style={{ position:'sticky', bottom:0, marginTop:80, padding:'18px 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:12 }}>
      <button onClick={onBack} disabled={stepIdx === 0} style={{ background:'transparent', border:'1px solid var(--line)', color: stepIdx === 0 ? 'var(--mute-3)' : 'var(--ink)', padding:'12px 22px', borderRadius:99, fontWeight:600, fontSize:14, cursor: stepIdx === 0 ? 'default' : 'pointer', fontFamily:'var(--font-body)', flexShrink:0 }}>
        ← Back
      </button>
      <div className="ob-footer-count" style={{ fontSize:12, color:'var(--mute-1)', fontFamily:'var(--font-mono)', textAlign:'center' }}>
        {stepIdx + 1} / {total} · {stepIdx > 0 ? 'auto-saved' : 'saved'}
      </div>
      <button
        onClick={isLast ? onSubmit : onNext}
        disabled={submitting}
        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: submitting ? 'default' : 'pointer', opacity: submitting ? 0.7 : 1, fontFamily:'var(--font-body)', display:'flex', alignItems:'center', gap:8, boxShadow: isLast ? '0 10px 30px rgba(196,240,0,0.4)' : '0 10px 30px rgba(12,14,16,0.18)', flexShrink:0, whiteSpace:'nowrap' }}
      >
        {isLast
          ? (submitting ? 'Sending…' : <> Submit application <IconCheck size={14} stroke="var(--ink)" sw={3}/></>)
          : <>Continue <IconArrow size={14} stroke="var(--chart-300)"/></>}
      </button>
    </div>
  );
}

/* Body dispatcher */
function OnboardingStepBody({ stepId, config, get, update, answers, prefillAll }) {
  if (!config) return (
    <div style={{ padding:'60px 20px', textAlign:'center' }}>
      <div style={{ fontSize:18, fontWeight:600, color:'var(--ink)', marginBottom:12 }}>Pick your trade to get started.</div>
      <p style={{ fontSize:14, color:'var(--mute-1)', marginBottom:24 }}>The whole system — fields, pricing, intake questions — configures around your specific trade.</p>
    </div>
  );
  if (stepId === 'welcome')   return <StepWelcome   cfg={config} get={get} update={update} prefillAll={prefillAll}/>;
  if (stepId === 'certs')     return <StepCerts     cfg={config} get={get} update={update}/>;
  if (stepId === 'services')  return <StepServices  cfg={config} get={get} update={update}/>;
  if (stepId === 'equipment') return <StepEquipment cfg={config} get={get} update={update}/>;
  if (stepId === 'pricing')   return <StepPricing   cfg={config} get={get} update={update}/>;
  if (stepId === 'fields')    return <StepFields    cfg={config} get={get} update={update}/>;
  if (stepId === 'history')   return <StepHistory   cfg={config} get={get} update={update}/>;
  if (stepId === 'intake')    return <StepIntake    cfg={config} get={get} update={update}/>;
  if (stepId === 'voice')     return <StepVoice     cfg={config} get={get} update={update}/>;
  if (stepId === 'playbook')  return <StepPlaybook  cfg={config} get={get} update={update}/>;
  if (stepId === 'connect')   return <StepConnect   cfg={config} get={get} update={update}/>;
  if (stepId === 'market')    return <StepMarket    cfg={config} get={get} update={update}/>;
  if (stepId === 'review')    return <StepReview    cfg={config} answers={answers}/>;
  return null;
}

Object.assign(window, { Onboarding });
