// Sign-in modal — placeholder gateway for customer operators.
// No real auth: posting the form shows a polite "access by invitation" message.
// Opened via window.dispatchEvent(new Event('sign-in:open')) — any nav link
// can fire that event.

function SignInModal() {
  const [open, setOpen] = React.useState(false);
  const [state, setState] = React.useState('idle'); // idle | submitting | denied
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const emailRef = React.useRef(null);

  // Listen for open events
  React.useEffect(() => {
    const handler = () => { setOpen(true); setState('idle'); };
    window.addEventListener('sign-in:open', handler);
    return () => window.removeEventListener('sign-in:open', handler);
  }, []);

  // Esc closes
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  // Focus email on open
  React.useEffect(() => {
    if (open) setTimeout(() => emailRef.current?.focus(), 80);
  }, [open]);

  const submit = (e) => {
    e.preventDefault();
    if (!email.trim()) return;
    setState('submitting');
    // Brief delay so the action feels real, then deny.
    setTimeout(() => setState('denied'), 900);
  };

  if (!open) return null;

  return (
    <>
      <div onClick={() => setOpen(false)} style={{
        position: 'fixed', inset: 0,
        background: 'rgba(0, 0, 0, 0.55)',
        backdropFilter: 'blur(3px)',
        WebkitBackdropFilter: 'blur(3px)',
        zIndex: 998,
        animation: 'signin-fade 240ms var(--ease-out)',
      }}/>

      <div role="dialog" aria-modal="true" aria-label="Sign in to 8/0" style={{
        position: 'fixed',
        top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        width: 'min(440px, 92vw)',
        background: 'var(--ebz-ink-700)',
        border: '1px solid var(--border-2)',
        borderRadius: 6,
        boxShadow: '0 32px 64px -16px rgba(0,0,0,0.65)',
        zIndex: 999,
        display: 'flex', flexDirection: 'column',
        overflow: 'hidden',
        animation: 'signin-rise 280ms var(--ease-out)',
      }}>
        {/* Head */}
        <div style={{
          padding: '20px 22px 0',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <img src="/assets/logo-mark.svg" width="28" height="28" alt=""/>
            <span className="wordmark" style={{ fontSize: 17 }}>
              <span style={{ color: 'var(--accent)' }}>Eight</span>
              <span style={{ color: 'var(--fg-1)' }}>by</span>
              <span style={{ color: 'var(--accent)' }}>Zero</span>
            </span>
          </div>
          <button onClick={() => setOpen(false)} aria-label="Close" style={{
            background: 'transparent', border: 'none', color: 'var(--fg-3)',
            fontSize: 22, lineHeight: 1, padding: 4, cursor: 'pointer',
            fontFamily: 'var(--font-mono)',
          }}>×</button>
        </div>

        {/* Body */}
        {state !== 'denied' ? (
          <form onSubmit={submit} style={{ padding: '14px 22px 22px', display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 10.5,
                letterSpacing: '0.18em', textTransform: 'uppercase',
                color: 'var(--accent)', marginBottom: 6,
              }}>Customer access</div>
              <h2 style={{
                fontSize: 22, fontWeight: 700, letterSpacing: '-0.015em',
                margin: 0, lineHeight: 1.15, color: 'var(--fg-1)',
              }}>Sign in to 8/0.</h2>
              <p style={{ fontSize: 13.5, color: 'var(--fg-3)', lineHeight: 1.55, margin: '8px 0 0' }}>
                Carrier and TPA operators only. If you're new, talk to your implementation lead or book a demo.
              </p>
            </div>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>Work email</span>
              <input ref={emailRef} type="email" value={email} onChange={e => setEmail(e.target.value)}
                placeholder="you@carrier.com"
                autoComplete="email"
                style={{
                  padding: '12px 14px',
                  background: 'var(--bg)',
                  border: '1px solid var(--border-2)',
                  borderRadius: 4,
                  color: 'var(--fg-1)',
                  fontFamily: 'var(--font-sans)',
                  fontSize: 14, letterSpacing: '-0.005em',
                  outline: 'none',
                }}
                onFocus={e => e.target.style.borderColor = 'var(--accent)'}
                onBlur={e => e.target.style.borderColor = 'var(--border-2)'}
              />
            </label>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>Password</span>
              <input type="password" value={password} onChange={e => setPassword(e.target.value)}
                placeholder="••••••••"
                autoComplete="current-password"
                style={{
                  padding: '12px 14px',
                  background: 'var(--bg)',
                  border: '1px solid var(--border-2)',
                  borderRadius: 4,
                  color: 'var(--fg-1)',
                  fontFamily: 'var(--font-sans)',
                  fontSize: 14, letterSpacing: '-0.005em',
                  outline: 'none',
                }}
                onFocus={e => e.target.style.borderColor = 'var(--accent)'}
                onBlur={e => e.target.style.borderColor = 'var(--border-2)'}
              />
            </label>

            <button type="submit" disabled={state === 'submitting' || !email.trim()} style={{
              padding: '12px 16px',
              background: state === 'submitting' || !email.trim() ? 'rgba(16,200,128,0.20)' : 'var(--accent)',
              color: state === 'submitting' || !email.trim() ? 'var(--fg-3)' : '#052D1E',
              border: 'none', borderRadius: 4,
              fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 700,
              letterSpacing: '-0.005em',
              cursor: state === 'submitting' || !email.trim() ? 'default' : 'pointer',
              transition: 'background 180ms var(--ease-out)',
            }}>{state === 'submitting' ? 'Signing in…' : 'Sign in →'}</button>

            <div style={{
              borderTop: '1px solid var(--border-1)', paddingTop: 14, marginTop: 4,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              fontSize: 12.5, color: 'var(--fg-3)',
            }}>
              <a href="#" onClick={e => e.preventDefault()} style={{ color: 'var(--fg-3)', textDecoration: 'none', borderBottom: '1px solid var(--border-1)', paddingBottom: 1 }}>Forgot password?</a>
              <a href="#" onClick={e => { e.preventDefault(); setOpen(false); }} style={{ color: 'var(--accent)', textDecoration: 'none', fontFamily: 'var(--font-mono)' }}>Book a demo →</a>
            </div>
          </form>
        ) : (
          <div style={{ padding: '14px 22px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 10.5,
              letterSpacing: '0.18em', textTransform: 'uppercase',
              color: 'var(--attention)',
            }}>Access denied</div>
            <h2 style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-0.015em', margin: 0, lineHeight: 1.2, color: 'var(--fg-1)' }}>
              No customer on file for that account.
            </h2>
            <p style={{ fontSize: 13.5, color: 'var(--fg-3)', lineHeight: 1.6, margin: 0 }}>
              8/0 is in private deployment with a small group of carriers and TPAs. If you're an operator at a live customer, ask your implementation lead for a fresh invitation link. Everyone else is welcome to book a demo.
            </p>
            <div style={{ display: 'flex', gap: 12, marginTop: 4 }}>
              <a href="mailto:connect@eightbyzero.com?subject=Demo" style={{
                padding: '10px 16px', background: 'var(--accent)', color: '#052D1E',
                borderRadius: 4, fontSize: 13.5, fontWeight: 700, textDecoration: 'none',
                letterSpacing: '-0.005em',
              }}>Book a demo →</a>
              <a href="mailto:connect@eightbyzero.com?subject=Customer%20access" style={{
                padding: '10px 0', color: 'var(--fg-2)', textDecoration: 'none',
                borderBottom: '1px solid var(--border-2)', fontSize: 13.5, fontFamily: 'var(--font-mono)',
              }}>connect@eightbyzero.com</a>
            </div>
          </div>
        )}
      </div>

      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes signin-fade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes signin-rise {
          from { opacity: 0; transform: translate(-50%, -46%); }
          to   { opacity: 1; transform: translate(-50%, -50%); }
        }
      `}}/>
    </>
  );
}

window.SignInModal = SignInModal;
