// Lock screen — AK license number + 4-digit PIN
// Credentials are validated server-side; no passcodes in client JS.
const { useState: useStateL, useEffect: useEffectL, useRef: useRefL } = React;

function LockScreen({ onSignIn }) {
  const [licenseNumber, setLicenseNumber] = useStateL('');
  const [digits, setDigits] = useStateL(['', '', '', '']);
  const [error, setError] = useStateL('');
  const [shake, setShake] = useStateL(false);
  const [loading, setLoading] = useStateL(false);
  const [attempts, setAttempts] = useStateL(0);
  const [lockedUntil, setLockedUntil] = useStateL(0);
  const [now, setNow] = useStateL(Date.now());
  const licenseRef = useRefL(null);
  const inputs = useRefL([]);

  useEffectL(() => { licenseRef.current?.focus(); }, []);

  useEffectL(() => {
    if (lockedUntil <= now) return;
    const t = setInterval(() => setNow(Date.now()), 250);
    return () => clearInterval(t);
  }, [lockedUntil, now]);

  const locked = lockedUntil > now;
  const lockSecondsLeft = locked ? Math.ceil((lockedUntil - now) / 1000) : 0;

  function setDigit(i, val) {
    if (locked || loading) return;
    const clean = val.replace(/\D/g, '').slice(-1);
    const next = [...digits];
    next[i] = clean;
    setDigits(next);
    if (error) setError('');
    if (clean && i < 3) inputs.current[i + 1]?.focus();
    if (clean && i === 3 && next.every(d => d !== '')) {
      setTimeout(() => attemptSignIn(next.join('')), 80);
    }
  }

  function onKeyDown(i, e) {
    if (locked || loading) { e.preventDefault(); return; }
    if (e.key === 'Backspace') {
      if (digits[i]) {
        const next = [...digits]; next[i] = ''; setDigits(next);
        if (error) setError('');
      } else if (i > 0) {
        inputs.current[i - 1]?.focus();
        const next = [...digits]; next[i - 1] = ''; setDigits(next);
      }
      e.preventDefault();
    } else if (e.key === 'ArrowLeft' && i > 0) {
      inputs.current[i - 1]?.focus(); e.preventDefault();
    } else if (e.key === 'ArrowRight' && i < 3) {
      inputs.current[i + 1]?.focus(); e.preventDefault();
    } else if (e.key === 'Enter') {
      if (digits.every(d => d !== '')) attemptSignIn(digits.join(''));
    }
  }

  function onPaste(e) {
    if (locked || loading) { e.preventDefault(); return; }
    const text = (e.clipboardData?.getData('text') || '').replace(/\D/g, '').slice(0, 4);
    if (!text) return;
    e.preventDefault();
    const next = ['', '', '', ''];
    for (let i = 0; i < text.length; i++) next[i] = text[i];
    setDigits(next);
    if (error) setError('');
    const lastIdx = Math.min(text.length, 4) - 1;
    inputs.current[lastIdx]?.focus();
    if (text.length === 4) setTimeout(() => attemptSignIn(text), 80);
  }

  function onLicenseKeyDown(e) {
    if (e.key === 'Enter' || e.key === 'Tab') {
      e.preventDefault();
      inputs.current[0]?.focus();
    }
  }

  async function attemptSignIn(code) {
    if (!licenseNumber.trim()) {
      setError('Enter your AK license number first');
      licenseRef.current?.focus();
      setShake(true);
      setTimeout(() => setShake(false), 450);
      return;
    }

    setLoading(true);
    try {
      const { data, error } = await window._supabase.functions.invoke('sign-in', {
        body: { licenseNumber: licenseNumber.trim(), code },
      });

      if (error) {
        // Check for rate limiting
        if (error.context?.status === 429) {
          const body = await error.context.json().catch(() => ({}));
          setLockedUntil(Date.now() + (body.secondsLeft || 60) * 1000);
          setNow(Date.now());
          setLoading(false);
          setDigits(['', '', '', '']);
          return;
        }
        throw new Error(data?.error || error.message || 'Invalid credentials');
      }

      if (data?.error) {
        throw new Error(data.error);
      }

      // Store session in Supabase client
      await window._supabase.auth.setSession(data.session);
      onSignIn && onSignIn(data.user);

    } catch (err) {
      const nextAttempts = attempts + 1;
      setAttempts(nextAttempts);
      setShake(true);
      setError(err.message || 'Invalid license number or code');
      setTimeout(() => setShake(false), 450);
      setTimeout(() => {
        setDigits(['', '', '', '']);
        inputs.current[0]?.focus();
      }, 500);
      // Client-side visual cooldown (real enforcement is server-side)
      if (nextAttempts >= 5) {
        const cooldown = [10, 30, 60, 300][Math.min(nextAttempts - 5, 3)];
        setLockedUntil(Date.now() + cooldown * 1000);
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="lock-root" data-screen-label="lock">
      <div className={'lock-card' + (shake ? ' shake' : '')}>
        <div className="lock-brand">
          <img src="assets/locals-logo.png" alt="Locals Realty Group" className="lock-logo" />
        </div>
        <div className="lock-head">
          <h1 className="lock-title">Client Tracker</h1>
          <p className="lock-sub">Enter your AK license number and 4-digit code</p>
        </div>

        {/* License number field */}
        <div style={{width:'100%'}}>
          <label style={{display:'block', fontSize:11, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--ink-3)', fontWeight:600, marginBottom:6}}>
            AK License #
          </label>
          <input
            ref={licenseRef}
            type="text"
            value={licenseNumber}
            onChange={e => { setLicenseNumber(e.target.value); if (error) setError(''); }}
            onKeyDown={onLicenseKeyDown}
            placeholder="e.g. LICENSE-12345"
            disabled={locked || loading}
            autoCapitalize="characters"
            autoCorrect="off"
            spellCheck={false}
            style={{
              width: '100%',
              padding: '12px 14px',
              border: '1.5px solid var(--rule)',
              borderRadius: 10,
              background: 'var(--panel-2)',
              color: 'var(--ink)',
              fontFamily: 'var(--font-mono)',
              fontSize: 16,
              letterSpacing: '0.05em',
              outline: 'none',
              transition: 'border-color 0.15s, box-shadow 0.15s',
            }}
            onFocus={e => {
              e.target.style.borderColor = 'var(--accent)';
              e.target.style.boxShadow = '0 0 0 4px color-mix(in oklab, var(--accent) 18%, transparent)';
            }}
            onBlur={e => {
              e.target.style.borderColor = 'var(--rule)';
              e.target.style.boxShadow = 'none';
            }}
          />
        </div>

        {/* 4-digit PIN */}
        <div>
          <label style={{display:'block', fontSize:11, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--ink-3)', fontWeight:600, marginBottom:10, textAlign:'center'}}>
            4-Digit Access Code
          </label>
          <div className={'lock-pad' + (error ? ' err' : '')} onPaste={onPaste}>
            {[0, 1, 2, 3].map(i => (
              <input
                key={i}
                ref={el => inputs.current[i] = el}
                type="password"
                inputMode="numeric"
                autoComplete="one-time-code"
                pattern="[0-9]*"
                maxLength="1"
                value={digits[i]}
                onChange={e => setDigit(i, e.target.value)}
                onKeyDown={e => onKeyDown(i, e)}
                onFocus={e => e.target.select()}
                disabled={locked || loading}
                aria-label={`Digit ${i + 1}`}
                className="lock-digit"
              />
            ))}
          </div>
        </div>

        <div className="lock-msg-row">
          {loading && (
            <div style={{color:'var(--ink-3)', fontSize:13, display:'flex', alignItems:'center', gap:6}}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{animation:'spin 1s linear infinite'}}>
                <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>
              </svg>
              Verifying…
            </div>
          )}
          {error && !locked && !loading && (
            <div className="lock-error" role="alert">
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                <circle cx="8" cy="8" r="7" stroke="currentColor" strokeWidth="1.4"/>
                <path d="M8 4.5v4M8 10.8v.7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
              </svg>
              {error}
            </div>
          )}
          {locked && (
            <div className="lock-error" role="alert">
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                <rect x="3" y="7" width="10" height="7" rx="1.5" stroke="currentColor" strokeWidth="1.4"/>
                <path d="M5 7V5a3 3 0 1 1 6 0v2" stroke="currentColor" strokeWidth="1.4"/>
              </svg>
              Too many attempts — try again in {lockSecondsLeft}s
            </div>
          )}
        </div>

        <div className="lock-foot">
          <span>Locals Realty Group</span>
          <span className="lock-foot-sep">·</span>
          <span>tracker.mlsak.com</span>
        </div>
      </div>
      <div className="lock-help">
        Forgot your code? Ask Hilary.
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

window.LockScreen = LockScreen;
