// Lightweight account system. localStorage-backed mock auth
// Real build: swap for magic-link email flow via Google Apps Script / Supabase

const AUTH_KEY = 'afsws-auth';
const PROFILES_KEY = 'afsws-profiles';
const REGISTRATIONS_KEY = 'afsws-registrations';

const Auth = {
  // Get all profiles (keyed by email)
  _getProfiles() {
    try { return JSON.parse(localStorage.getItem(PROFILES_KEY) || '{}'); }
    catch(e) { return {}; }
  },
  _saveProfiles(p) {
    localStorage.setItem(PROFILES_KEY, JSON.stringify(p));
  },

  // Current session
  currentUser() {
    try {
      const session = JSON.parse(localStorage.getItem(AUTH_KEY) || 'null');
      if (!session?.email) return null;
      const profiles = this._getProfiles();
      return profiles[session.email.toLowerCase()] || null;
    } catch(e) { return null; }
  },

  signIn(email) {
    const key = email.toLowerCase().trim();
    const profiles = this._getProfiles();
    if (!profiles[key]) return { ok: false, error: 'No account found. Create one first.' };
    localStorage.setItem(AUTH_KEY, JSON.stringify({ email: key, ts: Date.now() }));
    return { ok: true, user: profiles[key] };
  },

  signUp(profileData) {
    const key = (profileData.email || '').toLowerCase().trim();
    if (!key) return { ok: false, error: 'Email required.' };
    const profiles = this._getProfiles();
    profiles[key] = { ...profileData, email: key, createdAt: profiles[key]?.createdAt || Date.now() };
    this._saveProfiles(profiles);
    localStorage.setItem(AUTH_KEY, JSON.stringify({ email: key, ts: Date.now() }));
    return { ok: true, user: profiles[key] };
  },

  updateProfile(profileData) {
    const user = this.currentUser();
    if (!user) return { ok: false };
    const profiles = this._getProfiles();
    profiles[user.email] = { ...profiles[user.email], ...profileData };
    this._saveProfiles(profiles);
    return { ok: true, user: profiles[user.email] };
  },

  signOut() {
    localStorage.removeItem(AUTH_KEY);
  },

  // Registrations
  _getRegs() {
    try { return JSON.parse(localStorage.getItem(REGISTRATIONS_KEY) || '[]'); }
    catch(e) { return []; }
  },
  _saveRegs(r) {
    localStorage.setItem(REGISTRATIONS_KEY, JSON.stringify(r));
  },

  registerForEvent(eventId, formData) {
    const regs = this._getRegs();
    const email = (formData.email || '').toLowerCase().trim();
    regs.push({
      id: 'R' + Date.now().toString(36).toUpperCase(),
      eventId, email,
      name: formData.name,
      ts: Date.now(),
      status: 'confirmed',
    });
    this._saveRegs(regs);
    return regs[regs.length - 1];
  },

  getRegistrationsForUser(email) {
    if (!email) return [];
    const key = email.toLowerCase().trim();
    return this._getRegs().filter(r => r.email === key);
  },

  cancelRegistration(regId) {
    const regs = this._getRegs();
    const next = regs.map(r => r.id === regId ? { ...r, status: 'cancelled' } : r);
    this._saveRegs(next);
  },
};

window.Auth = Auth;

// ─────────────────────────────────────────────────────────
// Sign In / Sign Up modal
// ─────────────────────────────────────────────────────────
function AuthModal({ open, onClose, onSuccess, t, initialMode = 'signin' }) {
  const [mode, setMode] = React.useState(initialMode);
  const [email, setEmail] = React.useState('');
  const [name, setName] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [age, setAge] = React.useState('');
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    if (open) { setErr(''); setMode(initialMode); }
  }, [open, initialMode]);

  if (!open) return null;

  const submit = () => {
    setErr('');
    if (!email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setErr('Valid email required.'); return;
    }
    if (mode === 'signin') {
      const r = Auth.signIn(email);
      if (!r.ok) { setErr(r.error); return; }
      onSuccess(r.user); onClose();
    } else {
      if (!name.trim() || name.trim().length < 2) { setErr('Name required.'); return; }
      const ageNum = parseInt(age, 10);
      if (!age || isNaN(ageNum) || ageNum < 18 || ageNum > 39) { setErr('Age must be 18–39.'); return; }
      if (!phone.trim() || phone.replace(/\D/g, '').length < 7) { setErr('Valid phone required.'); return; }
      const r = Auth.signUp({ email, name, phone, age });
      if (!r.ok) { setErr(r.error); return; }
      onSuccess(r.user); onClose();
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 2000, padding: 20, animation: 'fadeIn 0.2s ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: t.cellBg, border: `1px solid ${t.lineStrong}`,
        width: '100%', maxWidth: 420, padding: 32,
        boxShadow: t.shadow,
      }}>
        <div style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
          letterSpacing: '0.3em', color: t.brass, marginBottom: 10,
        }}>◉ {mode === 'signin' ? 'RETURNING OPERATOR' : 'NEW RECRUIT'}</div>
        <div style={{
          fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 28,
          color: t.fg, letterSpacing: '0.02em', marginBottom: 6,
        }}>{mode === 'signin' ? 'SIGN IN' : 'CREATE ACCOUNT'}</div>
        <div style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 12,
          color: t.dim, marginBottom: 22, lineHeight: 1.5,
        }}>
          {mode === 'signin'
            ? 'Your info auto-fills on every signup. Your roster stays with you.'
            : 'Save your info once. Skip the form on future events.'}
        </div>

        <AuthInput label="EMAIL" value={email} onChange={setEmail} t={t} type="email" />
        {mode === 'signup' && (
          <>
            <AuthInput label="FULL NAME" value={name} onChange={setName} t={t} />
            <AuthInput label="PHONE" value={phone} onChange={setPhone} t={t} type="tel" />
            <AuthInput label="AGE" value={age} onChange={setAge} t={t} type="number" />
          </>
        )}

        {err && (
          <div style={{
            fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 12,
            color: '#d06a4a', marginTop: 6, marginBottom: 4,
          }}>{err}</div>
        )}

        <button onClick={submit} style={{
          width: '100%', padding: '16px', marginTop: 16,
          background: t.brass, color: '#0F1114', border: 'none',
          fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13,
          letterSpacing: '0.3em', cursor: 'pointer',
        }}>{mode === 'signin' ? 'SIGN IN' : 'CREATE ACCOUNT'}</button>

        <div style={{ textAlign: 'center', marginTop: 16 }}>
          <button onClick={() => setMode(mode === 'signin' ? 'signup' : 'signin')} style={{
            background: 'transparent', border: 'none', color: t.dim,
            fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 11,
            letterSpacing: '0.15em', cursor: 'pointer', padding: 8,
          }}>
            {mode === 'signin' ? "No account? CREATE ONE →" : "Already have one? SIGN IN →"}
          </button>
        </div>
      </div>
    </div>
  );
}

function AuthInput({ label, value, onChange, t, type = 'text' }) {
  const [focus, setFocus] = React.useState(false);
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 10,
        letterSpacing: '0.3em', color: focus ? t.brass : t.dim,
        marginBottom: 6, transition: 'color 0.15s',
      }}>{label}</div>
      <input type={type} value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{
          width: '100%', padding: '10px 0', background: 'transparent',
          border: 'none', borderBottom: `1px solid ${focus ? t.brass : t.lineStrong}`,
          fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 16,
          color: t.fg, outline: 'none', boxSizing: 'border-box',
          transition: 'border-color 0.15s',
        }} />
    </div>
  );
}

window.AuthModal = AuthModal;
