/* Onboarding — guided flow from login → workspace */

function Onboarding({ user, onComplete }) {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({
    referral: '', otherReferral: '',
    role: '', otherRole: '',
    useCases: [],
    company: '', companySize: '',
    workspaceName: '',
    starter: 'sample',
  });

  const steps = [
    { title: 'How did you hear about Vamana?', sub: 'Helps us understand what brought you here.', key: 'referral' },
    { title: `What brings you to Vamana${user?.name ? `, ${user.name.split(' ')[0]}` : ''}?`, sub: 'Pick what describes your team best — we\'ll tune the workspace.', key: 'role' },
    { title: 'What are you trying to do with video?', sub: 'Multi-select. We\'ll pre-load the right tools and templates.', key: 'useCases' },
    { title: 'Set up your workspace.', sub: 'Last step — then we\'ll spin up a starter index for you.', key: 'workspace' },
  ];

  const referralOptions = [
    { id: 'twitter', label: 'X / Twitter', icon: '𝕏' },
    { id: 'github', label: 'GitHub', icon: '⌘' },
    { id: 'paper', label: 'Research paper', icon: '◧' },
    { id: 'colleague', label: 'Colleague / referral', icon: '◐' },
    { id: 'search', label: 'Search engine', icon: '◎' },
    { id: 'event', label: 'Conference / event', icon: '◇' },
    { id: 'press', label: 'Press / blog', icon: '▤' },
    { id: 'other', label: 'Something else', icon: '＋' },
  ];

  const roleOptions = [
    { id: 'eng', label: 'Engineer', sub: 'Building product features' },
    { id: 'researcher', label: 'ML / CV Researcher', sub: 'Training models, running experiments' },
    { id: 'pm', label: 'Product Manager', sub: 'Defining what gets built' },
    { id: 'founder', label: 'Founder / Exec', sub: 'Running a company' },
    { id: 'data', label: 'Data / ML Engineer', sub: 'Pipelines, infra, observability' },
    { id: 'other', label: 'Something else', sub: 'Tell us below' },
  ];

  const useCaseOptions = [
    { id: 'search', label: 'Natural-language video search', sub: '"find the moment a person crosses the gate"', icon: 'Search' },
    { id: 'training', label: 'Train ML models on video', sub: 'Stream large datasets to training jobs', icon: 'Database' },
    { id: 'archival', label: 'Archive & compress libraries', sub: 'Shrink storage 30–40× with no quality loss', icon: 'Compress' },
    { id: 'agents', label: 'Build agentic video apps', sub: 'Multi-hop reasoning, custom retrievers', icon: 'Layers' },
    { id: 'moderation', label: 'Moderate UGC / surveillance', sub: 'Caption, classify, flag at scale', icon: 'Tools' },
    { id: 'eval', label: 'Evaluate models on video', sub: 'Benchmark accuracy across datasets', icon: 'Activity' },
  ];

  const sizeOptions = ['1 (just me)', '2–10', '11–50', '51–200', '201–1000', '1000+'];

  const toggleArr = (key, id) => {
    const arr = answers[key];
    setAnswers({ ...answers, [key]: arr.includes(id) ? arr.filter(x => x !== id) : [...arr, id] });
  };

  const canAdvance = (() => {
    if (step === 0) return answers.referral && (answers.referral !== 'other' || answers.otherReferral.trim());
    if (step === 1) return answers.role && (answers.role !== 'other' || answers.otherRole.trim());
    if (step === 2) return answers.useCases.length > 0;
    if (step === 3) return answers.company.trim() && answers.companySize && answers.workspaceName.trim();
    return false;
  })();

  const next = () => {
    if (step < steps.length - 1) setStep(step + 1);
    else onComplete(answers);
  };

  // Auto-derive a workspace slug suggestion when the user types a company name
  React.useEffect(() => {
    if (step === 3 && answers.company && !answers.workspaceName) {
      const slug = answers.company.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 24);
      if (slug) setAnswers(a => ({ ...a, workspaceName: slug }));
    }
  }, [answers.company, step]);

  return (
    <div className="fullscreen">
      {/* Top bar */}
      <div style={{
        height: 64, padding: '0 32px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderBottom: '1px solid var(--border-subtle)',
      }}>
        <Logo size={20} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
            {String(step + 1).padStart(2, '0')} / {String(steps.length).padStart(2, '0')}
          </span>
          <button className="btn btn-ghost btn-sm" onClick={() => onComplete(answers)}>Skip for now</button>
        </div>
      </div>

      {/* Progress */}
      <div style={{ display: 'flex', gap: 6, padding: '20px 32px 0' }}>
        {steps.map((_, i) => (
          <div key={i} style={{
            flex: 1, height: 3, borderRadius: 2,
            background: i <= step ? 'var(--accent)' : 'var(--border-subtle)',
            transition: 'background 0.4s var(--ease-out)',
          }} />
        ))}
      </div>

      {/* Content */}
      <div style={{
        flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '40px 32px', overflowY: 'auto',
      }}>
        <div style={{ maxWidth: 760, width: '100%' }} key={step} className="fade-in-up">
          <div className="eyebrow" style={{ marginBottom: 12 }}>// Step {step + 1} of {steps.length}</div>
          <h1 style={{
            fontSize: 34, fontWeight: 600, letterSpacing: '-0.025em',
            margin: '0 0 12px', color: 'var(--text-primary)', lineHeight: 1.15,
          }}>
            {steps[step].title}
          </h1>
          <p style={{ fontSize: 15, color: 'var(--text-secondary)', margin: '0 0 36px' }}>
            {steps[step].sub}
          </p>

          {step === 0 && (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
                {referralOptions.map(opt => (
                  <button key={opt.id}
                    onClick={() => setAnswers({ ...answers, referral: opt.id })}
                    style={{
                      padding: '20px 16px',
                      background: answers.referral === opt.id ? 'var(--accent-subtle)' : 'var(--bg-surface)',
                      border: `1px solid ${answers.referral === opt.id ? 'var(--accent)' : 'var(--border-default)'}`,
                      borderRadius: 'var(--radius-lg)',
                      textAlign: 'left',
                      transition: 'all var(--duration-fast) var(--ease-out)',
                      cursor: 'pointer',
                    }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 8,
                      background: answers.referral === opt.id ? 'var(--accent)' : 'var(--bg-inset)',
                      color: answers.referral === opt.id ? 'white' : 'var(--text-secondary)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 16, fontWeight: 500, marginBottom: 12,
                      transition: 'all var(--duration-fast) var(--ease-out)',
                    }}>
                      {opt.icon}
                    </div>
                    <div style={{
                      fontSize: 13, fontWeight: 500,
                      color: answers.referral === opt.id ? 'var(--accent-text)' : 'var(--text-primary)',
                    }}>
                      {opt.label}
                    </div>
                  </button>
                ))}
              </div>
              {answers.referral === 'other' && (
                <div style={{ marginTop: 16 }} className="fade-in">
                  <input className="input" placeholder="How did you hear about us?"
                    value={answers.otherReferral}
                    onChange={(e) => setAnswers({ ...answers, otherReferral: e.target.value })} />
                </div>
              )}
            </>
          )}

          {step === 1 && (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
                {roleOptions.map(opt => (
                  <button key={opt.id}
                    onClick={() => setAnswers({ ...answers, role: opt.id })}
                    style={{
                      padding: 18,
                      background: answers.role === opt.id ? 'var(--accent-subtle)' : 'var(--bg-surface)',
                      border: `1px solid ${answers.role === opt.id ? 'var(--accent)' : 'var(--border-default)'}`,
                      borderRadius: 'var(--radius-lg)',
                      textAlign: 'left', cursor: 'pointer',
                      transition: 'all var(--duration-fast) var(--ease-out)',
                      display: 'flex', alignItems: 'center', gap: 14,
                    }}>
                    <div style={{
                      width: 22, height: 22, borderRadius: '50%',
                      border: `1.5px solid ${answers.role === opt.id ? 'var(--accent)' : 'var(--border-strong)'}`,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                    }}>
                      {answers.role === opt.id && <div style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--accent)' }} />}
                    </div>
                    <div>
                      <div style={{
                        fontSize: 14, fontWeight: 500,
                        color: answers.role === opt.id ? 'var(--accent-text)' : 'var(--text-primary)',
                      }}>{opt.label}</div>
                      <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 }}>{opt.sub}</div>
                    </div>
                  </button>
                ))}
              </div>
              {answers.role === 'other' && (
                <div style={{ marginTop: 16 }} className="fade-in">
                  <input className="input" placeholder="What's your role?"
                    value={answers.otherRole}
                    onChange={(e) => setAnswers({ ...answers, otherRole: e.target.value })} />
                </div>
              )}
            </>
          )}

          {step === 2 && (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
              {useCaseOptions.map(opt => {
                const Comp = Icon[opt.icon];
                const checked = answers.useCases.includes(opt.id);
                return (
                  <button key={opt.id}
                    onClick={() => toggleArr('useCases', opt.id)}
                    style={{
                      padding: 16,
                      background: checked ? 'var(--accent-subtle)' : 'var(--bg-surface)',
                      border: `1px solid ${checked ? 'var(--accent)' : 'var(--border-default)'}`,
                      borderRadius: 'var(--radius-lg)',
                      textAlign: 'left', cursor: 'pointer',
                      display: 'flex', alignItems: 'flex-start', gap: 14,
                      transition: 'all var(--duration-fast) var(--ease-out)',
                    }}>
                    <div style={{
                      width: 18, height: 18, borderRadius: 4, marginTop: 2,
                      border: `1.5px solid ${checked ? 'var(--accent)' : 'var(--border-strong)'}`,
                      background: checked ? 'var(--accent)' : 'transparent',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                    }}>
                      {checked && <Icon.Check size={11} color="white" />}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                        <Comp size={14} color={checked ? 'var(--accent)' : 'var(--text-secondary)'} />
                        <span style={{
                          fontSize: 13.5, fontWeight: 500,
                          color: checked ? 'var(--accent-text)' : 'var(--text-primary)',
                        }}>{opt.label}</span>
                      </div>
                      <div style={{ fontSize: 12, color: 'var(--text-tertiary)', lineHeight: 1.45 }}>{opt.sub}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          )}

          {step === 3 && (
            <div style={{ display: 'grid', gap: 24 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <div>
                  <label className="label">Company / firm name</label>
                  <input className="input" placeholder="Acme, Inc." autoFocus
                    value={answers.company}
                    onChange={(e) => setAnswers({ ...answers, company: e.target.value })} />
                </div>
                <div>
                  <label className="label">Workspace handle</label>
                  <div style={{ position: 'relative' }}>
                    <span className="mono" style={{
                      position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)',
                      fontSize: 13, color: 'var(--text-tertiary)', pointerEvents: 'none',
                    }}>vamana.ai/</span>
                    <input className="input" placeholder="acme"
                      style={{ paddingLeft: 88, fontFamily: 'var(--font-mono)' }}
                      value={answers.workspaceName}
                      onChange={(e) => setAnswers({ ...answers, workspaceName: e.target.value.replace(/[^a-z0-9-]/g, '').toLowerCase() })} />
                  </div>
                </div>
              </div>
              <div>
                <label className="label">Company size</label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
                  {sizeOptions.map(s => (
                    <button key={s}
                      onClick={() => setAnswers({ ...answers, companySize: s })}
                      style={{
                        padding: '12px 14px',
                        background: answers.companySize === s ? 'var(--accent-subtle)' : 'var(--bg-surface)',
                        border: `1px solid ${answers.companySize === s ? 'var(--accent)' : 'var(--border-default)'}`,
                        borderRadius: 'var(--radius-md)',
                        fontSize: 13, fontWeight: 500,
                        color: answers.companySize === s ? 'var(--accent-text)' : 'var(--text-primary)',
                        textAlign: 'center', cursor: 'pointer',
                        transition: 'all var(--duration-fast) var(--ease-out)',
                      }}>{s}</button>
                  ))}
                </div>
              </div>
              <div>
                <label className="label">Get started with…</label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
                  {[
                    { id: 'sample', title: 'A sample index', sub: '6 pre-loaded videos · ready to search', icon: 'Database' },
                    { id: 'empty',  title: 'An empty workspace', sub: 'I\'ll bring my own videos', icon: 'Plus' },
                  ].map(s => {
                    const Comp = Icon[s.icon];
                    const sel = answers.starter === s.id;
                    return (
                      <button key={s.id}
                        onClick={() => setAnswers({ ...answers, starter: s.id })}
                        style={{
                          padding: 14, textAlign: 'left', cursor: 'pointer',
                          background: sel ? 'var(--accent-subtle)' : 'var(--bg-surface)',
                          border: `1px solid ${sel ? 'var(--accent)' : 'var(--border-default)'}`,
                          borderRadius: 'var(--radius-md)',
                          display: 'flex', alignItems: 'center', gap: 12,
                        }}>
                        <Comp size={16} color={sel ? 'var(--accent)' : 'var(--text-secondary)'} />
                        <div>
                          <div style={{ fontSize: 13, fontWeight: 500, color: sel ? 'var(--accent-text)' : 'var(--text-primary)' }}>{s.title}</div>
                          <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>{s.sub}</div>
                        </div>
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          )}

          {/* Footer */}
          <div style={{
            marginTop: 48, paddingTop: 24,
            borderTop: '1px solid var(--border-subtle)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <button className="btn btn-ghost"
              onClick={() => step > 0 && setStep(step - 1)}
              disabled={step === 0}>
              <Icon.ChevronLeft size={14} /> Back
            </button>
            <button className="btn btn-primary btn-lg" onClick={next} disabled={!canAdvance}>
              {step === steps.length - 1 ? <>Enter Vamana <Icon.ArrowRight size={14} /></> : <>Continue <Icon.ArrowRight size={14} /></>}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Onboarding });
