/* Shared auth shell — centered card on a light canvas with a minimal top bar.
   `mode` = 'login' | 'signup'. Visual only; submit routes to the platform. */

function Field({ label, type = 'text', placeholder, autoComplete, suffix, value, onChange, invalid }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <span style={{ fontSize: 'var(--text-sm)', fontWeight: 500, color: 'var(--text-primary)' }}>{label}</span>
      <span style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
        <input type={type} placeholder={placeholder} autoComplete={autoComplete} value={value} onChange={onChange} className="bm-input"
          style={{ width: '100%', height: 48, padding: suffix ? '0 48px 0 14px' : '0 14px', fontSize: 'var(--text-base)', fontFamily: 'var(--font-sans)', color: 'var(--text-primary)', background: 'var(--neutral-25)', border: `1px solid ${invalid ? 'var(--red-500, #e5484d)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-md)', outline: 'none', transition: 'border-color 160ms, box-shadow 160ms, background 160ms' }} />
        {suffix}
      </span>
    </label>
  );
}

function Auth({ mode }) {
  const { Button, Checkbox } = window.BunkermeDesignSystem_9754f2;
  const vw = useVW();
  const isMobile = vw <= 560;
  const isSignup = mode === 'signup';
  const [showPw, setShowPw] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const dashboard = '../Customer%20dashboard/Customer%20Dashboard.html#app';

  const go = async (e) => {
    e.preventDefault();
    if (isSignup) { window.location.href = dashboard; return; }
    setErr('');
    const A = window.BunkermeAuth;
    if (!email.trim()) { setErr('Please enter your email.'); return; }
    if (!A) { window.location.href = dashboard; return; } // graceful fallback if store didn't load
    setBusy(true);
    const res = await A.verify(email, pw);
    setBusy(false);
    if (!res.ok && res.reason === 'no-user') { setErr("This email isn't registered. Please sign up first."); return; }
    if (!res.ok) { setErr('Invalid email or password.'); return; }
    A.setSession(email);
    window.location.href = dashboard;
  };

  const pwToggle = (
    <button type="button" onClick={() => setShowPw((s) => !s)} aria-label="Toggle password visibility"
      style={{ position: 'absolute', right: 6, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 36, height: 36, border: 'none', background: 'transparent', color: 'var(--text-tertiary)', cursor: 'pointer', borderRadius: 'var(--radius-sm)' }}>
      <Icon name={showPw ? 'eye-off' : 'eye'} size={18} color="currentColor" />
    </button>
  );

  return (
    <div style={{ position: 'relative', minHeight: '100vh', display: 'flex', flexDirection: 'column', background: 'var(--surface-page)' }}>
      {/* subtle top wash */}
      <div aria-hidden="true" style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 360, pointerEvents: 'none', background: 'radial-gradient(720px 320px at 50% -10%, rgba(12,41,241,0.07), transparent 70%)' }} />

      {/* top bar */}
      <header style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '26px 32px' }}>
        <a href="index.html" aria-label="bunkerme home" style={{ display: 'inline-flex' }}><Logo size={28} /></a>
        <a href={isSignup ? 'login.html' : 'signup.html'} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 'var(--text-sm)', fontWeight: 600, color: 'var(--text-secondary)', whiteSpace: 'nowrap' }}>
          {isSignup ? 'Log in' : 'Open account'} <Icon name="chevron-right" size={16} color="currentColor" />
        </a>
      </header>

      {/* centered card */}
      <div style={{ position: 'relative', flex: 1, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '40px 24px 72px' }}>
        <div style={{ width: '100%', maxWidth: 452, background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-2xl)', boxShadow: 'var(--shadow-lg)', padding: '40px 40px 36px' }}>
          <h1 style={{ fontSize: 'var(--text-h2)', fontWeight: 600, letterSpacing: 'var(--tracking-tight)', marginBottom: 6 }}>
            {isSignup ? 'Open your account' : 'Log in'}
          </h1>
          <p style={{ fontSize: 'var(--text-base)', color: 'var(--text-secondary)', marginBottom: 30 }}>
            {isSignup ? 'Start ordering bunkers and unlock flexible credit.' : 'Welcome back. Pick up where you left off.'}
          </p>

          {!isSignup && err && (
            <div role="alert" style={{ display: 'flex', alignItems: 'flex-start', gap: 8, background: 'var(--danger-subtle, #fdecec)', border: '1px solid var(--red-200, #f3c4c6)', color: 'var(--red-600, #c02a2a)', borderRadius: 'var(--radius-md)', padding: '10px 12px', fontSize: 'var(--text-sm)', lineHeight: 'var(--leading-normal)', marginBottom: 20 }}>
              <span>{err}</span>
            </div>
          )}

          <form onSubmit={go} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            {isSignup && (
              <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
                <Field label="Full name" placeholder="Roberto Costa" autoComplete="name" />
                <Field label="Company" placeholder="Sogdia Waters" autoComplete="organization" />
              </div>
            )}

            <Field label="Email" type="email" placeholder="you@fleet.com" autoComplete="email"
              value={isSignup ? undefined : email} onChange={isSignup ? undefined : (e) => { setEmail(e.target.value); if (err) setErr(''); }}
              invalid={!isSignup && !!err} />

            <div>
              <Field label="Password" type={showPw ? 'text' : 'password'}
                placeholder={isSignup ? 'At least 8 characters' : '••••••••'}
                autoComplete={isSignup ? 'new-password' : 'current-password'} suffix={pwToggle}
                value={isSignup ? undefined : pw} onChange={isSignup ? undefined : (e) => { setPw(e.target.value); if (err) setErr(''); }}
                invalid={!isSignup && !!err} />
              {!isSignup && (
                <div style={{ marginTop: 10 }}>
                  <a href="forgot-password.html" style={{ fontSize: 'var(--text-sm)', color: 'var(--blue-600)', fontWeight: 500 }}>Forgot password?</a>
                </div>
              )}
            </div>

            <div style={{ marginTop: 2 }}>
              <Checkbox label={isSignup
                ? <span style={{ fontSize: 'var(--text-sm)', color: 'var(--text-secondary)' }}>I agree to the <a href="#" style={{ color: 'var(--blue-600)' }}>Terms</a> and <a href="#" style={{ color: 'var(--blue-600)' }}>Privacy Policy</a>.</span>
                : <span style={{ fontSize: 'var(--text-sm)', color: 'var(--text-secondary)' }}>Keep me signed in</span>} />
            </div>

            <Button variant="primary" size="lg" type="submit" fullWidth disabled={busy} iconRight={<Icon name="arrow-right" size={18} color="#fff" />}>
              {isSignup ? 'Create account' : (busy ? 'Logging in…' : 'Log in')}
            </Button>
          </form>

          <div style={{ marginTop: 4 }} />
        </div>
      </div>

      <style>{`
        .bm-input:focus{ border-color: var(--border-focus); box-shadow: var(--ring-accent); background: var(--surface-card); }
        .bm-input::placeholder{ color: var(--text-tertiary); }
        .bm-sso{ display:flex; align-items:center; justify-content:center; gap:10px; height:48px; width:100%;
          font-size: var(--text-sm); font-weight:600; font-family: var(--font-sans); color: var(--text-primary);
          background: var(--surface-card); border:1px solid var(--border-strong); border-radius: var(--radius-md);
          cursor:pointer; transition: background 160ms, border-color 160ms; }
        .bm-sso:hover{ background: var(--surface-hover); border-color: var(--neutral-400); }
      `}</style>
    </div>
  );
}

Object.assign(window, { Auth });
