/* ============================================================
   COURSEDY — Auth (signup / signin) + Onboarding
   ============================================================ */

/* ---------- Brand side panel ---------- */
function AuthAside() {
  return (
    <div style={{ position: 'relative', overflow: 'hidden', background: 'var(--ink)', display: 'flex', flexDirection: 'column', padding: '40px 44px', color: '#fff' }} className="noise">
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(70% 60% at 20% 10%, rgba(91,84,230,.55), transparent 55%), radial-gradient(60% 60% at 100% 100%, rgba(62,123,232,.4), transparent 55%)' }} />
      <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <Logo light />
        <div className="grow center" style={{ flexDirection: 'column' }}>
          {/* mini live generation visual */}
          <div style={{ width: '100%', maxWidth: 360 }}>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,.55)', marginBottom: 16 }}>Generating · Negotiation for Engineers</div>
            {['Foundations of leverage', 'Reading the other side', 'Tactics that don’t backfire', 'Closing & follow-through'].map((m, i) => (
              <div key={i} className="reveal" style={{ '--d': `${0.2 + i * 0.15}s`, display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', borderRadius: 12, background: 'rgba(255,255,255,.08)', border: '1px solid rgba(255,255,255,.1)', marginBottom: 10, backdropFilter: 'blur(8px)' }}>
                <span className="center" style={{ width: 26, height: 26, borderRadius: 7, background: 'rgba(255,255,255,.14)', fontSize: 12, fontWeight: 700 }}>{i + 1}</span>
                <span style={{ fontSize: 14, fontWeight: 500 }}>{m}</span>
                <span className="grow" />
                <CheckCircle size={16} style={{ color: '#7CE0B0' }} />
              </div>
            ))}
          </div>
        </div>
        <div>
          <p style={{ fontSize: 17, lineHeight: 1.55, fontWeight: 500, letterSpacing: '-0.01em', maxWidth: 380 }}>
            “I had a full 8-module curriculum drafted in under an hour. Coursedy changed how I build products.”
          </p>
          <div className="row" style={{ gap: 11, marginTop: 18 }}>
            <Avatar name="Sarah Okafor" size={36} cat="business" />
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>Sarah Okafor</div>
              <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,.6)' }}>Business Coach · Growth Spark</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Auth (signup + signin) ---------- */
function Auth({ go, mode }) {
  const isSignup = mode === 'signup';
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [pw, setPw] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const submit = async (e) => {
    e && e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      if (isSignup) {
        await window.API.register(email, pw, name);
        window.__user = await window.API.me();
        go('onboarding');
      } else {
        await window.API.login(email, pw);
        window.__user = await window.API.me();
        go('library');
      }
    } catch (err) {
      setError(err?.message || 'Something went wrong. Please try again.');
      setLoading(false);
    }
  };
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr', height: '100vh' }} data-screen-label="Sign up">
      <AuthAside />
      <div className="center" style={{ padding: 24, overflow: 'auto' }}>
        <div style={{ width: '100%', maxWidth: 380 }} className="fade-up">
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 32 }}>
            <button className="btn btn-ghost btn-sm" onClick={() => go('landing')} icon style={{ paddingLeft: 8, color: 'var(--muted)' }}><ChevL size={16} /> Back</button>
            <span className="muted" style={{ fontSize: 13.5 }}>
              {isSignup ? 'Have an account?' : 'New here?'}{' '}
              <a style={{ color: 'var(--brand)', fontWeight: 600, cursor: 'pointer' }} onClick={() => go(isSignup ? 'signin' : 'signup')}>{isSignup ? 'Sign in' : 'Sign up'}</a>
            </span>
          </div>
          <h1 style={{ fontSize: 30, letterSpacing: '-0.03em' }}>{isSignup ? 'Create your account' : 'Welcome back'}</h1>
          <p className="muted" style={{ fontSize: 15, marginTop: 8 }}>{isSignup ? 'Start free — generate your first course in minutes.' : 'Sign in to keep building courses.'}</p>

          <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 15, marginTop: 26 }}>
            {isSignup && (
              <div><label className="label">Full name</label>
                <input className="field" placeholder="Alex Rivera" value={name} onChange={e => setName(e.target.value)} /></div>
            )}
            <div><label className="label">Email</label>
              <input className="field" type="email" placeholder="you@email.com" value={email} onChange={e => setEmail(e.target.value)} /></div>
            <div>
              <div className="row" style={{ justifyContent: 'space-between' }}>
                <label className="label">Password</label>
                {!isSignup && <a className="label" style={{ color: 'var(--brand)', cursor: 'pointer' }}>Forgot?</a>}
              </div>
              <input className="field" type="password" placeholder="••••••••" value={pw} onChange={e => setPw(e.target.value)} />
            </div>
            <Btn variant="brand" block style={{ height: 48, marginTop: 4 }} type="submit" disabled={loading}>
              {loading ? <span className="spinner" /> : <>{isSignup ? 'Create account' : 'Sign in'} <ArrowR /></>}
            </Btn>
            {error && (
              <div style={{ color: '#D9415F', fontSize: 13.5, marginTop: 4, lineHeight: 1.45 }}>{error}</div>
            )}
            {!isSignup && (
              <div className="muted" style={{ fontSize: 12.5, marginTop: 4, lineHeight: 1.4 }}>
                Use demo: <code style={{ color: 'var(--ink-2)' }}>demo@coursedy.com</code> / <code style={{ color: 'var(--ink-2)' }}>Demo1234!</code>
              </div>
            )}
          </form>

          <p className="muted" style={{ fontSize: 12, textAlign: 'center', marginTop: 18, lineHeight: 1.5 }}>
            By continuing you agree to Coursedy’s <a style={{ color: 'var(--ink-2)', textDecoration: 'underline' }}>Terms</a> & <a style={{ color: 'var(--ink-2)', textDecoration: 'underline' }}>Privacy Policy</a>.
          </p>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   Onboarding — 3 steps
   ============================================================ */
const ONB_ROLES = [
  { id: 'learner', label: 'Learn new skills', sub: 'Generate courses for yourself', icon: 'Compass' },
  { id: 'creator', label: 'Create & sell courses', sub: 'Build paid courses faster', icon: 'Star' },
  { id: 'team', label: 'Train my team', sub: 'Onboarding & compliance', icon: 'Briefcase' },
  { id: 'educator', label: 'Teach students', sub: 'Curriculum & assessments', icon: 'Book' },
];
const ONB_GOALS = ['Build my first course', 'Replace blank-page drafting', 'Standardize team training', 'Create a course to sell', 'Just exploring'];

function Onboarding({ go }) {
  const [step, setStep] = useState(0);
  const [role, setRole] = useState(null);
  const [topics, setTopics] = useState([]);
  const [goal, setGoal] = useState(null);
  const total = 3;
  const next = () => step < total - 1 ? setStep(step + 1) : go('creator');
  const back = () => step > 0 ? setStep(step - 1) : go('landing');
  const canNext = [role, topics.length > 0, goal][step];
  const toggleTopic = (id) => setTopics(t => t.includes(id) ? t.filter(x => x !== id) : [...t, id]);

  return (
    <div className="center" style={{ minHeight: '100vh', background: 'var(--paper)', padding: 24 }} data-screen-label="Onboarding">
      <div style={{ width: '100%', maxWidth: 620 }}>
        {/* header */}
        <div className="row" style={{ justifyContent: 'space-between', marginBottom: 30 }}>
          <Logo onClick={() => go('landing')} />
          <span className="mono" style={{ fontSize: 12, color: 'var(--faint)' }}>STEP {step + 1} / {total}</span>
        </div>
        {/* progress */}
        <div className="row" style={{ gap: 8, marginBottom: 38 }}>
          {[0, 1, 2].map(i => <div key={i} style={{ flex: 1 }}><Progress value={i <= step ? 100 : 0} height={5} /></div>)}
        </div>

        <div key={step} className="fade-up">
          {step === 0 && (
            <>
              <h1 style={{ fontSize: 28, letterSpacing: '-0.03em' }}>What brings you to Coursedy?</h1>
              <p className="muted" style={{ marginTop: 8, fontSize: 15 }}>We’ll tailor your workspace and templates.</p>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 26 }}>
                {ONB_ROLES.map(r => {
                  const Icon = ICON_BY_NAME(r.icon);
                  const on = role === r.id;
                  return (
                    <button key={r.id} onClick={() => setRole(r.id)} className="card" style={{ textAlign: 'left', padding: '18px 18px', cursor: 'pointer',
                      border: on ? '1.5px solid var(--brand)' : '1px solid var(--line)', boxShadow: on ? 'var(--sh-sm)' : 'none', background: on ? 'var(--brand-tint)' : 'var(--surface)' }}>
                      <div className="row" style={{ justifyContent: 'space-between' }}>
                        <span className="center" style={{ width: 40, height: 40, borderRadius: 11, background: on ? 'var(--brand)' : 'var(--surface-2)', color: on ? '#fff' : 'var(--ink-2)' }}><Icon size={20} /></span>
                        {on && <CheckCircle size={20} style={{ color: 'var(--brand)' }} />}
                      </div>
                      <div style={{ fontSize: 15.5, fontWeight: 600, marginTop: 14 }}>{r.label}</div>
                      <div className="muted" style={{ fontSize: 13, marginTop: 3 }}>{r.sub}</div>
                    </button>
                  );
                })}
              </div>
            </>
          )}
          {step === 1 && (
            <>
              <h1 style={{ fontSize: 28, letterSpacing: '-0.03em' }}>What topics interest you?</h1>
              <p className="muted" style={{ marginTop: 8, fontSize: 15 }}>Pick a few — we’ll surface relevant templates and examples.</p>
              <div className="row" style={{ flexWrap: 'wrap', gap: 10, marginTop: 26 }}>
                {CATEGORIES.map(c => {
                  const on = topics.includes(c.id);
                  return (
                    <button key={c.id} onClick={() => toggleTopic(c.id)} className={`chip ${on ? 'active' : ''}`} style={{ height: 42, paddingLeft: 8, paddingRight: 16, fontSize: 14.5 }}>
                      <span style={{ width: 24, height: 24, borderRadius: 7, background: c.grad }} />{c.name}
                      {on && <Check size={15} />}
                    </button>
                  );
                })}
              </div>
              <p className="muted" style={{ fontSize: 13, marginTop: 18 }}>{topics.length} selected</p>
            </>
          )}
          {step === 2 && (
            <>
              <h1 style={{ fontSize: 28, letterSpacing: '-0.03em' }}>What’s your main goal?</h1>
              <p className="muted" style={{ marginTop: 8, fontSize: 15 }}>Last one — then you’re in.</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 26 }}>
                {ONB_GOALS.map(g => {
                  const on = goal === g;
                  return (
                    <button key={g} onClick={() => setGoal(g)} className="card" style={{ textAlign: 'left', padding: '16px 18px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 13,
                      border: on ? '1.5px solid var(--brand)' : '1px solid var(--line)', background: on ? 'var(--brand-tint)' : 'var(--surface)' }}>
                      <span className="center" style={{ width: 22, height: 22, borderRadius: 50, border: on ? 'none' : '2px solid var(--line-strong)', background: on ? 'var(--brand)' : 'transparent', color: '#fff', flexShrink: 0 }}>{on && <Check size={14} />}</span>
                      <span style={{ fontSize: 15.5, fontWeight: 500 }}>{g}</span>
                    </button>
                  );
                })}
              </div>
            </>
          )}
        </div>

        {/* nav */}
        <div className="row" style={{ justifyContent: 'space-between', marginTop: 38 }}>
          <Btn variant="ghost" onClick={back} icon={<ChevL size={16} />}>Back</Btn>
          <Btn variant="brand" onClick={next} disabled={!canNext} iconR={<ArrowR />} style={{ opacity: canNext ? 1 : .5 }}>
            {step === total - 1 ? 'Create my first course' : 'Continue'}
          </Btn>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Auth, Onboarding });
