// LoginScreen.jsx — Telefon + 6 haneli PIN ile tek-form giriş
const { useState: useStateLS, useRef: useRefLS } = React;

// Native numeric PIN input. Auto-submits when length reached.
// On mobile (inputMode=numeric) the OS keypad opens automatically; on
// desktop the user just types. Visual: single styled input with masked dots.
function PinInput({ length, onSubmit, error, autoFocus = true, disabled, name, accent }) {
  const [pin, setPin] = useStateLS('');
  const submitting = useRefLS(false);
  const inputRef = useRefLS(null);
  const color = accent || 'var(--accent)';

  const reset = () => {
    setPin('');
    submitting.current = false;
    if (inputRef.current) {
      try { inputRef.current.focus(); } catch {}
    }
  };

  const handleChange = (e) => {
    if (submitting.current) return;
    const v = e.target.value.replace(/\D/g, '').slice(0, length);
    setPin(v);
    if (v.length === length && onSubmit) {
      submitting.current = true;
      setTimeout(async () => {
        try {
          const ok = await onSubmit(v);
          if (ok === false) reset();
          else submitting.current = false;
        } catch { reset(); }
      }, 80);
    }
  };

  return (
    <div>
      <input
        ref={inputRef}
        type="password"
        inputMode="numeric"
        pattern="[0-9]*"
        autoComplete="off"
        autoCorrect="off"
        spellCheck="false"
        name={name || 'pin'}
        maxLength={length}
        value={pin}
        onChange={handleChange}
        autoFocus={autoFocus}
        disabled={disabled || submitting.current}
        placeholder={'•'.repeat(length).split('').join(' ')}
        style={{
          width: '100%',
          padding: '18px 16px',
          fontSize: 30,
          fontWeight: 700,
          textAlign: 'center',
          letterSpacing: '0.45em',
          border: '2px solid',
          borderColor: error ? 'var(--red)' : (pin.length === length ? color : 'var(--border)'),
          borderRadius: 14,
          fontFamily: 'inherit',
          outline: 'none',
          background: 'white',
          color: 'var(--text)',
          transition: 'border-color 0.15s, box-shadow 0.15s',
          boxShadow: error ? '0 0 0 4px #FEF2F2' : '0 0 0 0 transparent',
        }}
        onFocus={(e) => { if (!error) e.currentTarget.style.borderColor = color; }}
        onBlur={(e) => { if (!error && pin.length !== length) e.currentTarget.style.borderColor = 'var(--border)'; }}
      />
      {error && <div style={{ color: 'var(--red)', fontSize: 13, marginTop: 10, fontWeight: 600, textAlign: 'center' }}>{error}</div>}
    </div>
  );
}

// Format raw 10-digit input as "5XX XXX XX XX"
function formatPhoneInput(digits) {
  const d = digits.slice(0, 10);
  const parts = [];
  if (d.length > 0) parts.push(d.slice(0, 3));
  if (d.length > 3) parts.push(d.slice(3, 6));
  if (d.length > 6) parts.push(d.slice(6, 8));
  if (d.length > 8) parts.push(d.slice(8, 10));
  return parts.join(' ');
}

function LoginScreen({ onLoggedIn }) {
  const [phoneDigits, setPhoneDigits] = useStateLS('');
  const [error, setError] = useStateLS(null);
  const pinInputRef = useRefLS(null);

  const fullPhone = '+90' + phoneDigits;
  const phoneOk = phoneDigits.length === 10;

  const submit = async (pin) => {
    try {
      setError(null);
      await Store.login(fullPhone, pin);
      onLoggedIn();
      return true;
    } catch (e) {
      const msg = e.status === 429 ? e.message : 'Telefon veya PIN hatalı';
      setError(msg);
      return false;
    }
  };

  const handlePhoneChange = (e) => {
    const d = e.target.value.replace(/\D/g, '').slice(0, 10);
    setPhoneDigits(d);
    setError(null);
  };

  // When phone reaches 10 digits, auto-focus the PIN field.
  const handlePhoneKeyUp = (e) => {
    if (phoneDigits.length === 10 && pinInputRef.current) {
      try { pinInputRef.current.querySelector('input')?.focus(); } catch {}
    }
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 300, background: 'var(--bg)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      paddingTop: 'max(20px, env(safe-area-inset-top, 20px))',
      paddingBottom: 'max(20px, env(safe-area-inset-bottom, 20px))',
      paddingLeft: 24, paddingRight: 24,
    }}>
      <div style={{ width: '100%', maxWidth: 380, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18 }}>
        <div style={{ width: 56, height: 56, background: 'var(--accent)', borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28 }}>☕</div>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontWeight: 800, fontSize: 22, letterSpacing: '-0.02em' }}>adisyon</div>
          <div style={{ fontSize: 12, color: 'var(--text-3)', fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase' }}>kafe pos</div>
        </div>

        <form
          onSubmit={(e) => e.preventDefault()}
          style={{ width: '100%', background: 'white', borderRadius: 18, boxShadow: 'var(--shadow-lg)', padding: 24 }}
        >
          <div style={{ fontWeight: 700, fontSize: 18, marginBottom: 4 }}>Giriş Yap</div>
          <div style={{ color: 'var(--text-2)', fontSize: 13, marginBottom: 20 }}>Telefon numaran ve 6 haneli PIN ile</div>

          {/* Phone */}
          <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 6 }}>Telefon</label>
          <div style={{ display: 'flex', alignItems: 'stretch', border: '2px solid var(--border)', borderRadius: 12, overflow: 'hidden', marginBottom: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', padding: '0 12px', background: 'var(--bg)', fontSize: 16, fontWeight: 600, color: 'var(--text-2)' }}>+90</div>
            <input
              type="tel" inputMode="numeric" autoComplete="tel-national"
              placeholder="5XX XXX XX XX"
              value={formatPhoneInput(phoneDigits)}
              onChange={handlePhoneChange}
              onKeyUp={handlePhoneKeyUp}
              style={{ flex: 1, padding: '14px 14px', border: 'none', outline: 'none', fontFamily: 'inherit', fontSize: 17, fontWeight: 600, letterSpacing: '0.04em' }}
            />
          </div>

          {/* PIN */}
          <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 6 }}>PIN</label>
          <div ref={pinInputRef}>
            <PinInput
              length={6}
              onSubmit={submit}
              error={error}
              autoFocus={false}
              disabled={!phoneOk}
            />
          </div>

          {!phoneOk && (
            <div style={{ marginTop: 12, fontSize: 12, color: 'var(--text-3)', textAlign: 'center' }}>
              Önce telefon numaranı gir.
            </div>
          )}
        </form>
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen, PinInput, formatPhoneInput });
