// screen-login.jsx — PIN-based login

const LAST_USER_KEY = 'pasticeria_last_user_info';

function UserAvatar({ name, color }) {
  const initials = (name || '?').split(' ').map(s => s[0]).slice(0, 2).join('').toUpperCase();
  const palette = ['#D4607A', '#4CAF82', '#D89331', '#4B948F', '#7A5AE0', '#3B1F0A'];
  const bg = color || palette[(initials.charCodeAt(0) + (initials.charCodeAt(1) || 0)) % palette.length];
  return (
    <div style={{ width: 64, height: 64, borderRadius: '50%', background: bg, color: '#FDF8F3',
      display: 'grid', placeItems: 'center', fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em',
      boxShadow: '0 8px 24px -8px rgba(59,31,10,0.3)' }}>
      {initials}
    </div>
  );
}

function getSavedUser() {
  try { return JSON.parse(localStorage.getItem(LAST_USER_KEY)); } catch { return null; }
}
function saveUser(user) {
  localStorage.setItem(LAST_USER_KEY, JSON.stringify({ username: user.username, name: user.name, color: user.color }));
}
function clearSavedUser() {
  localStorage.removeItem(LAST_USER_KEY);
}

function LoginScreen({ onLogin }) {
  const [savedUser] = React.useState(() => getSavedUser());
  const [username, setUsername] = React.useState('');
  const [pin, setPin] = React.useState('');
  const [error, setError] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  // If a previous user is known, go straight to PIN; otherwise ask for username first
  const [step, setStep] = React.useState(savedUser ? 'pin' : 'username');
  const [activeUser, setActiveUser] = React.useState(savedUser); // { username, name, color } | null

  const switchUser = () => {
    clearSavedUser();
    setActiveUser(null);
    setUsername('');
    setPin('');
    setError(false);
    setStep('username');
  };

  const attemptLogin = (fullPin) => {
    const u = activeUser?.username || username;
    setLoading(true);
    window.api.login(u, fullPin).then(user => {
      saveUser(user);
      onLogin(user);
    }).catch(() => {
      setError(true);
      setPin('');
      setLoading(false);
    });
  };

  const onKey = (key) => {
    if (error) setError(false);
    if (key === 'back') {
      setPin(p => p.slice(0, -1));
    } else if (pin.length < 4) {
      const next = pin + key;
      setPin(next);
      if (next.length === 4) attemptLogin(next);
    }
  };

  React.useEffect(() => {
    if (step !== 'pin') return;
    const onKeyDown = (e) => {
      if (e.key >= '0' && e.key <= '9') onKey(e.key);
      else if (e.key === 'Backspace') onKey('back');
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [pin, step]);

  return (
    <div style={{ minHeight: '100vh', display: 'grid', background: 'var(--cream)' }}>
      <div style={{ display: 'grid', placeItems: 'center', padding: 24 }} className="login-layout">
        <div style={{ width: '100%', maxWidth: 420, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 28 }}>

          {/* Brand */}
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, marginBottom: 8 }}>
            <div className="login-brand-logo" style={{
              width: 76, height: 76,
              borderRadius: '50%',
              background: 'var(--ink)',
              display: 'grid', placeItems: 'center',
              boxShadow: '0 12px 30px -10px rgba(59, 31, 10, 0.4)',
            }}>
              <PastericaLogo size={38} color="var(--cream)" />
            </div>
            <div style={{ textAlign: 'center' }}>
              <div className="display login-brand-name" style={{ fontSize: 38, fontWeight: 600, letterSpacing: '-0.015em', lineHeight: 1 }}>Sistemi</div>
              <div style={{ marginTop: 6, fontSize: 12.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-mute)' }}>
                Internal · Vetëm për stafin
              </div>
            </div>
          </div>

          {/* ── Username step ── */}
          {step === 'username' && (
            <div className="slide-up" style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div className="field">
                <label className="field-label">Emri i përdoruesit</label>
                <input
                  className="input lg"
                  type="text"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  onKeyDown={(e) => { if (e.key === 'Enter' && username.trim()) { setActiveUser({ username: username.trim(), name: username.trim(), color: null }); setStep('pin'); } }}
                  placeholder="emri i përdoruesit"
                  autoFocus
                />
              </div>
              <button className="btn lg" disabled={!username.trim()}
                onClick={() => { setActiveUser({ username: username.trim(), name: username.trim(), color: null }); setStep('pin'); }}>
                Vazhdo <IconArrowRight size={18} color="var(--cream)" />
              </button>
            </div>
          )}

          {/* ── PIN step ── */}
          {step === 'pin' && (
            <div className="slide-up" style={{ width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 24 }}>

              {/* User avatar + name */}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
                <UserAvatar name={activeUser?.name || activeUser?.username || ''} color={activeUser?.color} />
                <div>
                  <div style={{ textAlign: 'center', fontSize: 17, fontWeight: 600, fontFamily: 'var(--font-display)', fontStyle: 'italic' }}>
                    {activeUser?.name || activeUser?.username}
                  </div>
                  <div className="muted" style={{ textAlign: 'center', fontSize: 12.5, marginTop: 2 }}>Shkruani PIN-in tuaj 4-shifror</div>
                </div>
              </div>

              {/* PIN dots */}
              <div style={{ display: 'flex', gap: 14, alignItems: 'center', height: 24 }}>
                {[0, 1, 2, 3].map(i => (
                  <div key={i} className={`pin-dot ${error ? 'error' : ''} ${pin.length > i ? 'filled' : ''}`} />
                ))}
              </div>

              {error && (
                <div style={{ color: 'var(--red)', fontSize: 13.5, display: 'flex', alignItems: 'center', gap: 6 }}>
                  <IconAlertCircle size={14} color="var(--red)" />
                  PIN i gabuar — ju lutemi provoni përsëri
                </div>
              )}

              {/* PIN keypad */}
              <div className="pin-grid">
                {[1,2,3,4,5,6,7,8,9].map(n => (
                  <button key={n} className="pin-key" onClick={() => onKey(String(n))} disabled={loading}>{n}</button>
                ))}
                {/* Bottom row: change user | 0 | backspace */}
                <button className="pin-key action" onClick={switchUser} title="Ndrysho përdoruesin">
                  <IconUsers size={18} />
                </button>
                <button className="pin-key" onClick={() => onKey('0')} disabled={loading}>0</button>
                <button className="pin-key action" onClick={() => onKey('back')} disabled={!pin.length || loading}>
                  <IconBackspace size={20} />
                </button>
              </div>

              {/* Change user text link */}
              <button onClick={switchUser} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-mute)', fontSize: 13, display: 'flex', alignItems: 'center', gap: 5 }}>
                <IconUsers size={13} color="var(--ink-mute)" /> Ndrysho përdoruesin
              </button>

              <div style={{ height: 20, display: 'flex', alignItems: 'center', gap: 8, color: 'var(--ink-mute)', fontSize: 13 }}>
                {loading && (
                  <>
                    <span className="spinner" style={{ borderColor: 'rgba(59,31,10,0.2)', borderTopColor: 'var(--ink)' }} />
                    Duke u kyçur…
                  </>
                )}
              </div>
            </div>
          )}

        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen });
