// Login + Set-Password screens — Journey Tech branding

// ─── Shared brand header ──────────────────────────────────────────
function BrandHeader() {
  return (
    <div style={{ textAlign: 'center', marginBottom: 28, color: '#fff' }}>
      <div style={{
        width: 68, height: 68, borderRadius: 18,
        background: 'rgba(255,255,255,0.12)',
        border: '2px solid rgba(255,255,255,0.25)',
        display: 'grid', placeItems: 'center',
        margin: '0 auto 14px',
        fontSize: 24, fontWeight: 700,
        fontFamily: 'var(--font-display)', color: '#fff',
      }}>JT</div>
      <h1 style={{ margin: 0, fontSize: 22, fontFamily: 'var(--font-display)', fontWeight: 700,
                   letterSpacing: '0.06em', color: '#e11d48' }}>
        JOURNEY TECH
      </h1>
      <div style={{ marginTop: 3, opacity: 0.65, fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
        ARS Service Management
      </div>
    </div>
  );
}

const BG_STYLE = {
  minHeight: '100vh',
  background: 'linear-gradient(135deg, #0a1f5c 0%, #1a3a8f 60%, #2851b3 100%)',
  display: 'grid', placeItems: 'center',
  fontFamily: 'var(--font-sans)',
};

function BgCircles() {
  return (
    <svg style={{ position: 'fixed', inset: 0, width: '100%', height: '100%', opacity: 0.06, pointerEvents: 'none' }}
         viewBox="0 0 800 600" preserveAspectRatio="xMidYMid slice">
      {[80,140,200,260,320].map(r => <circle key={r} cx="650" cy="100" r={r} fill="none" stroke="#5ec5ff" strokeWidth="1"/>)}
    </svg>
  );
}

// ─── Login Screen ────────────────────────────────────────────────
function LoginScreen({ onLogin }) {
  const [mode, setMode]           = React.useState('login'); // 'login' | 'forgot'
  const [email, setEmail]         = React.useState('');
  const [password, setPassword]   = React.useState('');
  const [resetEmail, setResetEmail] = React.useState('');
  const [loading, setLoading]     = React.useState(false);
  const [error, setError]         = React.useState(null);
  const [resetSent, setResetSent] = React.useState(false);

  const login = async (e) => {
    e.preventDefault();
    setLoading(true); setError(null);
    const { data, error: err } = await window.sb.auth.signInWithPassword({ email: email.trim(), password });
    if (err) {
      setError(err.message === 'Invalid login credentials'
        ? 'Email หรือรหัสผ่านไม่ถูกต้อง'
        : err.message);
      setLoading(false);
      return;
    }
    onLogin(data.user);
  };

  const sendReset = async (e) => {
    e.preventDefault();
    if (!resetEmail) { setError('กรุณากรอก Email'); return; }
    setLoading(true); setError(null);
    const { error: err } = await window.sb.auth.resetPasswordForEmail(resetEmail.trim(), {
      redirectTo: window.location.origin,
    });
    setLoading(false);
    if (err) setError(err.message);
    else setResetSent(true);
  };

  const switchMode = (m) => { setMode(m); setError(null); setResetSent(false); };

  return (
    <div style={BG_STYLE}>
      <BgCircles/>
      <div style={{ width: 420, maxWidth: '90vw', position: 'relative' }}>
        <BrandHeader/>

        {/* ── Login card ── */}
        {mode === 'login' && (
          <div style={{ background: '#fff', borderRadius: 16, padding: '32px 32px 28px', boxShadow: '0 24px 64px rgba(0,0,0,0.35)' }}>
            <h2 style={{ margin: '0 0 4px', fontFamily: 'var(--font-display)', fontSize: 20, color: 'var(--jt-navy-800)' }}>
              เข้าสู่ระบบ
            </h2>
            <p style={{ margin: '0 0 22px', color: 'var(--text-muted)', fontSize: 13 }}>
              Sign in with your registered email
            </p>
            <form onSubmit={login} style={{ display: 'grid', gap: 14 }}>
              <div className="field">
                <label>Email</label>
                <input className="input" type="email" value={email}
                       onChange={e => { setEmail(e.target.value); setError(null); }}
                       placeholder="your@email.com" required autoFocus
                       style={{ height: 44, fontSize: 14 }}/>
              </div>
              <div className="field">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
                  <label style={{ margin: 0 }}>Password</label>
                  <button type="button" onClick={() => switchMode('forgot')}
                          style={{ background: 'none', border: 'none', cursor: 'pointer',
                                   color: 'var(--jt-red)', fontSize: 12, padding: 0 }}>
                    ลืมรหัสผ่าน?
                  </button>
                </div>
                <input className="input" type="password" value={password}
                       onChange={e => { setPassword(e.target.value); setError(null); }}
                       placeholder="••••••••" required style={{ height: 44, fontSize: 14 }}/>
              </div>
              {error && (
                <div style={{ padding: '10px 14px', background: '#fef2f2', border: '1px solid #fecaca',
                              borderRadius: 8, color: '#dc2626', fontSize: 13,
                              display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Icon name="bell" size={14} color="#dc2626"/> {error}
                </div>
              )}
              <button className="btn btn--primary" type="submit" disabled={loading}
                      style={{ height: 46, fontSize: 15, marginTop: 4, borderRadius: 10 }}>
                {loading ? 'กำลังเข้าสู่ระบบ…' : 'เข้าสู่ระบบ →'}
              </button>
            </form>
          </div>
        )}

        {/* ── Forgot password card ── */}
        {mode === 'forgot' && (
          <div style={{ background: '#fff', borderRadius: 16, padding: '32px 32px 28px', boxShadow: '0 24px 64px rgba(0,0,0,0.35)' }}>
            <h2 style={{ margin: '0 0 4px', fontFamily: 'var(--font-display)', fontSize: 20, color: 'var(--jt-navy-800)' }}>
              ลืมรหัสผ่าน
            </h2>
            <p style={{ margin: '0 0 22px', color: 'var(--text-muted)', fontSize: 13 }}>
              ระบบจะส่งลิงก์ตั้งรหัสผ่านใหม่ไปยัง Email
            </p>
            {resetSent ? (
              <div style={{ display: 'grid', gap: 16 }}>
                <div style={{ padding: 16, background: '#f0fdf4', border: '1px solid #86efac',
                              borderRadius: 10, textAlign: 'center' }}>
                  <div style={{ fontSize: 28, marginBottom: 8 }}>📧</div>
                  <div style={{ fontWeight: 600, color: '#15803d', marginBottom: 4 }}>ส่งลิงก์แล้ว!</div>
                  <div style={{ fontSize: 13, color: '#166534' }}>
                    ตรวจสอบ Inbox ของ <strong>{resetEmail}</strong><br/>
                    คลิกลิงก์ในอีเมล → ระบบจะพาไปตั้งรหัสผ่านใหม่<br/>
                    <span style={{ opacity: 0.75 }}>(หากไม่พบ ตรวจสอบโฟลเดอร์ Spam)</span>
                  </div>
                </div>
                <button type="button" className="btn" onClick={() => switchMode('login')} style={{ height: 44 }}>
                  ← กลับหน้า Login
                </button>
              </div>
            ) : (
              <form onSubmit={sendReset} style={{ display: 'grid', gap: 14 }}>
                <div className="field">
                  <label>Email</label>
                  <input className="input" type="email" value={resetEmail}
                         onChange={e => { setResetEmail(e.target.value); setError(null); }}
                         placeholder="your@email.com" required autoFocus style={{ height: 44, fontSize: 14 }}/>
                </div>
                {error && (
                  <div style={{ padding: '10px 14px', background: '#fef2f2', border: '1px solid #fecaca',
                                borderRadius: 8, color: '#dc2626', fontSize: 13 }}>
                    {error}
                  </div>
                )}
                <button className="btn btn--primary" type="submit" disabled={loading}
                        style={{ height: 46, fontSize: 15, borderRadius: 10 }}>
                  {loading ? 'กำลังส่ง…' : 'ส่งลิงก์ตั้งรหัสผ่านใหม่'}
                </button>
                <button type="button" onClick={() => switchMode('login')}
                        style={{ background: 'none', border: 'none', cursor: 'pointer',
                                 color: 'var(--text-muted)', fontSize: 13, textAlign: 'center', padding: '4px 0' }}>
                  ← กลับหน้า Login
                </button>
              </form>
            )}
          </div>
        )}

        <div style={{ textAlign: 'center', marginTop: 18, color: 'rgba(255,255,255,0.4)', fontSize: 11 }}>
          © {new Date().getFullYear()} Journey Tech Co., Ltd. &nbsp;•&nbsp; ARS v1.0
        </div>
      </div>
    </div>
  );
}

// ─── Set Password Screen (shown after magic link / invite click) ──
function SetPasswordScreen({ userId, onDone }) {
  const [password, setPassword]   = React.useState('');
  const [confirm, setConfirm]     = React.useState('');
  const [loading, setLoading]     = React.useState(false);
  const [error, setError]         = React.useState(null);
  const [success, setSuccess]     = React.useState(false);

  const strength = !password ? 0 : password.length < 8 ? 1 : password.length < 12 ? 2 : 3;
  const strengthLabel = ['', 'อ่อนเกินไป (< 8 ตัว)', 'พอใช้ได้', 'แข็งแกร่ง ✓'][strength];
  const strengthColor = ['', '#ef4444', '#f59e0b', '#22c55e'][strength];

  const handleSet = async (e) => {
    e.preventDefault();
    if (password.length < 8)  { setError('รหัสผ่านต้องมีอย่างน้อย 8 ตัวอักษร'); return; }
    if (password !== confirm)  { setError('รหัสผ่านไม่ตรงกัน'); return; }
    setLoading(true); setError(null);

    // Step 1: save password to auth.users
    const { data: updData, error: err } = await window.sb.auth.updateUser({ password });
    if (err) { setLoading(false); setError(err.message); return; }

    // Step 2: mark profile.password_set=true so SetPasswordScreen never re-appears
    const uid = userId || updData?.user?.id;
    if (uid) {
      const { error: pErr } = await window.sb
        .from('profiles')
        .update({ password_set: true })
        .eq('id', uid);
      if (pErr) console.warn('profile.password_set update failed:', pErr.message);
    }

    setLoading(false);
    setSuccess(true);
    setTimeout(onDone, 1800);
  };

  return (
    <div style={BG_STYLE}>
      <BgCircles/>
      <div style={{ width: 420, maxWidth: '90vw', position: 'relative' }}>
        <BrandHeader/>
        <div style={{ background: '#fff', borderRadius: 16, padding: '32px 32px 28px', boxShadow: '0 24px 64px rgba(0,0,0,0.35)' }}>
          {success ? (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <div style={{ fontSize: 52, marginBottom: 12 }}>✅</div>
              <h2 style={{ margin: '0 0 8px', fontFamily: 'var(--font-display)', fontSize: 20, color: 'var(--jt-navy-800)' }}>
                ตั้งรหัสผ่านสำเร็จ!
              </h2>
              <p style={{ color: 'var(--text-muted)', fontSize: 13, margin: 0 }}>
                กำลังเข้าสู่ระบบ…
              </p>
            </div>
          ) : (
            <>
              <h2 style={{ margin: '0 0 4px', fontFamily: 'var(--font-display)', fontSize: 20, color: 'var(--jt-navy-800)' }}>
                ตั้งรหัสผ่าน
              </h2>
              <p style={{ margin: '0 0 22px', color: 'var(--text-muted)', fontSize: 13 }}>
                กำหนดรหัสผ่านสำหรับใช้ Login ครั้งต่อไป
              </p>
              <form onSubmit={handleSet} style={{ display: 'grid', gap: 14 }}>
                <div className="field">
                  <label>รหัสผ่านใหม่</label>
                  <input className="input" type="password" value={password}
                         onChange={e => { setPassword(e.target.value); setError(null); }}
                         placeholder="อย่างน้อย 8 ตัวอักษร" required autoFocus
                         style={{ height: 44, fontSize: 14 }}/>
                  {password.length > 0 && (
                    <div style={{ marginTop: 8, display: 'flex', gap: 4, alignItems: 'center' }}>
                      {[1,2,3].map(i => (
                        <div key={i} style={{ flex: 1, height: 4, borderRadius: 2, transition: 'background 0.2s',
                                              background: strength >= i ? strengthColor : 'var(--border)' }}/>
                      ))}
                      <span style={{ fontSize: 11, color: strengthColor, minWidth: 80, textAlign: 'right' }}>
                        {strengthLabel}
                      </span>
                    </div>
                  )}
                </div>
                <div className="field">
                  <label>ยืนยันรหัสผ่าน</label>
                  <input className="input" type="password" value={confirm}
                         onChange={e => { setConfirm(e.target.value); setError(null); }}
                         placeholder="กรอกรหัสผ่านอีกครั้ง" required
                         style={{ height: 44, fontSize: 14,
                                  borderColor: confirm && confirm !== password ? '#fca5a5' : '' }}/>
                  {confirm && confirm !== password && (
                    <div style={{ fontSize: 12, color: '#dc2626', marginTop: 4 }}>รหัสผ่านไม่ตรงกัน</div>
                  )}
                </div>
                {error && (
                  <div style={{ padding: '10px 14px', background: '#fef2f2', border: '1px solid #fecaca',
                                borderRadius: 8, color: '#dc2626', fontSize: 13 }}>{error}</div>
                )}
                <button className="btn btn--primary" type="submit" disabled={loading}
                        style={{ height: 46, fontSize: 15, marginTop: 4, borderRadius: 10 }}>
                  {loading ? 'กำลังบันทึก…' : 'ยืนยันรหัสผ่าน →'}
                </button>
              </form>
            </>
          )}
        </div>
        <div style={{ textAlign: 'center', marginTop: 18, color: 'rgba(255,255,255,0.4)', fontSize: 11 }}>
          © {new Date().getFullYear()} Journey Tech Co., Ltd. &nbsp;•&nbsp; ARS v1.0
        </div>
      </div>
    </div>
  );
}

window.LoginScreen      = LoginScreen;
window.SetPasswordScreen = SetPasswordScreen;
