// ── Supabase Client ───────────────────────────────────────────
const SUPABASE_URL = 'https://ugijzojsrhecajikhspg.supabase.co';
const SUPABASE_ANON_KEY = 'sb_publishable_hp4PahtRw80E3wCH_Yr6Bw_gjHF866S';

// Load Supabase dynamically
let _supabase = null;
async function getSupabase() {
  if (_supabase) return _supabase;
  if (!window.supabase) {
    await new Promise((resolve, reject) => {
      const s = document.createElement('script');
      s.src = 'https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/dist/umd/supabase.min.js';
      s.onload = resolve;
      s.onerror = reject;
      document.head.appendChild(s);
    });
  }
  _supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
  return _supabase;
}

const { useState, useEffect, useContext, createContext, useRef } = React;

// ── Auth Context ───────────────────────────────────────────────
const AuthContext = createContext(null);

function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [passes, setPasses] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalMode, setModalMode] = useState('signin');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let sub;
    (async () => {
      const sb = await getSupabase();
      // Restore session
      const { data: { session } } = await sb.auth.getSession();
      if (session?.user) {
        setUser(session.user);
        await loadPasses(session.user.id);
      }
      setLoading(false);
      // Listen for auth changes
      const { data } = sb.auth.onAuthStateChange(async (event, session) => {
        if (session?.user) {
          setUser(session.user);
          await ensureProfile(session.user);
          await loadPasses(session.user.id);
        } else {
          setUser(null);
          setPasses([]);
        }
      });
      sub = data.subscription;
    })();
    return () => sub?.unsubscribe();
  }, []);

  const ensureProfile = async (u) => {
    const sb = await getSupabase();
    const { data } = await sb.from('profiles').select('id').eq('id', u.id).single();
    if (!data) {
      await sb.from('profiles').insert({
        id: u.id,
        name: u.user_metadata?.full_name || u.user_metadata?.name || u.email?.split('@')[0],
        email: u.email,
      });
    }
  };

  const loadPasses = async (userId) => {
    const sb = await getSupabase();
    const { data } = await sb.from('user_passes').select('*').eq('user_id', userId);
    setPasses(data || []);
  };

  const signUp = async (name, email, password) => {
    const sb = await getSupabase();
    const { data, error } = await sb.auth.signUp({ email, password, options: { data: { full_name: name } } });
    if (error) return { error: error.message };
    if (data.user) {
      await ensureProfile(data.user);
    }
    return { success: true };
  };

  const signIn = async (email, password) => {
    const sb = await getSupabase();
    const { error } = await sb.auth.signInWithPassword({ email, password });
    if (error) return { error: error.message };
    return { success: true };
  };

  const signInWithGoogle = async () => {
    const sb = await getSupabase();
    const { error } = await sb.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: window.location.href },
    });
    if (error) return { error: error.message };
    return { success: true };
  };

  const signOut = async () => {
    const sb = await getSupabase();
    await sb.auth.signOut();
    setUser(null);
    setPasses([]);
    setModalOpen(false);
  };

  const addPass = async (pass) => {
    const sb = await getSupabase();
    const { error } = await sb.from('user_passes').upsert({
      user_id: user.id,
      pass_id: pass.id,
      pass_name: pass.name,
      airdropped: false,
    }, { onConflict: 'user_id,pass_id' });
    if (!error) await loadPasses(user.id);
  };

  const hasPass = (passId) => {
    if (!user) return false;
    if (passes.some(p => p.pass_id === 'admin')) return true;
    return passes.some(p => p.pass_id === passId);
  };

  const sendPasswordReset = async (email) => {
    const sb = await getSupabase();
    const { error } = await sb.auth.resetPasswordForEmail(email, {
      redirectTo: window.location.origin + '/index.html',
    });
    return error ? { error: error.message } : { success: true };
  };

  const openModal = (mode = 'signin') => { setModalMode(mode); setModalOpen(true); };
  const closeModal = () => setModalOpen(false);

  const userName = user?.user_metadata?.full_name || user?.user_metadata?.name || user?.email?.split('@')[0] || '';

  if (loading) return null;

  return (
    <AuthContext.Provider value={{ user, passes, userName, signUp, signIn, signInWithGoogle, signOut, addPass, hasPass, sendPasswordReset, modalOpen, modalMode, openModal, closeModal }}>
      {children}
      {modalOpen && <AuthModal />}
    </AuthContext.Provider>
  );
}

function useAuth() { return useContext(AuthContext); }

// ── Auth Modal ─────────────────────────────────────────────────
function AuthModal() {
  const { modalMode, closeModal, signIn, signUp, signInWithGoogle, signOut, user, openModal, sendPasswordReset } = useAuth();
  const [mode, setMode] = useState(modalMode);
  const [form, setForm] = useState({ name: '', email: '', password: '' });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [resetSent, setResetSent] = useState(false);
  const [resetEmail, setResetEmail] = useState('');
  const overlayRef = useRef(null);

  useEffect(() => { setMode(modalMode); }, [modalMode]);

  const handleSubmit = async e => {
    e.preventDefault();
    setError('');
    setLoading(true);
    const result = mode === 'signup'
      ? await signUp(form.name, form.email, form.password)
      : await signIn(form.email, form.password);
    setLoading(false);
    if (result.error) setError(result.error);
    else closeModal();
  };

  const handleGoogle = async () => {
    setError('');
    const result = await signInWithGoogle();
    if (result?.error) setError(result.error);
    // Google redirects, so no closeModal needed
  };

  const handleReset = async e => {
    e.preventDefault();
    setLoading(true);
    const result = await sendPasswordReset(resetEmail);
    setLoading(false);
    if (result.error) setError(result.error);
    else setResetSent(true);
  };

  // Cannot close modal if not logged in
  const canClose = !!user || mode === 'wallet';

  return (
    <div ref={overlayRef} onClick={canClose ? (e => e.target === overlayRef.current && closeModal()) : undefined}
      style={{ position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(0,0,0,0.75)', backdropFilter: 'blur(8px)' }}>
      <div className="liquid-glass" style={{ borderRadius: 24, padding: '36px 32px', width: '100%', maxWidth: 420, position: 'relative' }}>
        {canClose && <button onClick={closeModal} style={{ position: 'absolute', top: 16, right: 16, background: 'none', border: 'none', color: 'rgba(255,255,255,0.4)', fontSize: '1.2rem', cursor: 'pointer', lineHeight: 1 }}>✕</button>}

        {mode === 'wallet' ? (
          <WalletView onClose={closeModal} />
        ) : mode === 'forgot' ? (
          <>
            <button onClick={() => { setMode('signin'); setResetSent(false); setResetEmail(''); }} style={{ background: 'none', border: 'none', color: 'rgba(255,255,255,0.4)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4, fontSize: '0.8rem', marginBottom: 24 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="15 18 9 12 15 6"/></svg> Back to Sign In
            </button>
            <div style={{ textAlign: 'center', marginBottom: 28 }}>
              <img src="uploads/AiFonDeW Owl.png" alt="FonDeW" style={{ height: 52, width: 52, borderRadius: '50%', objectFit: 'cover', objectPosition: 'top', border: '1px solid rgba(255,255,255,0.15)', marginBottom: 12 }} />
              <h2 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: '1.6rem', color: '#fff' }}>Reset Password</h2>
              <p style={{ color: 'rgba(255,255,255,0.4)', fontSize: '0.8rem', marginTop: 6 }}>Enter your email and we'll send reset instructions.</p>
            </div>
            {resetSent ? (
              <div style={{ textAlign: 'center', padding: '16px 0' }}>
                <div style={{ fontSize: '2.5rem', marginBottom: 12 }}>📧</div>
                <p style={{ color: 'rgba(255,255,255,0.6)', fontSize: '0.88rem', lineHeight: 1.6 }}>Check your inbox for a reset link sent to <strong style={{ color: 'var(--accent)' }}>{resetEmail}</strong>.</p>
                <button className="btn-accent" onClick={() => { setMode('signin'); setResetSent(false); }} style={{ marginTop: 24, padding: '10px 28px' }}>Back to Sign In</button>
              </div>
            ) : (
              <form onSubmit={handleReset} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.72rem', color: 'rgba(255,255,255,0.4)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Email Address</label>
                  <input className="glass-input" type="email" placeholder="your@email.com" required value={resetEmail} onChange={e => setResetEmail(e.target.value)} />
                </div>
                {error && <div style={{ fontSize: '0.8rem', color: '#f87171', padding: '8px 12px', background: 'rgba(248,113,113,0.1)', borderRadius: 8 }}>{error}</div>}
                <button type="submit" className="btn-accent" disabled={loading} style={{ width: '100%', justifyContent: 'center', padding: '12px', fontSize: '0.9rem', opacity: loading ? 0.7 : 1 }}>
                  {loading ? 'Sending...' : 'Send Reset Link'}
                </button>
              </form>
            )}
          </>
        ) : (
          <>
            <div style={{ textAlign: 'center', marginBottom: 28 }}>
              <img src="uploads/AiFonDeW Owl.png" alt="FonDeW" style={{ height: 52, width: 52, borderRadius: '50%', objectFit: 'cover', objectPosition: 'top', border: '1px solid rgba(255,255,255,0.15)', marginBottom: 12 }} />
              <h2 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: '1.6rem', color: '#fff' }}>
                {mode === 'signup' ? 'Create Account' : 'Welcome back'}
              </h2>
              <p style={{ color: 'rgba(255,255,255,0.4)', fontSize: '0.8rem', marginTop: 4 }}>
                {mode === 'signup' ? 'Join the FonDeW community' : 'Sign in to access your wallet'}
              </p>
            </div>

            {/* Google Sign-In */}
            <button onClick={handleGoogle}
              style={{ width: '100%', padding: '11px', borderRadius: 10, background: '#fff', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, fontSize: '0.88rem', fontWeight: 500, color: '#333', marginBottom: 16 }}>
              <svg width="18" height="18" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
              Continue with Google
            </button>

            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
              <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.10)' }} />
              <span style={{ fontSize: '0.72rem', color: 'rgba(255,255,255,0.3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>or</span>
              <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.10)' }} />
            </div>

            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {mode === 'signup' && (
                <div>
                  <label style={{ display: 'block', fontSize: '0.72rem', color: 'rgba(255,255,255,0.4)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Name</label>
                  <input className="glass-input" type="text" placeholder="Your name" required value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
                </div>
              )}
              <div>
                <label style={{ display: 'block', fontSize: '0.72rem', color: 'rgba(255,255,255,0.4)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Email</label>
                <input className="glass-input" type="email" placeholder="your@email.com" required value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
              </div>
              <div>
                <label style={{ display: 'block', fontSize: '0.72rem', color: 'rgba(255,255,255,0.4)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Password</label>
                <input className="glass-input" type="password" placeholder="••••••••" required minLength={6} value={form.password} onChange={e => setForm({ ...form, password: e.target.value })} />
              </div>
              {mode === 'signin' && (
                <div style={{ textAlign: 'right', marginTop: -8 }}>
                  <button onClick={() => setMode('forgot')} type="button" style={{ background: 'none', border: 'none', color: 'rgba(255,255,255,0.35)', fontSize: '0.75rem', cursor: 'pointer' }}>Forgot password?</button>
                </div>
              )}
              {error && <div style={{ fontSize: '0.8rem', color: '#f87171', padding: '8px 12px', background: 'rgba(248,113,113,0.1)', borderRadius: 8, border: '1px solid rgba(248,113,113,0.2)' }}>{error}</div>}
              <button type="submit" className="btn-accent" disabled={loading}
                style={{ width: '100%', justifyContent: 'center', padding: '12px', fontSize: '0.9rem', opacity: loading ? 0.7 : 1, marginTop: 4 }}>
                {loading ? 'Please wait...' : mode === 'signup' ? 'Create Account' : 'Sign In'}
              </button>
            </form>

            <div style={{ textAlign: 'center', marginTop: 20 }}>
              <span style={{ fontSize: '0.8rem', color: 'rgba(255,255,255,0.35)' }}>
                {mode === 'signup' ? 'Already have an account? ' : "Don't have an account? "}
              </span>
              <button onClick={() => { setMode(mode === 'signup' ? 'signin' : 'signup'); setError(''); }} type="button"
                style={{ background: 'none', border: 'none', color: 'var(--accent)', fontSize: '0.8rem', cursor: 'pointer', fontWeight: 500 }}>
                {mode === 'signup' ? 'Sign In' : 'Create one'}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ── Wallet View ────────────────────────────────────────────────
function WalletView({ onClose }) {
  const { user, passes, userName, signOut } = useAuth();

  const passLabels = {
    'admin':              { name: 'Admin Pass — All Access', icon: '🛡️', desc: 'Full access to all content on the site' },
    'transmission-vip':   { name: 'Transmission EP Content Pass', icon: '🎵', desc: 'Full access to all Transmission EP content' },
    'fan-club':           { name: 'The Burrow Club Pass', icon: '🦉', desc: 'Full fan club membership & exclusive content' },
    'outta-my-hands':     { name: 'Outta My Hands Content Pass', icon: '✋', desc: 'Exclusive content for Outta My Hands' },
    'sounds-brown-eyes':  { name: 'Brown Eyes Content Pass', icon: '🎶', desc: 'Exclusive Brown Eyes content' },
    'sounds-silhouette':  { name: 'Silhouette Content Pass', icon: '🎶', desc: 'Exclusive Silhouette content' },
    'sounds-take-my-time':{ name: 'Take My Time Content Pass', icon: '🎶', desc: 'Exclusive Take My Time content' },
    'garage-session-1':   { name: 'Garage Session 1 Pass', icon: '🎸', desc: 'Access to Garage Session 1 recording' },
  };

  return (
    <div>
      <div style={{ textAlign: 'center', marginBottom: 28 }}>
        <img src="uploads/AiFonDeW Owl.png" alt="FonDeW" style={{ height: 52, width: 52, borderRadius: '50%', objectFit: 'cover', objectPosition: 'top', border: '1px solid rgba(255,255,255,0.15)', marginBottom: 12 }} />
        <h2 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: '1.5rem', color: '#fff' }}>Your Wallet</h2>
        <p style={{ color: 'rgba(255,255,255,0.4)', fontSize: '0.8rem', marginTop: 4 }}>Welcome, {userName}</p>
      </div>

      {passes.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '24px 0', color: 'rgba(255,255,255,0.3)', fontSize: '0.85rem' }}>
          <div style={{ fontSize: '2rem', marginBottom: 10 }}>🎫</div>
          No passes yet. Purchase a pass to unlock exclusive content.
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 20 }}>
          {passes.map(p => {
            const info = passLabels[p.pass_id] || { name: p.pass_name || p.pass_id, icon: '🎫', desc: '' };
            return (
              <div key={p.pass_id} className="liquid-glass" style={{ borderRadius: 12, padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{ fontSize: '1.4rem' }}>{info.icon}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 500, fontSize: '0.88rem', color: '#fff' }}>{info.name}</div>
                  <div style={{ fontSize: '0.72rem', color: 'rgba(255,255,255,0.35)', marginTop: 2 }}>{info.desc}</div>
                </div>
                <div style={{ fontSize: '0.65rem', color: 'var(--accent)', fontWeight: 600, padding: '3px 10px', borderRadius: 9999, border: '1px solid rgba(201,168,76,0.3)', background: 'rgba(201,168,76,0.08)' }}>
                  {p.airdropped ? '✈️ AIRDROP' : 'ACTIVE'}
                </div>
              </div>
            );
          })}
        </div>
      )}

      <button onClick={async () => { await signOut(); onClose(); }}
        style={{ width: '100%', padding: '10px', borderRadius: 9999, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)', color: 'rgba(255,255,255,0.5)', fontSize: '0.82rem', cursor: 'pointer', fontWeight: 500, marginTop: 8 }}>
        Sign Out
      </button>
    </div>
  );
}

Object.assign(window, { AuthProvider, useAuth, AuthModal, WalletView });
