/* ClinicFlow AI — Authentication: LoginPage + ClinicPickerPage */

const { useState: _as, useEffect: _ae, useRef: _ar } = React;

// Clinics this user has access to (in real life: returned by the auth backend)
const CLINICS = [
  {
    id: 'apollo-family',
    code: 'AF',
    name: 'Apollo Family Clinic',
    city: 'Civil Lines, Raipur · CG',
    role: 'Owner',
    bg: 'linear-gradient(135deg, #4F46E5, #7C3AED)',
    stats: { patients: 1284, doctors: 4 },
  },
  {
    id: 'wellcare-multi',
    code: 'WC',
    name: 'WellCare Multispecialty',
    city: 'Vyapar Vihar, Bilaspur · CG',
    role: 'Doctor',
    bg: 'linear-gradient(135deg, #0EA5E9, #6366F1)',
    stats: { patients: 842, doctors: 6 },
  },
  {
    id: 'newsight-eye',
    code: 'NS',
    name: 'NewSight Eye Centre',
    city: 'Vidhan Sabha Rd, Durg · CG',
    role: 'Doctor',
    bg: 'linear-gradient(135deg, #10B981, #14B8A6)',
    stats: { patients: 478, doctors: 2 },
  },
  {
    id: 'metro-pediatric',
    code: 'MP',
    name: 'Metro Pediatric Hub',
    city: 'Shankar Nagar, Raipur · CG',
    role: 'Pending invite',
    bg: 'linear-gradient(135deg, #F59E0B, #EC4899)',
    disabled: true,
  },
];

const DEFAULT_CLINIC_ID = 'apollo-family';
const DEMO_EMAIL = 'vimal.rao@apollofamily.in';
const DEMO_PASSWORD = 'clinicflow';

// ---------------- LoginPage ----------------
function LoginPage({ onLogin }) {
  const [email, setEmail] = _as('');
  const [password, setPassword] = _as('');
  const [error, setError] = _as(null);
  const [loading, setLoading] = _as(false);
  const [showPw, setShowPw] = _as(false);
  const [remember, setRemember] = _as(true);
  const emailRef = _ar(null);

  _ae(() => { emailRef.current?.focus(); }, []);

  const fillDemo = () => {
    setEmail(DEMO_EMAIL);
    setPassword(DEMO_PASSWORD);
    setError(null);
  };

  const submit = (e) => {
    e?.preventDefault?.();
    setError(null);
    if (!email || !password) {
      setError('Email and password are required.');
      return;
    }
    if (!/\S+@\S+\.\S+/.test(email)) {
      setError('Enter a valid email address.');
      return;
    }
    setLoading(true);
    setTimeout(() => {
      if (email.trim().toLowerCase() === DEMO_EMAIL && password === DEMO_PASSWORD) {
        const user = { name: 'Dr. Vimal Rao', email: DEMO_EMAIL, initials: 'VR' };
        onLogin?.(user);
      } else {
        // For demo: accept any email/password but require they're set
        const initials = email[0].toUpperCase() + (email[1] || '').toUpperCase();
        const user = { name: 'Demo User', email, initials };
        onLogin?.(user);
      }
      setLoading(false);
    }, 700);
  };

  return (
    <div className="auth-shell" data-screen-label="Login">
      {/* Brand panel */}
      <div className="auth-brand">
        <div className="auth-brand-top">
          <OrbisMark size={32}/>
          <div className="wm">
            ClinicFlow
            <small>AI · by Orbis Systems</small>
          </div>
        </div>

        <div className="auth-brand-body">
          <span className="auth-eyebrow">For clinics across India</span>
          <h1 className="auth-headline">
            AI follow-ups that <span className="grad">retain patients</span>, automatically.
          </h1>
          <p className="auth-sub">
            Sign in to your ClinicFlow workspace to manage appointments,
            run the AI follow-up agent, and stay on top of every patient
            conversation — all from one secure dashboard.
          </p>

          <div className="auth-stats">
            <div className="auth-stat">
              <span className="auth-stat-value">99.9%</span>
              <span className="auth-stat-label">Uptime SLA</span>
            </div>
            <div className="auth-stat">
              <span className="auth-stat-value">142+</span>
              <span className="auth-stat-label">Clinics live</span>
            </div>
            <div className="auth-stat">
              <span className="auth-stat-value">2.4M</span>
              <span className="auth-stat-label">Messages sent</span>
            </div>
          </div>
        </div>

        <div className="auth-brand-foot">
          <span>© 2026 Orbis Systems · Raipur, CG</span>
          <a href="#" onClick={(e) => { e.preventDefault(); window.toast?.('Status page (demo)', { type: 'info' }); }}>
            All systems operational
          </a>
        </div>
      </div>

      {/* Form panel */}
      <form className="auth-form-side" onSubmit={submit}>
        <div className="auth-form-top">
          New to ClinicFlow?&nbsp;
          <a href="#" onClick={(e) => { e.preventDefault(); window.toast?.('Contact sales: hello@orbissystems.in', { type: 'info' }); }}>
            Request a demo
          </a>
        </div>

        <div className="auth-form-body">
          <h1>Sign in to your workspace</h1>
          <p className="lead">Use your work email to access the clinics you're a member of.</p>

          <div className="demo-creds">
            <I.sparkles size={14} stroke="#7C3AED"/>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, color: 'var(--purple-700)' }}>Demo account</div>
              <div style={{ marginTop: 4, lineHeight: 1.5 }}>
                <div className="demo-mono">{DEMO_EMAIL}</div>
                <div className="demo-mono">password: {DEMO_PASSWORD}</div>
              </div>
            </div>
            <button type="button" onClick={fillDemo}>Use demo</button>
          </div>

          <div className="auth-field">
            <label htmlFor="email">Work email</label>
            <input id="email" ref={emailRef} className={`auth-input ${error ? 'invalid' : ''}`}
              type="email" autoComplete="username"
              placeholder="you@clinic.com"
              value={email} onChange={(e) => { setEmail(e.target.value); setError(null); }} />
          </div>

          <div className="auth-field">
            <label htmlFor="pw">
              Password
              <a href="#" onClick={(e) => { e.preventDefault(); window.toast?.('Reset link sent (demo)', { type: 'success' }); }}>
                Forgot password?
              </a>
            </label>
            <div style={{ position: 'relative' }}>
              <input id="pw" className={`auth-input ${error ? 'invalid' : ''}`}
                type={showPw ? 'text' : 'password'} autoComplete="current-password"
                placeholder="••••••••"
                value={password} onChange={(e) => { setPassword(e.target.value); setError(null); }}
                style={{ paddingRight: 80 }} />
              <button type="button" onClick={() => setShowPw(s => !s)}
                style={{
                  position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)',
                  background: 'transparent', border: 'none', color: 'var(--gray-500)',
                  fontSize: 12, fontWeight: 600, cursor: 'pointer', padding: '6px 8px',
                  borderRadius: 6,
                }}>
                {showPw ? 'Hide' : 'Show'}
              </button>
            </div>
          </div>

          {error && (
            <div style={{
              background: 'var(--danger-soft)', color: 'var(--danger)',
              border: '1px solid #FECACA', borderRadius: 8,
              padding: '8px 12px', fontSize: 12, fontWeight: 500,
              marginBottom: 14, display: 'flex', alignItems: 'center', gap: 8,
            }}>
              <I.x size={14} sw={2.5} />{error}
            </div>
          )}

          <label className="auth-checkbox">
            <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
            Keep me signed in on this device
          </label>

          <button className="auth-submit" type="submit" disabled={loading}>
            {loading ? (
              <>
                <I.refresh size={14} style={{ animation: 'spin 0.9s linear infinite' }}/>
                Signing in...
              </>
            ) : (
              <>Sign in <I.arrowRight size={14}/></>
            )}
          </button>

          <div className="auth-sep">or</div>

          <button className="auth-sso" type="button"
            onClick={() => window.toast?.('SSO redirect (demo)', { type: 'info' })}>
            <svg width="16" height="16" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
            Continue with Google Workspace
          </button>

          <button className="auth-sso" type="button" style={{ marginTop: 8 }}
            onClick={() => window.toast?.('Magic link sent to your email (demo)', { type: 'success' })}>
            <I.mail size={15}/>Email me a magic link
          </button>
        </div>

        <div className="auth-form-foot">
          By continuing you agree to ClinicFlow's <a href="#" onClick={(e) => e.preventDefault()}>Terms</a> and <a href="#" onClick={(e) => e.preventDefault()}>Privacy Policy</a>.
        </div>
      </form>
    </div>
  );
}

// ---------------- ClinicPickerPage ----------------
function ClinicPickerPage({ user, onPick, onSignOut }) {
  const pickerClinics = CLINICS;

  return (
    <div className="picker-shell" data-screen-label="Clinic picker">
      <div className="picker-top">
        <div className="flex items-center gap-3">
          <OrbisMark size={28}/>
          <div className="font-display" style={{ fontWeight: 700, color: 'var(--ink)', fontSize: 15, letterSpacing: '-0.01em' }}>
            ClinicFlow <span style={{ fontWeight: 400, color: 'var(--gray-400)' }}>· workspace</span>
          </div>
        </div>
        <div className="who">
          <span className="topbar-avatar" style={{ width: 28, height: 28, fontSize: 11 }}>{user.initials}</span>
          <span>{user.name}</span>
          <button onClick={onSignOut} style={{
            background: 'transparent', border: 'none', color: 'var(--gray-500)',
            fontWeight: 600, fontSize: 12, cursor: 'pointer', padding: '4px 8px',
            borderRadius: 6, fontFamily: 'inherit',
          }}>
            Sign out
          </button>
        </div>
      </div>

      <div className="picker-body">
        <div className="picker-card">
          <h2>Choose a workspace</h2>
          <p>You're a member of {pickerClinics.filter(c => !c.disabled).length} clinics. Pick one to open its dashboard.</p>

          {pickerClinics.map(c => (
            <div key={c.id}
              className={`clinic-row ${c.disabled ? 'disabled' : ''}`}
              onClick={() => !c.disabled && onPick(c)}>
              <span className="clinic-mark" style={{ background: c.bg }}>{c.code}</span>
              <div className="meta">
                <div className="name">{c.name}</div>
                <div className="loc">
                  {c.city}
                  {!c.disabled && c.stats && (
                    <>
                      <span style={{ color: 'var(--gray-300)' }}>·</span>
                      <span className="mono" style={{ fontSize: 11 }}>{c.stats.patients.toLocaleString()} patients</span>
                    </>
                  )}
                </div>
              </div>
              <span className="role">{c.role}</span>
              <I.chevR size={16} className="chev" />
            </div>
          ))}

          <div className="picker-foot">
            <span>Signed in as <span className="mono">{user.email}</span></span>
            <a href="#" onClick={(e) => { e.preventDefault(); window.toast?.('Setup wizard coming soon', { type: 'info' }); }}>
              + Add another clinic
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginPage, ClinicPickerPage, CLINICS, DEFAULT_CLINIC_ID });
