/* Nutri Auth — useAuth hook + LoginScreen + BrandMark.
   Wraps Firebase Auth (compat) into a tiny React surface. */

/* BrandMark — shared logo that prefers ./icon.png and falls back to the green "N".
   Used by LoginScreen, SplashScreen, and the main shell's top bar. */
function BrandMark({ size = 56, radius }) {
  const [failed, setFailed] = React.useState(false);
  const r = radius != null ? radius : Math.round(size * 0.28);
  if (failed) {
    return (
      <div style={{
        width: size, height: size, borderRadius: r,
        background: 'var(--accent)', color: 'var(--on-accent)',
        display: 'grid', placeItems: 'center',
        fontWeight: 700, fontSize: Math.round(size * 0.46), lineHeight: 1,
        boxShadow: '0 12px 24px -10px rgba(31,61,46,0.55)',
      }}>N</div>
    );
  }
  return (
    <img
      src="./icon.png"
      alt="Nutri logo"
      width={size} height={size}
      onError={() => setFailed(true)}
      style={{
        width: size, height: size,
        borderRadius: r,
        display: 'block', objectFit: 'contain',
        background: 'var(--bg)',
      }}
    />
  );
}
window.BrandMark = BrandMark;

(function(){
  const authState = {
    user: null,
    loading: true,
    error: null,
  };
  const listeners = new Set();
  function emit() { listeners.forEach(l => { try { l(); } catch(_) {} }); }

  // ── Remembered login emails (device-local; never passwords) ──
  const EMAILS_KEY = 'nutri_login_emails';
  function rememberEmail(email) {
    try {
      const e = (email || '').trim().toLowerCase();
      if (!e || e.indexOf('@') < 0) return;
      let list = JSON.parse(localStorage.getItem(EMAILS_KEY) || '[]');
      if (!Array.isArray(list)) list = [];
      list = [e, ...list.filter(x => x !== e)].slice(0, 5);
      localStorage.setItem(EMAILS_KEY, JSON.stringify(list));
    } catch (_) {}
  }
  function savedEmails() {
    try { const l = JSON.parse(localStorage.getItem(EMAILS_KEY) || '[]'); return Array.isArray(l) ? l : []; } catch (_) { return []; }
  }
  function clearSavedEmails() { try { localStorage.removeItem(EMAILS_KEY); } catch (_) {} }

  // Wait for Firebase to be ready, then subscribe to auth state.
  function boot() {
    if (!window.firebaseAuth) { setTimeout(boot, 50); return; }
    // Complete any pending redirect sign-in and surface its errors (so the UI never hangs).
    try {
      window.firebaseAuth.getRedirectResult().catch(e => {
        const code = e && e.code;
        if (code && code !== 'auth/no-auth-event' && code !== 'auth/popup-closed-by-user') {
          authState.error = humanError(e); emit();
        }
      });
    } catch (_) {}
    window.firebaseAuth.onAuthStateChanged(async (user) => {
      authState.user = user || null;
      authState.loading = false;
      authState.error = null;
      if (user) {
        try { await window.Cloud.ensureUserDoc(user); } catch (e) { /* offline ok */ }
        try { await (window.Store && window.Store.attachUser && window.Store.attachUser(user)); } catch (e) { console.error(e); }
      } else {
        try { window.Store && window.Store.detachUser && window.Store.detachUser(); } catch (_) {}
      }
      emit();
    });
  }
  boot();

  const Auth = {
    get user()    { return authState.user; },
    get loading() { return authState.loading; },
    get error()   { return authState.error; },
    subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },

    savedEmails, clearSavedEmails,

    async signInWithEmail(email, password) {
      authState.error = null; emit();
      try {
        await window.firebaseAuth.signInWithEmailAndPassword(email.trim(), password);
        rememberEmail(email);
      } catch (e) { authState.error = humanError(e); emit(); throw e; }
    },
    async signUpWithEmail(email, password, displayName) {
      authState.error = null; emit();
      try {
        const cred = await window.firebaseAuth.createUserWithEmailAndPassword(email.trim(), password);
        rememberEmail(email);
        if (cred.user && displayName) {
          const name = (displayName || '').trim();
          if (name) {
            try { await cred.user.updateProfile({ displayName: name }); } catch(_) {}
            try { await window.Cloud.writeProfile(cred.user.uid, { displayName: name, email: cred.user.email || '' }); } catch(_) {}
            // Re-emit so the UI picks up the new displayName immediately
            authState.user = window.firebaseAuth.currentUser;
            try {
              const p = window.Store && window.Store.profile && window.Store.profile();
              if (p) p.displayName = name;
            } catch(_) {}
            emit();
          }
        }
      } catch (e) { authState.error = humanError(e); emit(); throw e; }
    },
    async signInWithGoogle() {
      authState.error = null; emit();
      const provider = window.fbGoogleProvider;
      try { provider.setCustomParameters({ prompt: 'select_account' }); } catch (_) {}
      try {
        await window.firebaseAuth.signInWithPopup(provider);
      } catch (e) {
        const code = e && e.code;
        // User closed the popup / double-tapped → not an error, just reset quietly.
        if (code === 'auth/popup-closed-by-user' || code === 'auth/cancelled-popup-request' || code === 'auth/user-cancelled') {
          authState.error = null; emit(); return;
        }
        // Popup blocked or unsupported (webview / embedded) → fall back to full-page redirect.
        if (code === 'auth/popup-blocked' || code === 'auth/operation-not-supported-in-this-environment' || code === 'auth/web-storage-unsupported') {
          try { await window.firebaseAuth.signInWithRedirect(provider); return; }
          catch (e2) { authState.error = humanError(e2); emit(); throw e2; }
        }
        authState.error = humanError(e); emit(); throw e;
      }
    },
    async sendPasswordReset(email) {
      authState.error = null; emit();
      try { await window.firebaseAuth.sendPasswordResetEmail(email.trim()); }
      catch (e) { authState.error = humanError(e); emit(); throw e; }
    },
    async updateDisplayName(name) {
      const u = window.firebaseAuth.currentUser;
      if (!u) return;
      await u.updateProfile({ displayName: name });
      await window.Cloud.writeProfile(u.uid, { displayName: name });
      // local user object isn't auto-refreshed; manually re-emit
      authState.user = window.firebaseAuth.currentUser;
      emit();
    },
    async signOut() {
      authState.error = null;
      await window.firebaseAuth.signOut();
    },
  };

  function humanError(e) {
    if (!e) return 'Something went wrong.';
    const code = e.code || '';
    const map = {
      'auth/invalid-email': 'That email looks invalid.',
      'auth/user-disabled': 'This account is disabled.',
      'auth/user-not-found': 'No account with that email.',
      'auth/wrong-password': 'Wrong password.',
      'auth/invalid-credential': 'Email or password is incorrect.',
      'auth/email-already-in-use': 'That email is already registered.',
      'auth/weak-password': 'Password must be at least 6 characters.',
      'auth/popup-closed-by-user': 'Sign-in cancelled.',
      'auth/network-request-failed': 'Network error. Check your connection.',
      'auth/too-many-requests': 'Too many attempts. Try again later.',
    };
    return map[code] || (e.message || 'Something went wrong.');
  }

  function useAuth() {
    const [, force] = React.useReducer(x => x + 1, 0);
    React.useEffect(() => Auth.subscribe(force), []);
    return Auth;
  }
  window.Auth = Auth;
  window.useAuth = useAuth;
})();

// ────────────────────────────────────────────────────────────────────
// LoginScreen — Google + Email/Password + Sign-up + Forgot password
// ────────────────────────────────────────────────────────────────────
function LoginScreen() {
  const auth = useAuth();
  const [mode, setMode] = React.useState('login');         // 'login' | 'signup' | 'reset'
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [name, setName] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [info, setInfo] = React.useState('');
  const [emailHints, setEmailHints] = React.useState(() => (auth.savedEmails ? auth.savedEmails() : []));
  const [emailFocus, setEmailFocus] = React.useState(false);
  const _eq = email.trim().toLowerCase();
  const emailMatches = emailHints.filter(e => e !== _eq && e.indexOf(_eq) === 0).slice(0, 5);
  const showEmailSuggest = emailFocus && emailMatches.length > 0;

  async function onSubmit(e) {
    e && e.preventDefault();
    if (busy) return;
    setBusy(true); setInfo('');
    try {
      if (mode === 'login') {
        await auth.signInWithEmail(email, password);
      } else if (mode === 'signup') {
        if (password.length < 6) { setInfo('Password must be at least 6 characters.'); return; }
        await auth.signUpWithEmail(email, password, (name || '').trim());
      } else if (mode === 'reset') {
        await auth.sendPasswordReset(email);
        setInfo('Reset link sent — check your inbox.');
      }
    } catch (_) { /* error rendered via auth.error */ }
    finally { setBusy(false); }
  }

  async function onGoogle() {
    if (busy) return;
    setBusy(true); setInfo('');
    // Watchdog: never let the button hang forever if the popup is silently blocked.
    const watchdog = setTimeout(() => {
      setBusy(false);
      setInfo('Google sign-in is taking too long. If no window opened, allow pop-ups and try again — or use email below.');
    }, 20000);
    try { await auth.signInWithGoogle(); }
    catch (_) {}
    finally { clearTimeout(watchdog); setBusy(false); }
  }

  const card = {
    background: 'var(--surface)',
    border: '1px solid var(--border)',
    borderRadius: 22,
    padding: 24,
    boxShadow: 'var(--shadow-md)',
  };
  const fieldStyle = {
    width: '100%', padding: '11px 14px',
    background: 'var(--surface-2)', border: '1px solid var(--border)',
    borderRadius: 12, fontSize: 14, outline: 'none', font: 'inherit', color: 'var(--text)',
  };
  const primaryBtn = {
    width: '100%', padding: '12px 16px', borderRadius: 12,
    background: busy ? 'var(--muted-2)' : 'var(--accent)', color: 'var(--on-accent)',
    border: 'none', fontSize: 14, fontWeight: 600, cursor: busy ? 'wait' : 'pointer',
    font: 'inherit', boxShadow: '0 6px 14px -8px rgba(31,61,46,0.5)',
  };
  const ghostBtn = {
    width: '100%', padding: '12px 16px', borderRadius: 12,
    background: 'var(--surface)', color: 'var(--text)',
    border: '1px solid var(--border-2)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer',
    font: 'inherit',
    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
  };

  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column',
      justifyContent: 'center', padding: '24px 18px',
      paddingTop: 'calc(var(--safe-top) + 24px)',
      paddingBottom: 'calc(var(--safe-bottom) + 24px)',
      overflowY: 'auto',
      background: 'radial-gradient(80% 60% at 50% -10%, rgba(31,61,46,0.10), transparent 70%), var(--bg)',
    }}>
      <div style={{ width: '100%', maxWidth: 380, margin: '0 auto' }}>
        {/* Brand */}
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <div style={{ display: 'inline-block', margin: '0 auto 12px' }}>
            <BrandMark size={88} radius={20}/>
          </div>
          <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-0.02em' }}>Nutri</div>
          <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>
            {mode === 'signup' ? 'Create your account' : mode === 'reset' ? 'Reset password' : 'Sign in to continue'}
          </div>
        </div>

        <div style={card}>
          <button onClick={onGoogle} disabled={busy} style={ghostBtn}>
            <GoogleGlyph/>
            <span>Continue with Google</span>
          </button>

          <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '18px 0' }}>
            <div style={{ flex: 1, height: 1, background: 'var(--border)' }}/>
            <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600, letterSpacing: '0.06em' }}>OR</div>
            <div style={{ flex: 1, height: 1, background: 'var(--border)' }}/>
          </div>

          <form onSubmit={onSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {mode === 'signup' && (
              <input value={name} onChange={e=>setName(e.target.value)}
                placeholder="Your name (optional)"
                autoComplete="name"
                style={fieldStyle}/>
            )}
            <div style={{ position: 'relative' }}>
              <input value={email} onChange={e=>setEmail(e.target.value)}
                type="email" placeholder="Email" name="email"
                autoComplete="email" inputMode="email" required
                onFocus={()=>setEmailFocus(true)}
                onBlur={()=>setTimeout(()=>setEmailFocus(false), 150)}
                style={fieldStyle}/>
              {showEmailSuggest && (
                <div style={{
                  position: 'absolute', top: 'calc(100% + 4px)', left: 0, right: 0, zIndex: 5,
                  background: 'var(--surface)', border: '1px solid var(--border-2)', borderRadius: 12,
                  boxShadow: 'var(--shadow-lg)', overflow: 'hidden',
                }}>
                  {emailMatches.map(e => (
                    <button key={e} type="button"
                      onMouseDown={(ev)=>{ ev.preventDefault(); setEmail(e); setEmailFocus(false); }}
                      style={{
                        width: '100%', textAlign: 'left', padding: '10px 14px', font: 'inherit',
                        fontSize: 13.5, color: 'var(--text)', background: 'transparent', border: 0,
                        borderBottom: '1px solid var(--border)', cursor: 'pointer',
                        display: 'flex', alignItems: 'center', gap: 8,
                      }}>
                      <span style={{ color: 'var(--muted-2)' }}>✉️</span>{e}
                    </button>
                  ))}
                </div>
              )}
            </div>
            {mode !== 'reset' && (
              <input value={password} onChange={e=>setPassword(e.target.value)}
                type="password" placeholder="Password"
                autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
                required minLength={6}
                style={fieldStyle}/>
            )}
            {(auth.error || info) && (
              <div style={{
                fontSize: 12.5, padding: '8px 12px', borderRadius: 10,
                background: info ? 'var(--c-protein-soft)' : 'rgba(170,51,51,0.08)',
                color: info ? 'var(--text)' : '#A33',
                border: '1px solid ' + (info ? 'rgba(79,168,98,0.35)' : 'rgba(170,51,51,0.25)'),
              }}>{info || auth.error}</div>
            )}
            <button type="submit" disabled={busy} style={primaryBtn}>
              {busy ? 'Working…'
                : mode === 'login'  ? 'Sign in'
                : mode === 'signup' ? 'Create account'
                                    : 'Send reset link'}
            </button>
          </form>

          <div style={{ marginTop: 14, textAlign: 'center', fontSize: 12.5, color: 'var(--muted)' }}>
            {mode === 'login' && (<>
              <button onClick={()=>{setMode('reset'); setInfo('');}} style={textBtn}>Forgot password?</button>
              <span style={{ margin: '0 8px' }}>·</span>
              <button onClick={()=>{setMode('signup'); setInfo('');}} style={textBtn}>Create an account</button>
              {emailHints.length > 0 && (<>
                <span style={{ margin: '0 8px' }}>·</span>
                <button onClick={()=>{ auth.clearSavedEmails && auth.clearSavedEmails(); setEmailHints([]); }} style={textBtn}>Clear saved emails</button>
              </>)}
            </>)}
            {mode === 'signup' && (<>
              Already have an account?{' '}
              <button onClick={()=>{setMode('login'); setInfo('');}} style={textBtn}>Sign in</button>
            </>)}
            {mode === 'reset' && (<>
              <button onClick={()=>{setMode('login'); setInfo('');}} style={textBtn}>Back to sign in</button>
            </>)}
          </div>
        </div>

        <div style={{ marginTop: 16, fontSize: 11, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.55 }}>
          By continuing you accept that your data is stored securely in your Firebase account
          (<code style={{ fontSize: 10 }}>users/&#123;uid&#125;</code>) and is only accessible to you.
        </div>
      </div>
    </div>
  );
}
const textBtn = {
  background: 'transparent', border: 'none', color: 'var(--accent)',
  fontSize: 12.5, fontWeight: 600, cursor: 'pointer', padding: 0, font: 'inherit',
  textDecoration: 'underline',
};
function GoogleGlyph() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true">
      <path d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.7-1.57 2.68-3.88 2.68-6.62z" fill="#4285F4"/>
      <path d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.92v2.34A9 9 0 0 0 9 18z" fill="#34A853"/>
      <path d="M3.97 10.72A5.4 5.4 0 0 1 3.68 9c0-.6.1-1.18.29-1.72V4.94H.92A9 9 0 0 0 0 9c0 1.45.35 2.82.92 4.06l3.05-2.34z" fill="#FBBC05"/>
      <path d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58A9 9 0 0 0 9 0 9 9 0 0 0 .92 4.94l3.05 2.34C4.68 5.16 6.66 3.58 9 3.58z" fill="#EA4335"/>
    </svg>
  );
}

window.LoginScreen = LoginScreen;
