// Login & Forgot-password views

// ─── Helper: store/get auth token ────────────────────────────────────────────
window.authToken = {
  get:    ()    => localStorage.getItem('sol_auth_token'),
  set:    (t)   => localStorage.setItem('sol_auth_token', t),
  clear:  ()    => localStorage.removeItem('sol_auth_token'),
};

// ─── apiFetch helper (attaches Bearer token automatically) ───────────────────
window.apiFetch = (url, opts = {}) => {
  const token = window.authToken.get();
  return fetch(url, {
    ...opts,
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts.headers || {}),
    },
  });
};

// ─── Login View ──────────────────────────────────────────────────────────────
const LoginView = ({ onLogin }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPw,   setShowPw]   = useState(false);
  const [loading,  setLoading]  = useState(false);
  const [error,    setError]    = useState('');
  const [view,     setView]     = useState('login'); // 'login' | 'forgot'
  const usernameRef = useRef(null);

  useEffect(() => { usernameRef.current?.focus(); }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!username.trim() || !password) { setError('กรุณากรอก username และ password'); return; }
    setLoading(true); setError('');
    try {
      const r = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: username.trim(), password }),
      });
      const data = await r.json();
      if (!r.ok) { setError(data.error || 'เข้าสู่ระบบไม่ได้'); return; }
      window.authToken.set(data.token);
      // Reload all init data now that we have an auth token
      try {
        const init = await window.apiFetch('/api/init').then(r => r.ok ? r.json() : null);
        if (init) {
          if (init.products)           window.PRODUCTS           = init.products;
          if (init.orderStatuses)      window.ORDER_STATUSES     = init.orderStatuses;
          if (init.companies)          window.COMPANIES          = init.companies;
          if (init.contacts)           window.CONTACTS           = init.contacts;
          if (init.orders)             window.ORDERS             = init.orders;
          if (init.users)              window.USERS              = init.users;
          if (init.docTypes)           window.DOC_TYPES          = init.docTypes;
          if (init.docRequirements)    window.DOC_REQUIREMENTS   = init.docRequirements;
          if (init.workflows)          window.DEFAULT_WORKFLOWS  = init.workflows;
          if (init.categories)         window.PRODUCT_CATEGORIES = init.categories;
          if (init.conditions)         window.CONDITIONS_DATA    = init.conditions;
          if (init.roles)              window.ROLES              = init.roles;
        }
      } catch {}
      onLogin(data.user);
    } catch {
      setError('ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้');
    } finally {
      setLoading(false);
    }
  };

  if (view === 'forgot') return <ForgotPasswordView onBack={() => setView('login')}/>;

  return (
    <div style={{
      minHeight: '100vh', width: '100%',
      background: '#eeebe6',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}>
      <div style={{ width: '100%', maxWidth: 440 }}>
        {/* Logo */}
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <img src="assets/true-business-logo.png" alt="True Business"
            style={{ height: 34, marginBottom: 14 }}/>
          <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.02em', lineHeight: 1.2, marginBottom: 4 }}>
            B2B Solutions
          </div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-3)' }}>Order Management</div>
        </div>

        {/* Card */}
        <div style={{
          background: 'var(--panel)',
          borderRadius: 10,
          padding: '36px 40px',
          boxShadow: '0 4px 24px rgba(0,0,0,0.08)',
        }}>
          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {error && (
              <div style={{
                padding: '10px 14px', borderRadius: 4,
                background: 'var(--negative-bg)', border: '1px solid var(--negative)',
                fontSize: 12.5, color: 'var(--negative)',
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <Icon name="close" size={12}/>
                {error}
              </div>
            )}

            <div>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                Username
              </label>
              <input
                ref={usernameRef}
                type="text"
                value={username}
                onChange={e => { setUsername(e.target.value); setError(''); }}
                autoComplete="username"
                style={loginInputStyle}
              />
            </div>

            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
                <label style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-2)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                  Password
                </label>
                <button type="button" onClick={() => setView('forgot')} style={{
                  background: 'none', border: 'none', cursor: 'pointer', padding: 0,
                  fontSize: 12, color: 'var(--ink-3)', fontFamily: 'Kanit, sans-serif',
                }}>
                  ลืมรหัสผ่าน?
                </button>
              </div>
              <div style={{ position: 'relative' }}>
                <input
                  type={showPw ? 'text' : 'password'}
                  value={password}
                  onChange={e => { setPassword(e.target.value); setError(''); }}
                  autoComplete="current-password"
                  style={{ ...loginInputStyle, paddingRight: 42 }}
                />
                <button type="button" onClick={() => setShowPw(v => !v)} style={{
                  position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
                  background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)',
                  padding: 4, display: 'inline-flex',
                }}>
                  <Icon name={showPw ? 'eye' : 'eyeOff'} size={15}/>
                </button>
              </div>
            </div>

            <button type="submit" disabled={loading} style={{
              marginTop: 6,
              padding: '13px 0',
              background: loading ? 'var(--ink-4)' : 'var(--true-red)',
              color: '#fff',
              border: 'none', borderRadius: 6,
              fontFamily: 'Kanit, sans-serif', fontSize: 15, fontWeight: 500,
              cursor: loading ? 'not-allowed' : 'pointer',
              letterSpacing: '-0.01em',
              transition: 'background 120ms',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
              {loading ? (
                <>
                  <span style={{ display: 'inline-block', width: 14, height: 14, border: '2px solid rgba(255,255,255,0.4)', borderTopColor: '#fff', borderRadius: '50%', animation: 'spin 0.7s linear infinite' }}/>
                  กำลังตรวจสอบ…
                </>
              ) : 'เข้าสู่ระบบ'}
            </button>
          </form>
        </div>

        <div style={{ textAlign: 'center', marginTop: 20, fontSize: 12, color: 'var(--ink-3)' }}>
          © True Corporation · B2B Product development team
        </div>
      </div>

      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
};

const loginInputStyle = {
  width: '100%', boxSizing: 'border-box',
  padding: '12px 14px',
  border: 'none',
  borderRadius: 6, background: '#f2efea',
  fontFamily: 'Kanit, sans-serif', fontSize: 14,
  color: 'var(--ink)', outline: 'none',
};

// ─── Forgot Password View ────────────────────────────────────────────────────
const ForgotPasswordView = ({ onBack }) => {
  const [email,   setEmail]   = useState('');
  const [loading, setLoading] = useState(false);
  const [sent,    setSent]    = useState(false);
  const [error,   setError]   = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email.trim()) { setError('กรุณากรอก email'); return; }
    setLoading(true); setError('');
    try {
      await fetch('/api/auth/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim() }),
      });
      setSent(true);
    } catch {
      setError('ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh', width: '100%',
      background: '#eeebe6',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}>
      <div style={{ width: '100%', maxWidth: 440 }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <img src="assets/true-business-logo.png" alt="True Business"
            style={{ height: 34, marginBottom: 14 }}/>
          <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.02em', lineHeight: 1.2, marginBottom: 4 }}>
            B2B Solutions
          </div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-3)' }}>Order Management</div>
        </div>

        <div style={{
          background: 'var(--panel)',
          borderRadius: 10,
          padding: '36px 40px',
          boxShadow: '0 4px 24px rgba(0,0,0,0.08)',
        }}>
          {sent ? (
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 40, marginBottom: 16 }}>📧</div>
              <h2 style={{ fontSize: 17, fontWeight: 600, margin: '0 0 8px' }}>ตรวจสอบอีเมลของคุณ</h2>
              <div style={{ fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.7, marginBottom: 24 }}>
                หากอีเมล <strong style={{ color: 'var(--ink)' }}>{email}</strong> มีในระบบ
                เราจะส่งลิงก์รีเซ็ตรหัสผ่านไปให้ภายในไม่กี่นาที
                <br/>กรุณาตรวจสอบโฟลเดอร์ Spam ด้วย
              </div>
              <button onClick={onBack} style={{
                padding: '11px 24px', background: 'var(--bg-2)',
                border: 'none', borderRadius: 6,
                fontFamily: 'Kanit, sans-serif', fontSize: 13, cursor: 'pointer', color: 'var(--ink)',
              }}>
                กลับไปหน้า Login
              </button>
            </div>
          ) : (
            <>
              <button onClick={onBack} style={{
                background: 'none', border: 'none', cursor: 'pointer', padding: 0, marginBottom: 24,
                fontSize: 12, color: 'var(--ink-3)', fontFamily: 'Kanit, sans-serif',
                display: 'inline-flex', alignItems: 'center', gap: 5,
              }}>
                <Icon name="chevronLeft" size={10}/> กลับไปหน้า Login
              </button>

              <div style={{ marginBottom: 24 }}>
                <h1 style={{ fontSize: 20, fontWeight: 700, margin: '0 0 6px', letterSpacing: '-0.02em' }}>ลืมรหัสผ่าน</h1>
                <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>
                  กรอกอีเมลที่ใช้ลงทะเบียน เราจะส่งลิงก์รีเซ็ตรหัสผ่านให้คุณ
                </div>
              </div>

              <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                {error && (
                  <div style={{ padding: '10px 14px', borderRadius: 4, background: 'var(--negative-bg)', border: '1px solid var(--negative)', fontSize: 12.5, color: 'var(--negative)' }}>
                    {error}
                  </div>
                )}

                <div>
                  <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                    อีเมล
                  </label>
                  <input
                    type="email"
                    value={email}
                    onChange={e => { setEmail(e.target.value); setError(''); }}
                    placeholder="yourname@truebusiness.co.th"
                    autoFocus
                    style={loginInputStyle}
                  />
                </div>

                <button type="submit" disabled={loading} style={{
                  marginTop: 6, padding: '13px 0',
                  background: loading ? 'var(--ink-4)' : 'var(--true-red)',
                  color: '#fff', border: 'none', borderRadius: 6,
                  fontFamily: 'Kanit, sans-serif', fontSize: 15, fontWeight: 500,
                  cursor: loading ? 'not-allowed' : 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                }}>
                  {loading ? 'กำลังส่ง…' : 'ส่งลิงก์รีเซ็ตรหัสผ่าน'}
                </button>
              </form>

              <div style={{ marginTop: 18, fontSize: 12, color: 'var(--ink-3)', textAlign: 'center' }}>
                ไม่มีอีเมลในระบบ? ติดต่อ System Admin
              </div>
            </>
          )}
        </div>

        <div style={{ textAlign: 'center', marginTop: 20, fontSize: 12, color: 'var(--ink-3)' }}>
          © True Corporation · B2B Product development team
        </div>
      </div>
    </div>
  );
};

// ─── Reset Password View (opened via #reset/:token link) ─────────────────────
const ResetPasswordView = ({ token, onDone }) => {
  const [password,  setPassword]  = useState('');
  const [confirm,   setConfirm]   = useState('');
  const [showPw,    setShowPw]    = useState(false);
  const [loading,   setLoading]   = useState(false);
  const [error,     setError]     = useState('');
  const [success,   setSuccess]   = useState(false);

  const checks = {
    len:   password.length >= 8,
    upper: /[A-Z]/.test(password),
    digit: /[0-9]/.test(password),
  };
  const strong = Object.values(checks).every(Boolean);
  const valid  = strong && password === confirm;

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!valid) return;
    setLoading(true); setError('');
    try {
      const r = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, password }),
      });
      const data = await r.json();
      if (!r.ok) { setError(data.error || 'เกิดข้อผิดพลาด'); return; }
      setSuccess(true);
    } catch {
      setError('ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้');
    } finally {
      setLoading(false);
    }
  };

  const bgStyle = {
    minHeight: '100vh', width: '100%',
    background: '#eeebe6',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: 24,
  };

  if (success) return (
    <div style={bgStyle}>
      <div style={{ width: '100%', maxWidth: 440, textAlign: 'center' }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <img src="assets/true-business-logo.png" alt="True Business" style={{ height: 34, marginBottom: 14 }}/>
          <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.02em', marginBottom: 4 }}>B2B Solutions</div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-3)' }}>Order Management</div>
        </div>
        <div style={{ background: 'var(--panel)', borderRadius: 10, padding: '40px', boxShadow: '0 4px 24px rgba(0,0,0,0.08)', textAlign: 'center' }}>
          <div style={{ fontSize: 40, marginBottom: 16 }}>✅</div>
          <h2 style={{ fontSize: 18, fontWeight: 700, margin: '0 0 8px', letterSpacing: '-0.02em' }}>ตั้งรหัสผ่านใหม่สำเร็จ</h2>
          <p style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 28 }}>คุณสามารถเข้าสู่ระบบด้วยรหัสผ่านใหม่ได้ทันที</p>
          <button onClick={onDone} style={{
            padding: '13px 32px', background: 'var(--true-red)', color: '#fff',
            border: 'none', borderRadius: 6, fontFamily: 'Kanit, sans-serif',
            fontSize: 15, fontWeight: 500, cursor: 'pointer',
          }}>
            ไปหน้า Login
          </button>
        </div>
        <div style={{ textAlign: 'center', marginTop: 20, fontSize: 12, color: 'var(--ink-3)' }}>
          © True Corporation · B2B Product development team
        </div>
      </div>
    </div>
  );

  return (
    <div style={bgStyle}>
      <div style={{ width: '100%', maxWidth: 440 }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <img src="assets/true-business-logo.png" alt="True Business" style={{ height: 34, marginBottom: 14 }}/>
          <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.02em', marginBottom: 4 }}>B2B Solutions</div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-3)' }}>Order Management</div>
        </div>

        <div style={{ background: 'var(--panel)', borderRadius: 10, padding: '36px 40px', boxShadow: '0 4px 24px rgba(0,0,0,0.08)' }}>
          <div style={{ marginBottom: 24 }}>
            <h1 style={{ fontSize: 20, fontWeight: 700, margin: '0 0 6px', letterSpacing: '-0.02em' }}>ตั้งรหัสผ่านใหม่</h1>
            <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>กรอกรหัสผ่านใหม่ของคุณ (อย่างน้อย 8 ตัวอักษร)</div>
          </div>

          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {error && (
              <div style={{ padding: '10px 14px', borderRadius: 4, background: 'var(--negative-bg)', border: '1px solid var(--negative)', fontSize: 12.5, color: 'var(--negative)', display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icon name="close" size={12}/>{error}
              </div>
            )}

            <div>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                รหัสผ่านใหม่
              </label>
              <div style={{ position: 'relative' }}>
                <input
                  type={showPw ? 'text' : 'password'}
                  value={password}
                  onChange={e => { setPassword(e.target.value); setError(''); }}
                  autoFocus
                  style={{ ...loginInputStyle, paddingRight: 42 }}
                />
                <button type="button" onClick={() => setShowPw(v => !v)} style={{
                  position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
                  background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 4, display: 'inline-flex',
                }}>
                  <Icon name={showPw ? 'eye' : 'eyeOff'} size={15}/>
                </button>
              </div>
              {password.length > 0 && (
                <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 3 }}>
                  {[['len','อย่างน้อย 8 ตัวอักษร'],['upper','มีตัวพิมพ์ใหญ่ (A-Z)'],['digit','มีตัวเลข (0-9)']].map(([k,label]) => (
                    <div key={k} style={{ fontSize: 11.5, color: checks[k] ? 'var(--positive)' : 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 5 }}>
                      <span>{checks[k] ? '✓' : '·'}</span>{label}
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                ยืนยันรหัสผ่าน
              </label>
              <input
                type={showPw ? 'text' : 'password'}
                value={confirm}
                onChange={e => { setConfirm(e.target.value); setError(''); }}
                style={{ ...loginInputStyle, border: confirm && password !== confirm ? '1.5px solid var(--negative)' : 'none' }}
              />
              {confirm && password !== confirm && (
                <div style={{ marginTop: 6, fontSize: 11.5, color: 'var(--negative)' }}>รหัสผ่านไม่ตรงกัน</div>
              )}
            </div>

            <button type="submit" disabled={!valid || loading} style={{
              marginTop: 6, padding: '13px 0',
              background: !valid || loading ? 'var(--ink-4)' : 'var(--true-red)',
              color: '#fff', border: 'none', borderRadius: 6,
              fontFamily: 'Kanit, sans-serif', fontSize: 15, fontWeight: 500,
              cursor: !valid || loading ? 'not-allowed' : 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
              {loading ? (
                <><span style={{ display: 'inline-block', width: 14, height: 14, border: '2px solid rgba(255,255,255,0.4)', borderTopColor: '#fff', borderRadius: '50%', animation: 'spin 0.7s linear infinite' }}/> กำลังบันทึก…</>
              ) : 'ยืนยันรหัสผ่านใหม่'}
            </button>
          </form>
        </div>

        <div style={{ textAlign: 'center', marginTop: 20, fontSize: 12, color: 'var(--ink-3)' }}>
          © True Corporation · B2B Product development team
        </div>
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
};

Object.assign(window, { LoginView, ForgotPasswordView, ResetPasswordView });
