// Access Code Gate — landing screen
// Calls /api/auth/verify-code via tmApi (browser API client at /lib/tm-browser.js)

const CodeGate = ({ onSuccess, onAdminClick }) => {
  const [code, setCode] = React.useState('');
  const [error, setError] = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState('');
  const [shake, setShake] = React.useState(false);
  const [rateLimit, setRateLimit] = React.useState(false);
  const [rateLimitMin, setRateLimitMin] = React.useState(15);
  const [submitting, setSubmitting] = React.useState(false);
  const [attempts, setAttempts] = React.useState(0);
  const inputRef = React.useRef(null);

  React.useEffect(() => { inputRef.current?.focus(); }, []);

  const formatCode = (raw) => {
    const clean = raw.replace(/[^A-Z0-9]/gi, '').toUpperCase().slice(0, 16);
    return clean.match(/.{1,4}/g)?.join('-') || '';
  };

  const handleChange = (e) => {
    setCode(formatCode(e.target.value));
    setError(false);
    setErrorMsg('');
  };

  const submit = async () => {
    if (submitting || rateLimit) return;
    const stripped = code.replace(/-/g, '');
    if (stripped.length !== 16) {
      triggerError('Code must be 16 characters.');
      return;
    }
    setSubmitting(true);
    try {
      const res = await tmApi.customer.verifyCode(code);   // sends e.g. "DEMO-CODE-2026-ENTR"
      onSuccess({ codePreview: res?.codePreview || '' });
    } catch (e) {
      const c = e.code || 'http_error';
      if (c === 'rate_limited') {
        const m = /(\d+)\s*minutes/.exec(e.message || '');
        const mins = m ? Number(m[1]) : 15;
        setRateLimitMin(mins);
        setRateLimit(true);
        setTimeout(() => setRateLimit(false), Math.min(mins, 15) * 60 * 1000);
      } else if (c === 'invalid_code' || c === 'invalid_code_format') {
        triggerError('Invalid code.');
      } else if (c === 'key_revoked') {
        triggerError('This code has been revoked.');
      } else if (c === 'key_expired') {
        triggerError('This code has expired.');
      } else {
        triggerError(e.message || 'Sign-in failed.');
      }
      setAttempts((a) => a + 1);
    } finally {
      setSubmitting(false);
    }
  };

  const triggerError = (msg) => {
    setError(true);
    setErrorMsg(msg || '');
    setShake(true);
    setTimeout(() => setShake(false), 500);
  };

  const fillDemo = () => setCode('DEMO-CODE-2026-ENTR');

  return (
    <div style={{ minHeight: '100vh', background: '#0A0A0A', color: '#EDEDED', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 24, fontFamily: "'Geist', system-ui, sans-serif", position: 'relative', overflow: 'hidden' }}>
      {/* subtle grid bg */}
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'linear-gradient(#1a1a1a 1px, transparent 1px), linear-gradient(90deg, #1a1a1a 1px, transparent 1px)', backgroundSize: '48px 48px', opacity: 0.4, maskImage: 'radial-gradient(ellipse at center, black 0%, transparent 70%)' }} />

      <div style={{ position: 'relative', width: '100%', maxWidth: 440, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        {/* Logo + wordmark */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 48 }}>
          <IconLogo size={22} />
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 14, letterSpacing: '0.18em', color: '#EDEDED' }}>TEMPMAIL<span style={{ color: '#10B981' }}>.LOCAL</span></div>
        </div>

        {/* SMTP status dotted line */}
        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: '#565656', letterSpacing: '0.2em', marginBottom: 18, display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#10B981', boxShadow: '0 0 8px #10B981', animation: 'pulse 2s ease-in-out infinite' }} />
          <span>INVITE-ONLY · PRIVATE RELAY</span>
        </div>

        <h1 style={{ fontSize: 32, fontWeight: 500, letterSpacing: '-0.02em', margin: '0 0 12px 0', textAlign: 'center' }}>Enter access code</h1>
        <p style={{ fontSize: 14, color: '#8A8A8A', margin: '0 0 36px 0', textAlign: 'center', lineHeight: 1.5 }}>Paste or type the 16-character code you were issued.</p>

        <div style={{ width: '100%', position: 'relative', animation: shake ? 'shake 0.5s ease' : 'none' }}>
          <input
            ref={inputRef}
            value={code}
            onChange={handleChange}
            onKeyDown={(e) => e.key === 'Enter' && submit()}
            placeholder="XXXX-XXXX-XXXX-XXXX"
            disabled={rateLimit || submitting}
            style={{
              width: '100%',
              background: '#141414',
              border: `1px solid ${error ? '#DC2626' : '#262626'}`,
              color: '#EDEDED',
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 18,
              padding: '16px 18px',
              borderRadius: 6,
              outline: 'none',
              letterSpacing: '0.08em',
              textAlign: 'center',
              transition: 'border-color 150ms ease, background 150ms ease',
              boxSizing: 'border-box',
            }}
            onFocus={(e) => !error && (e.target.style.borderColor = '#404040')}
            onBlur={(e) => !error && (e.target.style.borderColor = '#262626')}
          />
        </div>

        <button
          onClick={submit}
          disabled={rateLimit || submitting}
          style={{
            width: '100%',
            marginTop: 12,
            background: '#10B981',
            color: '#0A0A0A',
            border: 'none',
            padding: '14px 18px',
            borderRadius: 6,
            fontFamily: "'Geist', system-ui, sans-serif",
            fontSize: 14,
            fontWeight: 600,
            letterSpacing: '0.02em',
            cursor: rateLimit || submitting ? 'not-allowed' : 'pointer',
            opacity: rateLimit || submitting ? 0.5 : 1,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 8,
            transition: 'background 150ms ease',
          }}
          onMouseEnter={(e) => !rateLimit && !submitting && (e.target.style.background = '#0ea371')}
          onMouseLeave={(e) => (e.target.style.background = '#10B981')}
        >
          {submitting ? 'Verifying…' : 'Enter'} <IconArrow size={14} stroke="#0A0A0A" />
        </button>

        {error && !rateLimit && (
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#DC2626', marginTop: 14, display: 'flex', alignItems: 'center', gap: 6 }}>
            <IconAlert size={12} stroke="#DC2626" /> {errorMsg || 'Invalid code.'}
          </div>
        )}

        {rateLimit && (
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#F59E0B', marginTop: 14, display: 'flex', alignItems: 'center', gap: 6 }}>
            <IconClock size={12} stroke="#F59E0B" /> Too many attempts. Try again in {rateLimitMin} minutes.
          </div>
        )}

        {/* "Are you an admin?" link — sits between Enter button and contact-admin row */}
        <button
          onClick={() => onAdminClick && onAdminClick()}
          style={{
            marginTop: 14, background: 'none', border: 'none', cursor: 'pointer',
            color: '#565656', fontSize: 11, fontFamily: "'JetBrains Mono', monospace",
            letterSpacing: '0.1em', padding: '4px 8px', borderRadius: 3,
            transition: 'color 120ms',
          }}
          onMouseEnter={(e) => (e.currentTarget.style.color = '#F59E0B')}
          onMouseLeave={(e) => (e.currentTarget.style.color = '#565656')}
        >
          ARE YOU AN ADMIN? <span style={{ color: '#404040' }}>→</span>
        </button>

        <div style={{ marginTop: 26, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
          <p style={{ fontSize: 12, color: '#565656', margin: 0 }}>Don't have a code? Contact admin.</p>
          <button onClick={fillDemo} style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: '#10B981', background: 'none', border: '1px dashed #262626', padding: '6px 10px', borderRadius: 4, cursor: 'pointer', letterSpacing: '0.1em' }}>
            DEMO · FILL TEST CODE
          </button>
        </div>

        {/* footer */}
        <div style={{ position: 'absolute', bottom: -140, fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: '#404040', display: 'flex', gap: 20 }}>
          <span>v0.4.2</span>
          <span>·</span>
          <span>status: operational</span>
          <span>·</span>
          <span>build 7f9a2c</span>
        </div>
      </div>
    </div>
  );
};

window.CodeGate = CodeGate;
