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

/* ============ THEME ============ */
const ThemeContext = createContext({ theme: 'dark', toggle: () => {} });

function applyTheme(theme) {
  const root = document.documentElement;
  if (theme === 'light') {
    root.style.setProperty('--bg', '#f4f1e8');
    root.style.setProperty('--bg2', '#ebe6d6');
    root.style.setProperty('--card', '#ffffff');
    root.style.setProperty('--card2', '#f9f6ec');
    root.style.setProperty('--border', '#d8d2bd');
    root.style.setProperty('--border2', '#e5e0cd');
    root.style.setProperty('--gold', '#a8862e');
    root.style.setProperty('--gold2', '#c9a84c');
    root.style.setProperty('--green', '#1a8f5a');
    root.style.setProperty('--red', '#c93838');
    root.style.setProperty('--blue', '#2563eb');
    root.style.setProperty('--purple', '#7c3aed');
    root.style.setProperty('--text', '#1a2032');
    root.style.setProperty('--text2', '#3a4458');
    root.style.setProperty('--muted', '#7a8294');
  } else {
    root.style.setProperty('--bg', '#14202f');
    root.style.setProperty('--bg2', '#1a2840');
    root.style.setProperty('--card', '#1e2f44');
    root.style.setProperty('--card2', '#243650');
    root.style.setProperty('--border', '#2a3f58');
    root.style.setProperty('--border2', '#1e3050');
    root.style.setProperty('--gold', '#c9a84c');
    root.style.setProperty('--gold2', '#e8c56a');
    root.style.setProperty('--green', '#3dd68c');
    root.style.setProperty('--red', '#f06b6b');
    root.style.setProperty('--blue', '#5ba3f5');
    root.style.setProperty('--purple', '#9b7fe8');
    root.style.setProperty('--text', '#d4e4f5');
    root.style.setProperty('--text2', '#a0b8d0');
    root.style.setProperty('--muted', '#5a7a95');
  }
}

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState(() => localStorage.getItem('iws_theme') || 'dark');
  useEffect(() => { applyTheme(theme); localStorage.setItem('iws_theme', theme); }, [theme]);
  return <ThemeContext.Provider value={{ theme, toggle: () => setTheme(t => t === 'dark' ? 'light' : 'dark') }}>{children}</ThemeContext.Provider>;
}
const useTheme = () => useContext(ThemeContext);

/* ============ AUTH ============ */
const AuthContext = createContext({ user: null, signIn: () => {}, signOut: () => {} });

function AuthProvider({ children }) {
  const [user, setUser] = useState(() => {
    try { return JSON.parse(localStorage.getItem('iws_user') || 'null'); } catch { return null; }
  });
  const signIn = (u) => { setUser(u); localStorage.setItem('iws_user', JSON.stringify(u)); };
  const signOut = () => { setUser(null); localStorage.removeItem('iws_user'); };
  return <AuthContext.Provider value={{ user, signIn, signOut }}>{children}</AuthContext.Provider>;
}
const useAuth = () => useContext(AuthContext);

function AuthModal({ open, onClose, lang }) {
  const { signIn } = useAuth();
  const [mode, setMode] = useState('signin');
  const [form, setForm] = useState({ email: '', password: '', name: '' });
  const [err, setErr] = useState('');

  if (!open) return null;

  const t = lang === 'es' ? {
    signin: 'Iniciar Sesión', signup: 'Crear Cuenta',
    email: 'Correo electrónico', password: 'Contraseña', name: 'Nombre completo',
    google: 'Continuar con Google', apple: 'Continuar con Apple', github: 'Continuar con GitHub',
    or: 'o', noAcc: '¿No tienes cuenta?', hasAcc: '¿Ya tienes cuenta?',
    create: 'Regístrate', login: 'Inicia sesión',
    submit: 'Continuar', terms: 'Al continuar, aceptas los Términos y la Política de Privacidad.',
    welcome: 'Bienvenido a Inside Wall Street', sub: 'Guarda tu perfil, watchlist y preferencias',
    invalid: 'Correo o contraseña inválidos',
  } : {
    signin: 'Sign In', signup: 'Create Account',
    email: 'Email address', password: 'Password', name: 'Full name',
    google: 'Continue with Google', apple: 'Continue with Apple', github: 'Continue with GitHub',
    or: 'or', noAcc: "Don't have an account?", hasAcc: 'Already have an account?',
    create: 'Sign up', login: 'Sign in',
    submit: 'Continue', terms: 'By continuing, you agree to the Terms and Privacy Policy.',
    welcome: 'Welcome to Inside Wall Street', sub: 'Save your profile, watchlist and preferences',
    invalid: 'Invalid email or password',
  };

  const handleSocial = (provider) => {
    const fakeUser = {
      id: 'usr_' + Math.random().toString(36).slice(2,10),
      email: provider === 'google' ? 'usuario@gmail.com' : provider === 'apple' ? 'usuario@icloud.com' : 'usuario@github.com',
      name: provider === 'google' ? 'Usuario Google' : provider === 'apple' ? 'Usuario Apple' : 'Usuario GitHub',
      provider,
      avatar: null,
      createdAt: Date.now(),
    };
    signIn(fakeUser);
    onClose();
  };

  const handleEmail = (e) => {
    e.preventDefault();
    setErr('');
    if (!form.email.includes('@') || form.password.length < 6) {
      setErr(t.invalid); return;
    }
    if (mode === 'signup' && !form.name.trim()) { setErr('Nombre requerido'); return; }
    signIn({
      id: 'usr_' + Math.random().toString(36).slice(2,10),
      email: form.email,
      name: mode === 'signup' ? form.name : form.email.split('@')[0],
      provider: 'email',
      avatar: null,
      createdAt: Date.now(),
    });
    onClose();
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(4px)',
      zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 14,
        width: '100%', maxWidth: 400, padding: 32, position: 'relative',
        boxShadow: '0 20px 60px rgba(0,0,0,0.4)',
      }}>
        <button onClick={onClose} style={{
          position: 'absolute', top: 14, right: 14, background: 'transparent', border: 'none',
          color: 'var(--muted)', cursor: 'pointer', padding: 4, borderRadius: 6,
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>

        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 16 }}>
          <img src="uploads/logo-1777404535649.jpeg" style={{ width: 48, height: 48, borderRadius: 8 }} alt="" />
        </div>
        <h2 style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 800, fontSize: 20, color: 'var(--text)', textAlign: 'center', marginBottom: 4 }}>
          {mode === 'signin' ? t.welcome : t.signup}
        </h2>
        <p style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center', marginBottom: 20 }}>{t.sub}</p>

        {/* Social buttons */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 18 }}>
          <button onClick={() => handleSocial('google')} style={socialBtn}>
            <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.84A10.997 10.997 0 0012 23z"/><path fill="#FBBC05" d="M5.84 14.09a6.6 6.6 0 010-4.18V7.07H2.18a10.998 10.998 0 000 9.86l3.66-2.84z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.46 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>
            {t.google}
          </button>
          <button onClick={() => handleSocial('apple')} style={socialBtn}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09l.01-.01zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/></svg>
            {t.apple}
          </button>
          <button onClick={() => handleSocial('github')} style={socialBtn}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .3a12 12 0 00-3.79 23.39c.6.11.82-.26.82-.58v-2.03c-3.34.73-4.04-1.6-4.04-1.6-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.08-.73.08-.73 1.2.09 1.84 1.24 1.84 1.24 1.07 1.83 2.81 1.3 3.5.99.11-.78.42-1.31.76-1.61-2.66-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.13-.3-.54-1.52.12-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 016 0c2.28-1.55 3.29-1.23 3.29-1.23.66 1.66.25 2.88.12 3.18a4.65 4.65 0 011.23 3.22c0 4.61-2.81 5.62-5.48 5.92.43.37.81 1.1.81 2.22v3.29c0 .32.21.7.82.58A12 12 0 0012 .3"/></svg>
            {t.github}
          </button>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18, color: 'var(--muted)', fontSize: 11 }}>
          <div style={{ flex: 1, height: 1, background: 'var(--border)' }}></div>
          <span>{t.or}</span>
          <div style={{ flex: 1, height: 1, background: 'var(--border)' }}></div>
        </div>

        <form onSubmit={handleEmail} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {mode === 'signup' && (
            <input className="inp" type="text" placeholder={t.name}
              value={form.name} onChange={e => setForm({...form, name: e.target.value})} />
          )}
          <input className="inp" type="email" placeholder={t.email} required
            value={form.email} onChange={e => setForm({...form, email: e.target.value})} />
          <input className="inp" type="password" placeholder={t.password} required
            value={form.password} onChange={e => setForm({...form, password: e.target.value})} />
          {err && <div style={{ fontSize: 12, color: 'var(--red)' }}>{err}</div>}
          <button type="submit" className="btn btn-gold" style={{ justifyContent: 'center', padding: '10px', fontWeight: 700, fontFamily: 'Barlow, sans-serif', letterSpacing: '0.04em' }}>
            {mode === 'signin' ? t.signin : t.create}
          </button>
        </form>

        <div style={{ marginTop: 14, textAlign: 'center', fontSize: 12, color: 'var(--muted)' }}>
          {mode === 'signin' ? t.noAcc : t.hasAcc}{' '}
          <button onClick={() => setMode(m => m === 'signin' ? 'signup' : 'signin')} style={{ background: 'none', border: 'none', color: 'var(--gold)', cursor: 'pointer', fontWeight: 600 }}>
            {mode === 'signin' ? t.create : t.login}
          </button>
        </div>
        <div style={{ marginTop: 12, fontSize: 10, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.4 }}>{t.terms}</div>
      </div>
    </div>
  );
}

const socialBtn = {
  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
  padding: '10px 16px', border: '1px solid var(--border)', borderRadius: 8,
  background: 'var(--bg2)', color: 'var(--text)', fontSize: 13, fontWeight: 500,
  cursor: 'pointer', fontFamily: 'DM Sans, sans-serif', transition: 'all 0.15s',
};

function UserMenu({ lang, onOpenAuth }) {
  const { user, signOut } = useAuth();
  const { theme, toggle } = useTheme();
  const [open, setOpen] = useState(false);

  const t = lang === 'es' ? { signin:'Iniciar Sesión', signup:'Registrarse', logout:'Cerrar Sesión', settings:'Configuración', watchlist:'Mi Watchlist', profile:'Mi Perfil', dark:'Tema Oscuro', light:'Tema Claro' } : { signin:'Sign In', signup:'Sign Up', logout:'Sign Out', settings:'Settings', watchlist:'My Watchlist', profile:'My Profile', dark:'Dark Theme', light:'Light Theme' };

  if (!user) {
    return (
      <button onClick={onOpenAuth} className="btn btn-gold btn-sm" style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, letterSpacing: '0.05em' }}>
        {t.signin}
      </button>
    );
  }

  const initial = (user.name || user.email).charAt(0).toUpperCase();

  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: 'flex', alignItems: 'center', gap: 8, background: 'transparent',
        border: '1px solid var(--border)', borderRadius: 99, padding: '4px 12px 4px 4px',
        cursor: 'pointer', color: 'var(--text)',
      }}>
        <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--gold)', color: '#1a1000', fontWeight: 700, fontFamily: 'Barlow, sans-serif', fontSize: 13, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {initial}
        </div>
        <span className="hide-mobile" style={{ fontSize: 12, maxWidth: 100, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.name || user.email}</span>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="6 9 12 15 18 9"/></svg>
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 99 }} />
          <div style={{
            position: 'absolute', top: '110%', right: 0, minWidth: 220,
            background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10,
            boxShadow: '0 10px 30px rgba(0,0,0,0.3)', zIndex: 100, overflow: 'hidden',
          }}>
            <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)' }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>{user.name}</div>
              <div style={{ fontSize: 11, color: 'var(--muted)' }}>{user.email}</div>
              {user.provider !== 'email' && (
                <span className="badge badge-blue" style={{ marginTop: 6, fontSize: 9, textTransform: 'uppercase' }}>{user.provider}</span>
              )}
            </div>
            <div style={{ padding: '6px 0' }}>
              <button onClick={() => { toggle(); }} style={menuItem}>
                {theme === 'dark' ? '☀️' : '🌙'} {theme === 'dark' ? t.light : t.dark}
              </button>
              <button style={menuItem}>⭐ {t.watchlist}</button>
              <button style={menuItem}>⚙️ {t.settings}</button>
            </div>
            <div style={{ borderTop: '1px solid var(--border)', padding: '6px 0' }}>
              <button onClick={() => { signOut(); setOpen(false); }} style={{ ...menuItem, color: 'var(--red)' }}>
                ↪ {t.logout}
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

const menuItem = {
  display: 'block', width: '100%', textAlign: 'left',
  padding: '9px 16px', background: 'transparent', border: 'none',
  color: 'var(--text2)', cursor: 'pointer', fontSize: 13,
  fontFamily: 'DM Sans, sans-serif',
};

function ThemeToggle() {
  const { theme, toggle } = useTheme();
  return (
    <button onClick={toggle} className="btn btn-ghost btn-sm" title={theme === 'dark' ? 'Cambiar a claro' : 'Cambiar a oscuro'} style={{ padding: 6 }}>
      {theme === 'dark' ? (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
      ) : (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>
      )}
    </button>
  );
}

Object.assign(window, { ThemeProvider, useTheme, AuthProvider, useAuth, AuthModal, UserMenu, ThemeToggle });
