// screens-auth.jsx — Login + Signup (with real API calls)

// Reusable password input with show/hide toggle
function PasswordInput({ value, onChange, placeholder, required, minLength, autoComplete, autoFocus }) {
  const [show, setShow] = React.useState(false);
  return (
    <div style={{ position: 'relative' }}>
      <input
        className="input"
        type={show ? 'text' : 'password'}
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        required={required}
        minLength={minLength}
        autoComplete={autoComplete}
        autoFocus={autoFocus}
        style={{ paddingRight: 44 }}
      />
      <button
        type="button"
        onClick={() => setShow(s => !s)}
        tabIndex={-1}
        title={show ? 'Hide password' : 'Show password'}
        style={{
          position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)',
          background: 'none', border: 'none', cursor: 'pointer',
          color: 'var(--fg3)', padding: 4, display: 'flex', alignItems: 'center',
          borderRadius: 6, lineHeight: 1,
        }}
        onMouseEnter={e => e.currentTarget.style.color = 'var(--psy-ink)'}
        onMouseLeave={e => e.currentTarget.style.color = 'var(--fg3)'}
      >
        <Icon name={show ? 'visibility_off' : 'visibility'} style={{ fontSize: 20 }} />
      </button>
    </div>
  );
}

function AuthShell({ children, kicker, title, subtitle }) {
  return (
    <div style={{
      minHeight: 'calc(100vh - 48px)',
      display: 'grid',
      gridTemplateColumns: '1fr 1fr',
    }}>
      <aside style={{
        background: 'var(--psy-surface)',
        borderRight: '1px solid var(--psy-rule)',
        padding: '56px 64px',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        position: 'relative', overflow: 'hidden',
      }}>
        <a className="brand" onClick={(e) => e.preventDefault()} style={{ position: 'relative', zIndex: 2 }}>
          <span className="glyph"><PsycheMark size={28} /></span>
          Psyche
        </a>
        <div style={{ position: 'absolute', inset: 0, padding: 56, display: 'grid', placeItems: 'center' }}>
          <div style={{ width: '92%', maxWidth: 460, opacity: 0.95 }}>
            <ThreadArt />
          </div>
        </div>
        <div style={{ position: 'relative', zIndex: 2, maxWidth: 420 }}>
          <p className="display" style={{
            fontSize: 28, fontWeight: 500, letterSpacing: '-0.025em',
            lineHeight: 1.15, color: 'var(--psy-ink)', textWrap: 'balance',
          }}>
            "Finding the right psychologist used to feel like throwing darts in the dark. Now it doesn't."
          </p>
          <div style={{ marginTop: 14, fontSize: 13, color: 'var(--fg2)' }}>
            — Maria K., Nicosia
          </div>
        </div>
      </aside>

      <main style={{
        padding: '56px 72px',
        display: 'flex', flexDirection: 'column', justifyContent: 'center',
        maxWidth: 560,
      }}>
        {kicker && <span className="eyebrow" style={{ color: 'var(--psy-accent)' }}>{kicker}</span>}
        <h1 className="display" style={{ fontSize: 38, fontWeight: 500, letterSpacing: '-0.025em', marginTop: 10, textWrap: 'balance' }}>
          {title}
        </h1>
        {subtitle && <p style={{ color: 'var(--fg2)', marginTop: 12, fontSize: 15, lineHeight: 1.55, maxWidth: 440 }}>{subtitle}</p>}
        <div style={{ marginTop: 32 }}>
          {children}
        </div>
      </main>
    </div>
  );
}

function SocialRow({ onAuth }) {
  const GOOGLE_CLIENT_ID = '140535414511-opindnumda1f5d7vpsk2kbk98njd86ku.apps.googleusercontent.com';

  function handleGoogleClick() {
    if (!window.google) return alert('Google SDK not loaded yet, please try again.');
    window.google.accounts.id.initialize({
      client_id: GOOGLE_CLIENT_ID,
      callback: async ({ credential }) => {
        try {
          const r = await fetch('/api/auth/google', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ credential }),
          });
          const data = await r.json();
          if (!r.ok) return alert(data.error || 'Google login failed.');
          onAuth && onAuth(data);
        } catch (e) {
          alert('Google login failed. Please try again.');
        }
      },
    });
    window.google.accounts.id.prompt();
  }

  return (
    <div style={{ marginBottom: 16 }}>
      <button className="btn ghost" style={{ width: '100%', justifyContent: 'center', gap: 8 }}
        onClick={handleGoogleClick}>
        <GoogleGlyph /> Continue with Google
      </button>
    </div>
  );
}
function GoogleGlyph() {
  return (
    <svg width="16" height="16" viewBox="0 0 48 48"><path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3c-1.6 4.7-6 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3 0 5.8 1.1 8 3l5.7-5.7C34 6.3 29.3 4.5 24 4.5 12.7 4.5 3.5 13.7 3.5 25S12.7 45.5 24 45.5s20.5-9.2 20.5-20.5c0-1.4-.2-2.8-.4-4.5z"/><path fill="#FF3D00" d="m6.3 14.7 6.6 4.8C14.7 16.1 19 13 24 13c3 0 5.8 1.1 8 3l5.7-5.7C34 6.3 29.3 4.5 24 4.5c-7.6 0-14.2 4.3-17.7 10.7"/><path fill="#4CAF50" d="M24 45.5c5.2 0 9.9-2 13.4-5.2L31 35.1C29 36.7 26.6 37.5 24 37.5c-5.2 0-9.6-3.3-11.2-8H6.1l-.1.1c3.4 6.7 10.4 11.4 18 11.4"/><path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.3-2.2 4.3-4.3 5.6l6.4 5.2c-.5.5 6.6-4.8 6.6-13.8 0-1.4-.2-2.8-.4-4.5"/></svg>
  );
}
function AppleGlyph() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
      <path d="M16.36 12.78c0-2.55 2.08-3.78 2.18-3.84-1.19-1.73-3.04-1.97-3.7-2-1.57-.16-3.07.93-3.87.93-.8 0-2.04-.9-3.36-.88-1.73.03-3.32 1-4.21 2.55-1.8 3.13-.46 7.74 1.3 10.27.86 1.24 1.88 2.63 3.21 2.58 1.29-.05 1.78-.83 3.34-.83 1.55 0 2 .83 3.37.8 1.39-.03 2.27-1.26 3.12-2.51.98-1.44 1.39-2.84 1.41-2.92-.03-.01-2.7-1.04-2.73-4.13zM13.85 4.83c.71-.86 1.19-2.06 1.06-3.25-1.02.04-2.26.68-3 1.54-.66.76-1.24 1.98-1.08 3.15 1.14.09 2.31-.58 3.02-1.44z"/>
    </svg>
  );
}
function Divider({ label = 'or' }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '16px 0', color: 'var(--fg3)', fontSize: 12, fontWeight: 500 }}>
      <span style={{ flex: 1, height: 1, background: 'var(--psy-rule)' }}></span>
      {label}
      <span style={{ flex: 1, height: 1, background: 'var(--psy-rule)' }}></span>
    </div>
  );
}

// ===========================================================
//  LOGIN
// ===========================================================
function LoginScreen({ onLogin, onSwitchSignup }) {
  const { t } = useLang();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const { token, user } = await API.login({ email, password });
      if (remember) localStorage.setItem('psyche-auth', JSON.stringify({ token, user }));
      onLogin({ user });
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <AuthShell
      kicker={t('signin_new')}
      title={t('signin_title')}
      subtitle={t('signin_sub')}>
      <form onSubmit={handleSubmit}>
        <div className="field-label">{t('signin_email')}</div>
        <input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" required />

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 16 }}>
          <span className="field-label" style={{ margin: 0 }}>{t('signin_password')}</span>
          <a className="btn link" style={{ fontSize: 12 }} href="#">{t('signin_forgot')}</a>
        </div>
        <PasswordInput value={password} onChange={e => setPassword(e.target.value)} placeholder={t('signin_password')} required />

        {error && (
          <div style={{ marginTop: 10, padding: '10px 14px', background: '#FEE2E2', borderRadius: 10, fontSize: 13, color: '#DC2626' }}>
            {error}
          </div>
        )}

        <label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 14, fontSize: 13, color: 'var(--fg2)' }}>
          <input type="checkbox" checked={remember} onChange={() => setRemember(!remember)} style={{ accentColor: 'var(--psy-ink)' }} />
          {t('signin_keep')}
        </label>

        <button className="btn primary lg block" style={{ marginTop: 22 }} type="submit" disabled={loading}>
          {loading ? t('signin_signing') : t('signin_btn')}
        </button>
      </form>

      <Divider label="ή" />
      <SocialRow onAuth={({ token, user }) => {
        localStorage.setItem('psyche-auth', JSON.stringify({ token, user }));
        onLogin({ user });
      }} />

      <div style={{ marginTop: 12, fontSize: 14, color: 'var(--fg2)' }}>
        {t('signin_new')} <button className="btn link" onClick={onSwitchSignup} style={{ fontSize: 14, color: 'var(--psy-ink)', fontWeight: 600 }}>{t('signin_create')}</button>
      </div>

      <div style={{ marginTop: 32, fontSize: 11, color: 'var(--fg3)', lineHeight: 1.6 }}>
        <Icon name="lock" className="sm" style={{ verticalAlign: -2 }} /> Psyche is GDPR-compliant. We never share your data with psychologists you haven't messaged.
      </div>
    </AuthShell>
  );
}

// ===========================================================
//  SIGNUP — three small steps
//  preRole: if passed, skips step 1 and locks the role
// ===========================================================
function SignupScreen({ onSignup, onSwitchLogin, preRole = null }) {
  const { t } = useLang();
  const [step, setStep] = useState(preRole ? 2 : 1);
  const [role, setRole] = useState(preRole);
  const [form, setForm] = useState({
    name: '', email: '', password: '', district: 'Nicosia', accept: false,
    licenseNumber: '', credentials: '', files: [],
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [submitted, setSubmitted] = useState(false); // pro-only success screen

  function up(k, v) { setForm({ ...form, [k]: v }); }
  const isPro = role === 'pro';

  // Pro signup: show success screen within the same page instead of routing away
  if (submitted && isPro) {
    return (
      <AuthShell kicker="Application submitted" title="We've got your application." subtitle={null}>
        <div style={{ textAlign: 'center', padding: '8px 0' }}>
          <div style={{ width: 64, height: 64, borderRadius: 18, background: 'var(--psy-leaf-soft)', display: 'grid', placeItems: 'center', margin: '0 auto 20px' }}>
            <Icon name="check_circle" style={{ fontSize: 34, color: 'var(--psy-leaf)' }} />
          </div>
          <p style={{ color: 'var(--fg2)', fontSize: 15, lineHeight: 1.6, marginBottom: 24 }}>
            Our team will verify your licence against the Cyprus Psychologists Board (ΠΣΨΨ) registry — usually within 24 hours.
            We will email <strong style={{ color: 'var(--psy-ink)' }}>{form.email}</strong> once you are approved.
          </p>
          <button className="btn ghost block" onClick={onSwitchLogin}>
            Back to sign in
          </button>
          <div style={{ marginTop: 14, fontSize: 12, color: 'var(--fg3)' }}>
            <Icon name="lock" className="sm" style={{ verticalAlign: -2 }} /> Your profile will not appear in the directory until verified.
          </div>
        </div>
      </AuthShell>
    );
  }

  async function handleFinish() {
    setError('');
    setLoading(true);
    try {
      const { token, user } = await API.signup({
        name: form.name,
        email: form.email,
        password: form.password,
        role: isPro ? 'pro' : 'user',
        district: form.district,
        credentials: isPro ? form.credentials : undefined,
        license_number: isPro ? form.licenseNumber : undefined,
      });
      localStorage.setItem('psyche-auth', JSON.stringify({ token, user }));
      if (isPro) {
        // Upload documents if the psychologist attached any
        if (form.files && form.files.length > 0) {
          await fetch('/api/psychologists/upload-docs', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token },
            body: JSON.stringify({ files: form.files }),
          }).catch(e => console.warn('[upload]', e.message));
        }
        // Show in-page success screen — don't try to render the provider dashboard yet
        setSubmitted(true);
      } else {
        onSignup({ role: user.role, user });
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <AuthShell
      kicker={step === 1 ? t('signup_title') : isPro ? 'Psychologist sign-up' : 'Almost there'}
      title={
        step === 1 ? t('signup_title') :
        step === 2 ? (isPro ? 'Tell us about your practice.' : 'Tell us a little about you.') :
        'One last thing.'
      }
      subtitle={
        step === 1 ? 'Psyche serves people seeking help and the psychologists who help them. Pick the one that fits.' :
        step === 2 ? (isPro ? 'Public details — these appear on your profile. You can edit any of this later.' : 'This stays private. We use it to match you and to fill in the basics later.') :
        (isPro ? t('signup_pro_sub') : 'Take a look. You can change anything later.')
      }>
      <div className="quiz-progress" style={{ maxWidth: 320 }}>
        {[1, 2, 3].map(i => (
          <span key={i} className={`seg ${i < step ? 'done' : i === step ? 'now' : ''}`}></span>
        ))}
      </div>

      {step === 1 && (
        <div style={{ marginTop: 28 }}>
          <div style={{ display: 'grid', gap: 12 }}>
            {[
              { id: 'user', icon: 'person', title: "I'm looking for a psychologist", sub: 'Browse, get matched, book sessions, journal your mood, talk anonymously in the community.' },
              { id: 'pro',  icon: 'medical_services', title: "I'm a licensed psychologist", sub: 'List your practice, receive enquiries, message clients, get verified reviews.' },
            ].map(r => (
              <button key={r.id}
                onClick={() => setRole(r.id)}
                className={`quiz-option ${role === r.id ? 'selected' : ''}`}
                style={{ alignItems: 'flex-start', padding: '20px 22px' }}>
                <span className="key" style={{ width: 36, height: 36, borderRadius: 10 }}>
                  <Icon name={r.icon} className="sm" />
                </span>
                <span style={{ display: 'flex', flexDirection: 'column', gap: 4, textAlign: 'left' }}>
                  <strong style={{ fontSize: 16 }}>{r.title}</strong>
                  <span style={{ fontSize: 13, color: role === r.id ? 'rgba(255,255,255,0.78)' : 'var(--fg2)', lineHeight: 1.4, fontWeight: 400 }}>{r.sub}</span>
                </span>
              </button>
            ))}
          </div>
          <button className="btn primary lg block" style={{ marginTop: 24 }} disabled={!role} onClick={() => setStep(2)}>
            {t('btn_continue')}
          </button>
        </div>
      )}

      {step === 2 && (
        <form onSubmit={(e) => { e.preventDefault(); setStep(3); }} style={{ marginTop: 24 }}>
          <div className="field-label">{t('name_field')}</div>
          <input className="input" required value={form.name} onChange={e => up('name', e.target.value)} placeholder={isPro ? 'Dr. Elena Constantinou' : 'Maria K.'} />

          {isPro && (
            <>
              <div className="field-label" style={{ marginTop: 16 }}>Title / credentials shown publicly</div>
              <input className="input" required value={form.credentials} onChange={e => up('credentials', e.target.value)} placeholder="MSc, Licensed Counselling Psychologist" />
            </>
          )}

          <div className="field-label" style={{ marginTop: 16 }}>{t('email_field')}</div>
          <input className="input" type="email" required value={form.email} onChange={e => up('email', e.target.value)} placeholder="you@example.com" />

          <div className="field-label" style={{ marginTop: 16 }}>{t('password_field')}</div>
          <PasswordInput required minLength={8} value={form.password} onChange={e => up('password', e.target.value)} placeholder="At least 8 characters" />

          <div className="field-label" style={{ marginTop: 16 }}>District</div>
          <select className="select" value={form.district} onChange={e => up('district', e.target.value)}>
            {DISTRICTS.map(d => <option key={d} value={d}>{d}</option>)}
          </select>

          <div style={{ display: 'flex', gap: 10, marginTop: 26 }}>
            <button className="btn ghost" type="button" onClick={() => setStep(1)}>
              <Icon name="arrow_back" className="sm" /> {t('quiz_back')}
            </button>
            <button className="btn primary lg" type="submit" style={{ flex: 1 }}>{t('btn_continue')}</button>
          </div>
        </form>
      )}

      {step === 3 && (
        <div style={{ marginTop: 24 }}>
          {isPro ? (
            <>
              <div className="field-label">Your licence number (ΠΣΨΨ)</div>
              <input className="input" value={form.licenseNumber} onChange={e => up('licenseNumber', e.target.value)} placeholder="e.g. ΠΣΨΨ 1284" />
              <div style={{ marginTop: 18 }}>
                <div className="field-label">Upload your diploma + licence</div>
                <label style={{ display: 'block', border: '1.5px dashed var(--psy-rule)', borderRadius: 14, padding: 24, textAlign: 'center', background: 'var(--psy-surface)', cursor: 'pointer' }}>
                  <input type="file" multiple accept=".pdf,.jpg,.jpeg,.png" style={{ display: 'none' }}
                    onChange={async (e) => {
                      const fileList = Array.from(e.target.files);
                      const encoded = await Promise.all(fileList.map(f => new Promise((resolve, reject) => {
                        const reader = new FileReader();
                        reader.onload = () => resolve({ name: f.name, type: f.type, size: f.size, data: reader.result });
                        reader.onerror = reject;
                        reader.readAsDataURL(f);
                      })));
                      up('files', encoded);
                    }}
                  />
                  <Icon name="upload_file" style={{ fontSize: 32, color: 'var(--fg2)' }} />
                  {form.files && form.files.length > 0 ? (
                    <div style={{ marginTop: 8 }}>
                      {form.files.map((f, i) => (
                        <div key={i} style={{ fontSize: 13, fontWeight: 500, color: 'var(--psy-accent)', marginTop: 4 }}>
                          <Icon name="check_circle" className="sm" style={{ verticalAlign: -2, marginRight: 4 }} />
                          {f.name} <span style={{ color: 'var(--fg3)', fontWeight: 400 }}>({(f.size / 1024).toFixed(0)} KB)</span>
                        </div>
                      ))}
                      <div style={{ marginTop: 8, fontSize: 12, color: 'var(--fg3)' }}>Click to add more files</div>
                    </div>
                  ) : (
                    <>
                      <div style={{ marginTop: 8, fontSize: 14, fontWeight: 500 }}>Click to browse files</div>
                      <div style={{ marginTop: 4, fontSize: 12, color: 'var(--fg3)' }}>PDF or image · up to 10 MB each</div>
                    </>
                  )}
                </label>
              </div>
              <div style={{ marginTop: 18, padding: 14, background: 'var(--psy-leaf-soft)', borderRadius: 12, fontSize: 13, color: 'var(--psy-leaf)', lineHeight: 1.5 }}>
                <Icon name="verified" className="sm" /> Our admin team checks every licence. Usually within 24 hours. Your profile stays hidden until then.
              </div>
            </>
          ) : (
            <>
              <div className="field-label">Anything we should know before showing you matches? (optional)</div>
              <textarea className="textarea" placeholder="e.g. I've done CBT before and want to try something different. I prefer evenings." />
              <div style={{ marginTop: 18, padding: 14, background: 'var(--psy-leaf-soft)', borderRadius: 12, fontSize: 13, color: 'var(--psy-leaf)', lineHeight: 1.5 }}>
                <Icon name="lock" className="sm" /> This stays private. Only used to refine your recommendations.
              </div>
            </>
          )}

          <label style={{ display: 'flex', gap: 8, marginTop: 22, fontSize: 13, color: 'var(--fg2)', lineHeight: 1.5 }}>
            <input type="checkbox" checked={form.accept} onChange={() => up('accept', !form.accept)} style={{ marginTop: 3, accentColor: 'var(--psy-ink)' }} />
            I agree to Psyche's <a className="btn link" style={{ fontSize: 13 }}>Terms of Service</a> and <a className="btn link" style={{ fontSize: 13 }}>Privacy Policy</a>{isPro ? '. I confirm my licence is valid and in good standing.' : '.'}
          </label>

          {error && (
            <div style={{ marginTop: 12, padding: '10px 14px', background: '#FEE2E2', borderRadius: 10, fontSize: 13, color: '#DC2626' }}>
              {error}
            </div>
          )}

          <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
            <button className="btn ghost" type="button" onClick={() => setStep(2)}>
              <Icon name="arrow_back" className="sm" /> {t('quiz_back')}
            </button>
            <button className="btn primary lg" disabled={!form.accept || loading} onClick={handleFinish} style={{ flex: 1 }}>
              {loading ? t('signup_creating') : isPro ? t('signup_pro_btn') : t('signup_btn')}
            </button>
          </div>
        </div>
      )}

      <div style={{ marginTop: 32, fontSize: 14, color: 'var(--fg2)' }}>
        {t('signup_already')} <button className="btn link" onClick={onSwitchLogin} style={{ fontSize: 14, color: 'var(--psy-ink)', fontWeight: 600 }}>{t('signin_btn')}</button>
      </div>
    </AuthShell>
  );
}

// ===========================================================
//  AUTH MODAL — lightweight overlay for guest → action gating
// ===========================================================
function AuthModal({ view, onClose, onLogin, onSignup, onSwitchView, onOpenProSignup }) {
  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 50,
        background: 'rgba(15, 21, 37, 0.5)',
        backdropFilter: 'blur(4px)',
        display: 'grid', placeItems: 'center',
        padding: 16,
      }}>
      <div
        onClick={e => e.stopPropagation()}
        style={{
          background: 'var(--psy-surface-2)',
          borderRadius: 24,
          padding: '36px 40px',
          width: '100%',
          maxWidth: 460,
          boxShadow: '0 24px 64px rgba(15,21,37,0.22)',
          position: 'relative',
        }}>
        {/* Close */}
        <button
          onClick={onClose}
          style={{
            position: 'absolute', top: 16, right: 16,
            appearance: 'none', border: 0, background: 'var(--psy-surface)',
            width: 32, height: 32, borderRadius: '50%', cursor: 'pointer',
            display: 'grid', placeItems: 'center', color: 'var(--fg2)',
          }}>
          <Icon name="close" className="sm" />
        </button>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <PsycheMark size={24} />
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 18, letterSpacing: '-0.02em' }}>Psyche</span>
        </div>

        {view === 'login'
          ? <ModalLogin onLogin={onLogin} onSwitch={() => onSwitchView('signup')} onOpenProSignup={onOpenProSignup} />
          : <ModalSignup onSignup={onSignup} onSwitch={() => onSwitchView('login')} onOpenProSignup={onOpenProSignup} />}
      </div>
    </div>
  );
}

function ModalLogin({ onLogin, onSwitch, onOpenProSignup }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    setError(''); setLoading(true);
    try {
      const { token, user } = await API.login({ email, password });
      localStorage.setItem('psyche-auth', JSON.stringify({ token, user }));
      onLogin({ user });
    } catch (err) { setError(err.message); }
    finally { setLoading(false); }
  }

  return (
    <>
      <h2 className="display" style={{ fontSize: 26, fontWeight: 600, marginBottom: 4 }}>Sign in</h2>
      <p style={{ fontSize: 14, color: 'var(--fg2)', marginBottom: 24 }}>
        You need an account to do this. Already have one? Sign in below.
      </p>
      <form onSubmit={handleSubmit}>
        <div className="field-label">Email</div>
        <input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" required autoFocus />
        <div className="field-label" style={{ marginTop: 14 }}>Password</div>
        <PasswordInput value={password} onChange={e => setPassword(e.target.value)} placeholder="Your password" required />
        {error && (
          <div style={{ marginTop: 10, padding: '9px 13px', background: '#FEE2E2', borderRadius: 10, fontSize: 13, color: '#DC2626' }}>
            {error}
          </div>
        )}
        <button className="btn primary lg block" style={{ marginTop: 20 }} type="submit" disabled={loading}>
          {loading ? 'Signing in…' : 'Sign in'}
        </button>
      </form>
      <Divider label="ή" />
      <SocialRow onAuth={({ token, user }) => {
        localStorage.setItem('psyche-auth', JSON.stringify({ token, user }));
        onLogin({ user });
      }} />
      <div style={{ marginTop: 8, textAlign: 'center', fontSize: 14, color: 'var(--fg2)' }}>
        No account? <button className="btn link" onClick={onSwitch} style={{ fontSize: 14, fontWeight: 600, color: 'var(--psy-ink)' }}>Create one — it's free</button>
      </div>
      {onOpenProSignup && (
        <div style={{ marginTop: 12, textAlign: 'center', fontSize: 13, color: 'var(--fg3)' }}>
          Are you a psychologist? <button className="btn link" onClick={onOpenProSignup} style={{ fontSize: 13, color: 'var(--psy-accent)', fontWeight: 600 }}>Register your practice →</button>
        </div>
      )}
    </>
  );
}

function ModalSignup({ onSignup, onSwitch, onOpenProSignup }) {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    setError(''); setLoading(true);
    try {
      const { token, user } = await API.signup({ name, email, password, role: 'user' });
      localStorage.setItem('psyche-auth', JSON.stringify({ token, user }));
      onSignup({ role: 'user', user });
    } catch (err) { setError(err.message); }
    finally { setLoading(false); }
  }

  return (
    <>
      <h2 className="display" style={{ fontSize: 26, fontWeight: 600, marginBottom: 4 }}>Create an account</h2>
      <p style={{ fontSize: 14, color: 'var(--fg2)', marginBottom: 24 }}>Free, private, and takes 30 seconds.</p>
      <form onSubmit={handleSubmit}>
        <div className="field-label">Your name</div>
        <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Maria K." required autoFocus autoComplete="off" />
        <div className="field-label" style={{ marginTop: 14 }}>Email</div>
        <input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" required autoComplete="off" />
        <div className="field-label" style={{ marginTop: 14 }}>Password</div>
        <PasswordInput value={password} onChange={e => setPassword(e.target.value)} placeholder="At least 8 characters" required minLength={8} autoComplete="new-password" />
        {error && (
          <div style={{ marginTop: 10, padding: '9px 13px', background: '#FEE2E2', borderRadius: 10, fontSize: 13, color: '#DC2626' }}>
            {error}
          </div>
        )}
        <button className="btn primary lg block" style={{ marginTop: 20 }} type="submit" disabled={loading}>
          {loading ? 'Creating account…' : 'Create account'}
        </button>
      </form>
      <Divider label="ή" />
      <SocialRow onAuth={({ token, user }) => {
        localStorage.setItem('psyche-auth', JSON.stringify({ token, user }));
        onSignup({ role: 'user', user });
      }} />
      <div style={{ marginTop: 8, textAlign: 'center', fontSize: 14, color: 'var(--fg2)' }}>
        Already have an account? <button className="btn link" onClick={onSwitch} style={{ fontSize: 14, fontWeight: 600, color: 'var(--psy-ink)' }}>Sign in</button>
      </div>
      {onOpenProSignup && (
        <div style={{ marginTop: 12, textAlign: 'center', fontSize: 13, color: 'var(--fg3)' }}>
          Are you a psychologist? <button className="btn link" onClick={onOpenProSignup} style={{ fontSize: 13, color: 'var(--psy-accent)', fontWeight: 600 }}>Register your practice →</button>
        </div>
      )}
      <div style={{ marginTop: 12, fontSize: 11, color: 'var(--fg3)', textAlign: 'center', lineHeight: 1.5 }}>
        <Icon name="lock" className="sm" style={{ verticalAlign: -2 }} /> GDPR-compliant. We never share your data.
      </div>
    </>
  );
}

Object.assign(window, { LoginScreen, SignupScreen, AuthModal });
