// Standalone entry for the Admin Back-office — includes Login gate.
//
// Whitelisted admin accounts. Each entry has a user profile that gets stored
// in sessionStorage on successful login and feeds the RBAC + activity logger.
const ADMIN_ACCOUNTS = [
  {
    email:    'kaidaocreative@gmail.com',
    password: '210247',
    user: {
      id:    'user-super-001',
      name:  'Super Admin',
      role:  'super_admin',
      assigned_branch_id: null,
    },
  },
  {
    email:    'adminclover@gmail.com',
    password: '123456',
    user: {
      id:    'user-admin-001',
      name:  'Admin Clover',
      role:  'admin',
      assigned_branch_id: null,
    },
  },
];

function findAdminAccount(email, password) {
  const e = String(email || '').trim().toLowerCase();
  return ADMIN_ACCOUNTS.find(a => a.email === e && a.password === password) || null;
}

// Kept for back-compat with code that references the legacy constant.
const ADMIN_EMAIL    = ADMIN_ACCOUNTS[0].email;
const ADMIN_PASSWORD = ADMIN_ACCOUNTS[0].password;

function AdminLogin({ onAuth }) {
  const [email,    setEmail]    = useState('');
  const [password, setPassword] = useState('');
  const [showPw,   setShowPw]   = useState(false);
  const [error,    setError]    = useState(null);
  const [loading,  setLoading]  = useState(false);

  const C = {
    cloverDeep: '#122A20', clover: '#1F4435', cloverMid: '#2E5A47', cloverSoft: '#E6EEE8',
    gold: '#C9A66B', goldDeep: '#A8854A', goldSoft: '#F1E6CE',
    bone: '#F6F3EC', line: '#E6E2D7', line2: '#D5CFBE',
    mute: '#7A7A72', ink: '#14140F', ink2: '#2A2A24',
  };

  const submit = () => {
    if (!email.trim() || !password) {
      setError('กรุณากรอกอีเมลและรหัสผ่าน');
      return;
    }
    setError(null);
    setLoading(true);
    setTimeout(() => {
      const account = findAdminAccount(email, password);
      if (account) {
        const profile = { ...account.user, email: account.email };
        sessionStorage.setItem('clover-admin-authed', '1');
        // Seed the current-user blob so RBAC + activity logger know who we are
        sessionStorage.setItem('clover-current-user', JSON.stringify(profile));
        // Remember the ORIGINAL login role so the role-preview switcher
        // (which is only shown to super_admin) doesn't disappear when the
        // admin previews as a lower role.
        sessionStorage.setItem('clover-login-role', profile.role);
        // Activity log (fire-and-forget)
        fetch('/api/logs/create', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'x-user-id':   profile.id,
            'x-user-name': profile.name,
            'x-user-role': profile.role,
          },
          body: JSON.stringify({
            action_type: 'login_success',
            action_label: `Admin login: ${profile.email} (${profile.role})`,
          }),
        }).catch(() => {});
        onAuth();
      } else {
        fetch('/api/logs/create', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            action_type: 'login_failed',
            action_label: `Failed login attempt: ${email.trim().toLowerCase()}`,
          }),
        }).catch(() => {});
        setError('อีเมลหรือรหัสผ่านไม่ถูกต้อง');
        setLoading(false);
      }
    }, 500);
  };

  const handleKeyDown = (e) => { if (e.key === 'Enter') submit(); };

  const inputStyle = {
    width: '100%', padding: '11px 14px', borderRadius: 10,
    border: '1.5px solid ' + C.line2, background: C.bone,
    fontSize: 13.5, color: C.ink, outline: 'none', fontFamily: 'inherit',
    transition: 'border-color .15s',
  };

  return (
    <div className="fade-in" style={{
      width: '100vw', height: '100vh',
      background: C.cloverDeep,
      backgroundImage: 'repeating-linear-gradient(135deg, rgba(255,255,255,0.035) 0 1px, transparent 1px 9px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
      fontFamily: 'DM Sans, IBM Plex Sans Thai, sans-serif',
    }}>
      <div className="slide-up" style={{
        width: '100%', maxWidth: 400,
        background: '#fff', borderRadius: 22, padding: '40px 36px 32px',
        boxShadow: '0 40px 100px rgba(0,0,0,0.5), 0 8px 32px rgba(0,0,0,0.2)',
      }}>
        {/* Logo */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 30 }}>
          <CloverMark size={38} color={C.clover} />
          <div>
            <div className="serif" style={{ fontSize: 21, color: C.clover, letterSpacing: -0.3 }}>Clover Clinic</div>
            <div style={{ fontSize: 10, color: C.mute, letterSpacing: 1.8, textTransform: 'uppercase' }}>Admin Console</div>
          </div>
        </div>

        <div style={{ fontSize: 19, fontWeight: 700, color: C.ink, marginBottom: 4 }}>Sign in</div>
        <div style={{ fontSize: 13, color: C.mute, marginBottom: 26 }}>เข้าสู่ระบบจัดการคลินิก</div>

        {/* Email */}
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: C.mute, letterSpacing: 0.7, textTransform: 'uppercase', marginBottom: 6 }}>Email</div>
          <input
            type="email" placeholder="you@example.com"
            value={email} onChange={(e) => setEmail(e.target.value)}
            onKeyDown={handleKeyDown} autoComplete="email"
            style={inputStyle}
            onFocus={(e)  => (e.target.style.borderColor = C.clover)}
            onBlur={(e)   => (e.target.style.borderColor = C.line2)}
          />
        </div>

        {/* Password */}
        <div style={{ marginBottom: 22 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: C.mute, letterSpacing: 0.7, textTransform: 'uppercase', marginBottom: 6 }}>Password</div>
          <div style={{ position: 'relative' }}>
            <input
              type={showPw ? 'text' : 'password'} placeholder="••••••••"
              value={password} onChange={(e) => setPassword(e.target.value)}
              onKeyDown={handleKeyDown} autoComplete="current-password"
              style={{ ...inputStyle, paddingRight: 56 }}
              onFocus={(e)  => (e.target.style.borderColor = C.clover)}
              onBlur={(e)   => (e.target.style.borderColor = C.line2)}
            />
            <button type="button" onClick={() => setShowPw(v => !v)} style={{
              position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
              background: 'none', border: 'none', cursor: 'pointer',
              fontSize: 10.5, fontWeight: 700, color: C.mute, fontFamily: 'inherit',
              letterSpacing: 0.5, textTransform: 'uppercase', padding: '4px 6px',
            }}>{showPw ? 'HIDE' : 'SHOW'}</button>
          </div>
        </div>

        {/* Error */}
        {error && (
          <div className="fade-in" style={{
            marginBottom: 16, padding: '10px 14px', borderRadius: 8,
            background: '#FEF0EF', border: '1px solid #F5C5C2',
            fontSize: 12.5, color: '#B5453A', whiteSpace: 'pre-line',
          }}>{error}</div>
        )}

        {/* Submit */}
        <button type="button" onClick={submit} disabled={loading} style={{
          width: '100%', padding: 13, borderRadius: 11, border: 'none',
          background: loading ? C.cloverMid : C.clover, color: '#fff',
          fontSize: 14, fontWeight: 700, cursor: loading ? 'default' : 'pointer',
          transition: 'background .15s', fontFamily: 'inherit', letterSpacing: 0.2,
        }}>{loading ? 'กำลังเข้าสู่ระบบ…' : 'Sign in →'}</button>
      </div>
    </div>
  );
}

function AdminStandalone() {
  const [authed, setAuthed] = useState(
    () => sessionStorage.getItem('clover-admin-authed') === '1'
  );

  const handleSignOut = () => {
    // Best-effort logout log
    try {
      const u = JSON.parse(sessionStorage.getItem('clover-current-user') || '{}');
      fetch('/api/logs/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-user-id':   u.id   || '',
          'x-user-name': u.name || '',
          'x-user-role': u.role || '',
        },
        body: JSON.stringify({ action_type: 'logout', action_label: 'Signed out' }),
      }).catch(() => {});
    } catch {}
    sessionStorage.removeItem('clover-admin-authed');
    sessionStorage.removeItem('clover-admin-token');
    sessionStorage.removeItem('clover-admin-email');
    sessionStorage.removeItem('clover-current-user');
    sessionStorage.removeItem('clover-login-role');
    setAuthed(false);
  };

  if (!authed) return <AdminLogin onAuth={() => setAuthed(true)} />;

  return (
    <I18nProvider>
      <div className="admin-stage">
        <AdminApp initialView="customers" initialRole="super_admin" onSignOut={handleSignOut} />
      </div>
    </I18nProvider>
  );
}

Object.assign(window, { AdminStandalone });

ReactDOM.createRoot(document.getElementById('root')).render(<AdminStandalone />);
