/* ============================================================
   auth-ui.jsx — login screen + account badge + guest upgrade
   ============================================================ */
const { useState: useStateA, useEffect: useEffectA } = React;

const AUTH_ERRORS = {
  invalid_email: 'Email no válido.',
  weak_password: 'La contraseña necesita al menos 6 caracteres.',
  email_taken: 'Ese email ya tiene cuenta.',
  bad_credentials: 'Email o contraseña incorrectos.',
  not_guest: 'Ya tienes una cuenta completa.',
  no_token: 'Sesión no válida.',
  bad_token: 'Sesión caducada, inicia de nuevo.',
};
function authMsg(e) {
  if (!e) return 'Error desconocido.';
  if (e.code && AUTH_ERRORS[e.code]) return AUTH_ERRORS[e.code];
  if (e.message && /failed to fetch|networkerror|load failed/i.test(e.message))
    return 'No se pudo conectar con el servidor.';
  return 'Error: ' + (e.code || e.message || 'desconocido');
}

// Subscribe React to the AUTH store.
function useAuth() {
  const [snap, setSnap] = useStateA(() => window.AUTH ? window.AUTH.snapshot() : { ready: true, authed: false });
  useEffectA(() => {
    if (!window.AUTH) return;
    setSnap(window.AUTH.snapshot());
    return window.AUTH.subscribe(setSnap);
  }, []);
  return snap;
}

/* ---------------- credential form (login / register / upgrade) ---------------- */
function CredForm({ mode, onSubmit, busy, error }) {
  const [email, setEmail] = useStateA('');
  const [pw, setPw] = useStateA('');
  const submit = (e) => { e.preventDefault(); if (!busy) onSubmit(email, pw); };
  const inputStyle = {
    width: 320, padding: '12px 14px', fontSize: 14, background: '#07131f',
    color: '#eaf6ff', border: '3px solid #16242f', outline: 'none', fontFamily: 'inherit',
  };
  return (
    <form onSubmit={submit} className="col center" style={{ gap: 12 }}>
      <input type="email" placeholder="email" value={email} autoComplete="username"
        onChange={(e) => setEmail(e.target.value)} className="body" style={inputStyle} />
      <input type="password" placeholder="contraseña" value={pw} autoComplete={mode === 'register' ? 'new-password' : 'current-password'}
        onChange={(e) => setPw(e.target.value)} className="body" style={inputStyle} />
      {error && <div className="body" style={{ fontSize: 16, color: '#ff6b8b', maxWidth: 340, textAlign: 'center' }}>{error}</div>}
      <Btn variant="btn-primary" disabled={busy} style={{ fontSize: 13, padding: '13px 26px' }}>
        {busy ? '...' : mode === 'register' ? 'CREAR CUENTA ▶' : mode === 'upgrade' ? 'GUARDAR CUENTA ▶' : 'ENTRAR ▶'}
      </Btn>
    </form>
  );
}

/* ---------------- login screen ---------------- */
function LoginScreen({ onAuthed }) {
  const [mode, setMode] = useStateA('login');   // login | register
  const [busy, setBusy] = useStateA(false);
  const [error, setError] = useStateA(null);

  async function run(fn) {
    setBusy(true); setError(null);
    try { await fn(); onAuthed && onAuthed(); }
    catch (e) { setError(authMsg(e)); }
    finally { setBusy(false); }
  }
  const doAuth = (email, pw) =>
    run(() => mode === 'register' ? window.AUTH.register(email, pw) : window.AUTH.login(email, pw));
  const doGuest = () => run(() => window.AUTH.guest());

  return (
    <div className="fill col center" style={{ background: 'radial-gradient(120% 90% at 50% 20%, #16344b, #07131f 75%)', gap: 22, padding: 24 }}>
      <div className="col center" style={{ gap: 6 }}>
        <div className="pix" style={{ fontSize: 12, color: '#2ce8d8', letterSpacing: 6, textShadow: '2px 2px 0 #000' }}>EL TIBURÓN</div>
        <div className="pix" style={{ fontSize: 40, color: '#ff5a3c', textShadow: '4px 4px 0 #07131f, 0 0 30px rgba(255,90,60,.4)' }}>TUNTUN</div>
      </div>
      <div className="bob"><Sprite name="c_tuntun" scale={5} /></div>

      <div className="panel col center" style={{ padding: 22, gap: 16, background: '#0b1d2e', minWidth: 380 }}>
        <div className="row center" style={{ gap: 0 }}>
          {['login', 'register'].map(m => (
            <div key={m} onClick={() => { setMode(m); setError(null); }} className="pix"
              style={{ fontSize: 11, padding: '8px 18px', cursor: 'pointer',
                color: mode === m ? '#07131f' : '#9db8c9', background: mode === m ? '#ffd23f' : '#13293d',
                borderTop: '3px solid ' + (mode === m ? '#ffd23f' : '#16242f') }}>
              {m === 'login' ? 'ENTRAR' : 'REGISTRARSE'}
            </div>
          ))}
        </div>
        <CredForm mode={mode} onSubmit={doAuth} busy={busy} error={error} />
      </div>

      <div className="col center" style={{ gap: 8 }}>
        <div className="body" style={{ fontSize: 15, color: '#6f8aa0' }}>— o —</div>
        <Btn disabled={busy} onClick={doGuest} style={{ fontSize: 11, padding: '11px 22px' }}>JUGAR COMO INVITADO</Btn>
        <div className="body" style={{ fontSize: 13, color: '#5a7088', maxWidth: 340, textAlign: 'center' }}>
          Tu progreso de invitado se guarda en este equipo. Crea una cuenta luego para llevarlo a cualquier sitio.
        </div>
      </div>
    </div>
  );
}

/* ---------------- guest → account upgrade modal ---------------- */
function UpgradeModal({ onClose }) {
  const [busy, setBusy] = useStateA(false);
  const [error, setError] = useStateA(null);
  const submit = async (email, pw) => {
    setBusy(true); setError(null);
    try { await window.AUTH.attachAccount(email, pw); onClose(); }
    catch (e) { setError(authMsg(e)); }
    finally { setBusy(false); }
  };
  return (
    <div className="fill col center" style={{ position: 'absolute', inset: 0, zIndex: 400, background: 'rgba(7,19,31,.93)', gap: 18, padding: 24 }}>
      <div className="pix" style={{ fontSize: 16, color: '#ffd23f', textShadow: '2px 2px 0 #000' }}>GUARDA TU PROGRESO</div>
      <div className="body" style={{ fontSize: 17, color: '#9db8c9', maxWidth: 380, textAlign: 'center' }}>
        Crea una cuenta con email y contraseña. Conserva tus desbloqueos y podrás entrar desde cualquier dispositivo.
      </div>
      <div className="panel col center" style={{ padding: 22, background: '#0b1d2e' }}>
        <CredForm mode="upgrade" onSubmit={submit} busy={busy} error={error} />
      </div>
      <Btn disabled={busy} onClick={onClose} style={{ fontSize: 10 }}>AHORA NO</Btn>
    </div>
  );
}

/* ---------------- account badge (top-left corner overlay) ---------------- */
function AccountBadge() {
  const auth = useAuth();
  const [upgrading, setUpgrading] = useStateA(false);
  if (!auth.authed) return null;
  const guest = auth.user && auth.user.isGuest;
  const label = guest ? 'INVITADO' : (auth.user && auth.user.email) || 'CUENTA';
  const dot = auth.online ? '#9ae600' : '#6f8aa0';
  return (
    <React.Fragment>
      <div className="row" style={{ position: 'fixed', top: 8, left: 8, zIndex: 350, alignItems: 'center', gap: 8,
        background: 'rgba(7,19,31,.82)', border: '2px solid #16242f', padding: '5px 9px' }}>
        <span title={auth.online ? 'sincronizado' : 'sin conexión'}
          style={{ width: 8, height: 8, borderRadius: '50%', background: dot, boxShadow: '0 0 6px ' + dot }} />
        <span className="pix" style={{ fontSize: 8, color: '#9db8c9', maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
        {guest && <span onClick={() => setUpgrading(true)} className="pix"
          style={{ fontSize: 8, color: '#ffd23f', cursor: 'pointer', borderBottom: '1px dotted #ffd23f' }}>CREAR CUENTA</span>}
        <span onClick={() => window.AUTH.logout()} className="pix"
          style={{ fontSize: 8, color: '#ff6b8b', cursor: 'pointer' }}>SALIR</span>
      </div>
      {upgrading && <UpgradeModal onClose={() => setUpgrading(false)} />}
    </React.Fragment>
  );
}

Object.assign(window, { useAuth, LoginScreen, AccountBadge, UpgradeModal });
