// portal-auth.jsx — Login page (shown when no user is signed in)

function LoginPage() {
  const users = useStore(s => s.users);
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [forgot, setForgot] = React.useState(false);

  async function submit(e) {
    if (e) e.preventDefault();
    setError('');
    if (!email || !password) { setError('Email and password required.'); return; }
    setLoading(true);
    try {
      const res = await Store.login(email, password);
      if (!res.ok) { setError(res.error); setLoading(false); }
      // on success the App re-renders to the portal
    } catch (err) {
      setError(err.message || 'Login failed');
      setLoading(false);
    }
  }

  function quickFill(u) {
    setEmail(u.email);
    setPassword(u.password);
    setError('');
  }

  return (
    <div className="pt" style={{
      minHeight: '100vh',
      display: 'flex',
      background: T.bg,
      backgroundImage: `
        radial-gradient(ellipse 800px 600px at 18% 15%, rgba(200,162,90,0.10), transparent 70%),
        radial-gradient(ellipse 700px 500px at 90% 90%, rgba(124,158,255,0.06), transparent 60%)`,
    }}>
      {/* Left — brand panel */}
      <div style={{
        flex: '0 0 46%',
        padding: '36px 48px',
        display: 'flex',
        flexDirection: 'column',
        gap: 28,
        background: 'linear-gradient(180deg, rgba(11,22,38,0.6), rgba(10,20,36,0.9))',
        borderRight: '1px solid ' + T.borderSoft,
        overflowY: 'auto',
      }}>
        <div className="pt-row" style={{ gap: 14, alignItems: 'center' }}>
          <Mark size={36} />
          <div className="pt-col" style={{ lineHeight: 1.05 }}>
            <div className="pt-display" style={{ fontSize: 26, fontWeight: 600 }}>Nepalirika</div>
            <div className="pt-eyebrow">Membership · CRM</div>
          </div>
        </div>

        <div className="pt-col" style={{ gap: 14, maxWidth: 460 }}>
          <h1 className="pt-display" style={{ fontSize: 48, lineHeight: 1.02, fontWeight: 500, letterSpacing: '-0.02em' }}>
            Welcome to the<br />
            <span style={{ color: T.gold, fontStyle: 'italic' }}>members' desk.</span>
          </h1>
          <div className="pt-mute" style={{ fontSize: 14, lineHeight: 1.6 }}>
            One portal for both properties. Sign in to enroll members, redeem benefits, and post member bills from Aegis PMS.
          </div>
          <div className="pt-row" style={{ gap: 10, marginTop: 2 }}>
            <Badge variant="gold">◆ Biratchowk</Badge>
            <Badge variant="gold">◆ Damak</Badge>
          </div>
        </div>

        <div className="pt-faint" style={{ fontSize: 11, marginTop: 'auto', lineHeight: 1.6 }}>
          Don't have an account? Ask your Super Admin to create one for you.<br />
          For password issues, use "Forgot password" on the right.
        </div>
      </div>

      {/* Right — login form */}
      <div style={{
        flex: 1,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '52px',
      }}>
        <form onSubmit={submit} className="pt-col" style={{ width: '100%', maxWidth: 360, gap: 16 }}>
          <div className="pt-col" style={{ gap: 6, marginBottom: 8 }}>
            <h2 className="pt-h1" style={{ fontSize: 34 }}>Staff sign in</h2>
            <div className="pt-mute" style={{ fontSize: 14 }}>Use your hotel email & password.</div>
          </div>

          <Input label="Email" value={email} onChange={setEmail} placeholder="name@nepalirika.com" type="email" />
          <Input label="Password" value={password} onChange={setPassword} type="password" placeholder="••••••••" />

          {error && (
            <div style={{
              padding: '10px 12px',
              background: 'rgba(239,68,68,0.08)',
              border: '1px solid rgba(239,68,68,0.3)',
              borderRadius: 8,
              color: '#fca5a5',
              fontSize: 13,
            }}>⚠ {error}</div>
          )}

          <div className="pt-row" style={{ justifyContent: 'space-between', fontSize: 12 }}>
            <label className="pt-row pt-mute" style={{ gap: 6, cursor: 'pointer' }}>
              <input type="checkbox" defaultChecked /> Remember this device
            </label>
            <span className="pt-link" onClick={() => setForgot(true)}>Forgot password?</span>
          </div>

          <Button type="submit" variant="gold" size="lg" disabled={loading}
            style={{ width: '100%', marginTop: 4 }}>
            {loading ? 'Signing in…' : 'Sign in →'}
          </Button>

          <div className="pt-faint" style={{ fontSize: 12, textAlign: 'center', marginTop: 10 }}>
            v0.4 · internal use only · need an account? <span className="pt-link">ask your manager</span>
          </div>
        </form>
      </div>

      <ForgotPasswordModal open={forgot} onClose={() => setForgot(false)} users={users} />
    </div>
  );
}

function ForgotPasswordModal({ open, onClose, users }) {
  const [email, setEmail] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);
  React.useEffect(() => { if (open) { setEmail(''); setSubmitted(false); } }, [open]);
  const user = users.find(u => u.email.toLowerCase() === email.toLowerCase().trim());
  const supers = users.filter(u => u.role === 'Super Admin');
  return (
    <Modal open={open} title="Forgot password" onClose={onClose} width={460} footer={
      <>
        <Button variant="ghost" onClick={onClose}>{submitted ? 'Done' : 'Cancel'}</Button>
        {!submitted && <Button variant="gold" onClick={() => setSubmitted(true)} disabled={!email.trim()}>Send request</Button>}
      </>
    }>
      {!submitted ? (
        <>
          <div className="pt-mute" style={{ fontSize: 13, marginBottom: 14 }}>
            Enter your staff email. Your Super Admin will be notified and can reset your password from the Staff page. They'll hand you the new password securely.
          </div>
          <Input label="Staff email" value={email} onChange={setEmail} placeholder="name@nepalirika.com" type="email" />
          {email.trim() && (
            <div className="pt-faint" style={{ fontSize: 12, marginTop: 10 }}>
              {user ? <span>✓ found · <b>{user.name}</b> ({user.role})</span> : <span>No account with that email yet — the request will still be sent for review.</span>}
            </div>
          )}
        </>
      ) : (
        <>
          <div style={{ padding: 14, background: 'rgba(74,222,128,0.08)', border: '1px solid rgba(74,222,128,0.3)', borderRadius: 8, color: T.good, fontSize: 13, marginBottom: 14 }}>
            ✓ Request sent. A Super Admin will reset your password and hand you the new one.
          </div>
          <div className="pt-mute" style={{ fontSize: 13 }}>
            Reach out to one of:
          </div>
          <div className="pt-col" style={{ gap: 6, marginTop: 8 }}>
            {supers.map(u => (
              <div key={u.id} style={{ padding: '8px 12px', background: 'rgba(255,255,255,0.03)', border: '1px solid ' + T.borderSoft, borderRadius: 8 }}>
                <div style={{ fontWeight: 600 }}>{u.name}</div>
                <div className="pt-faint pt-num" style={{ fontSize: 12 }}>{u.email}</div>
              </div>
            ))}
          </div>
        </>
      )}
    </Modal>
  );
}

Object.assign(window, { LoginPage });
