// DramaScope — auth, i18n, ratings, reactions
// Exposes: useAuth, useI18n, LANGUAGES, AuthModal, AuthContext, I18nContext
//          LanguageMenu, AuthButtons, AvatarMenu, GuestGate
//          DramaRatingPanel, DramaReactionPanel
//          ActorReactionPanel, ActorTraitsPanel

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

// ── I18N ──────────────────────────────────────────────────────────────────────
const LANGUAGES = [
{ code: 'en', short: 'EN', label: 'English' },
{ code: 'es', short: 'ES', label: 'Español' },
{ code: 'ru', short: 'RU', label: 'Русский' },
{ code: 'de', short: 'DE', label: 'Deutsch' },
{ code: 'uk', short: 'UK', label: 'Українська' }];


// Translation dictionary. Missing keys fall back to English (the key itself).
const I18N = {
  en: {},
  es: {
    'Home': 'Inicio', 'Chinese Dramas': 'C-Dramas', 'Chinese Actors': 'Actores Chinos',
    'AI Picks': 'Selección IA', 'Rankings': 'Rankings', 'News': 'Noticias',
    'Community': 'Comunidad', 'Watchlist': 'Lista', 'Profile': 'Perfil',
    'Sign In': 'Iniciar sesión', 'Join Free': 'Regístrate', 'Sign Up': 'Registrarse',
    'Log Out': 'Cerrar sesión', 'My Profile': 'Mi perfil', 'My Library': 'Mi biblioteca',
    'My Ratings': 'Mis valoraciones', 'My Reactions': 'Mis reacciones',
    'My Lists': 'Mis listas', 'Account Settings': 'Configuración', 'Language': 'Idioma',
    'Upgrade to Premium': 'Actualizar a Premium',
    'Discover Chinese Dramas & Actors': 'Descubre C-Dramas y actores chinos',
    'Explore C-Dramas': 'Explorar C-Dramas', 'Browse Chinese Actors': 'Ver actores chinos',
    'Get AI Recommendations': 'Recomendaciones IA',
    'Sign in to rate': 'Inicia sesión para valorar',
    'Sign in to react': 'Inicia sesión para reaccionar',
    'Sign in to rate this drama': 'Inicia sesión para valorar este drama',
    'Sign in to react to this actor': 'Inicia sesión para reaccionar a este actor',
    'Create an account to save this drama': 'Crea una cuenta para guardar este drama',
    'Create an account to save to your watchlist': 'Crea una cuenta para guardar en tu lista',
    'Join free to follow actors': 'Regístrate gratis para seguir actores',
    'Join free to unlock your C-Drama library': 'Únete gratis para desbloquear tu biblioteca de C-Dramas',
    'Want to see more? Create a free account.': '¿Quieres ver más? Crea una cuenta gratis.',
    'Sign up to unlock more details.': 'Regístrate para más detalles.',
    'Create an account to access full actor profiles.': 'Crea una cuenta para perfiles completos.',
    'Register to see full drama details, ratings, reactions, and recommendations.': 'Regístrate para ver detalles completos, valoraciones y recomendaciones.',
    'Join free to save dramas, follow actors, and get personalized AI recommendations.': 'Únete gratis para guardar dramas, seguir actores y obtener recomendaciones personalizadas.',
    'Sign in to rate, react, comment, and build your C-Drama library.': 'Inicia sesión para valorar, reaccionar y comentar.',
    'Create your free account to unlock fandom rankings, watchlists, reviews, and AI picks.': 'Crea tu cuenta gratis para desbloquear rankings, listas, reseñas y selección IA.',
    'Sign Up to See More': 'Regístrate para ver más', 'Create Free Account': 'Crear cuenta gratis',
    'Unlock Full Profile': 'Desbloquear perfil', 'Unlock More Details': 'Más detalles',
    'Sign In to Continue': 'Inicia sesión para continuar', 'Register to Save': 'Regístrate para guardar',
    'Register to Rate': 'Regístrate para valorar', 'Register to React': 'Regístrate para reaccionar',
    'Your Ratings': 'Tus valoraciones', 'Your Reactions': 'Tus reacciones',
    'Overall Rating': 'Valoración general', 'OST Rating': 'Banda sonora',
    'Side Characters Rating': 'Personajes secundarios', 'Chemistry Score': 'Química',
    'Recommendation Score': 'Recomendación', 'Rewatch Score': 'Volver a ver',
    'Rate this drama': 'Valorar este drama', 'React to this drama': 'Reacciona a este drama',
    'React to this actor': 'Reacciona a este actor', 'Vote on traits': 'Vota rasgos',
    'Agree': 'De acuerdo', 'Disagree': 'En desacuerdo',
    'Welcome back': 'Bienvenido', 'Create your account': 'Crea tu cuenta',
    'Email': 'Correo', 'Password': 'Contraseña', 'Display name': 'Nombre',
    'Already have an account?': '¿Ya tienes cuenta?', 'Need an account?': '¿Necesitas cuenta?',
    'Continue': 'Continuar', 'Cancel': 'Cancelar',
    'Follow': 'Seguir', 'Following': 'Siguiendo'
  },
  ru: {
    'Home': 'Главная', 'Chinese Dramas': 'Дорамы Китая', 'Chinese Actors': 'Актёры',
    'AI Picks': 'AI Подбор', 'Rankings': 'Рейтинги', 'News': 'Новости',
    'Community': 'Сообщество', 'Watchlist': 'Избранное', 'Profile': 'Профиль',
    'Sign In': 'Войти', 'Join Free': 'Регистрация', 'Sign Up': 'Создать аккаунт',
    'Log Out': 'Выйти', 'My Profile': 'Мой профиль', 'My Library': 'Моя библиотека',
    'My Ratings': 'Мои оценки', 'My Reactions': 'Мои реакции',
    'My Lists': 'Мои списки', 'Account Settings': 'Настройки', 'Language': 'Язык',
    'Upgrade to Premium': 'Премиум',
    'Discover Chinese Dramas & Actors': 'Открой китайские дорамы и актёров',
    'Explore C-Dramas': 'Смотреть дорамы', 'Browse Chinese Actors': 'Актёры Китая',
    'Get AI Recommendations': 'AI рекомендации',
    'Sign in to rate': 'Войдите, чтобы оценить',
    'Sign in to react': 'Войдите, чтобы оставить реакцию',
    'Sign in to rate this drama': 'Войдите, чтобы оценить эту дораму',
    'Sign in to react to this actor': 'Войдите, чтобы оставить реакцию',
    'Create an account to save this drama': 'Создайте аккаунт, чтобы сохранить',
    'Create an account to save to your watchlist': 'Создайте аккаунт, чтобы добавить в избранное',
    'Join free to follow actors': 'Регистрация — чтобы подписываться на актёров',
    'Join free to unlock your C-Drama library': 'Регистрация — чтобы получить доступ к библиотеке',
    'Want to see more? Create a free account.': 'Хотите видеть больше? Создайте бесплатный аккаунт.',
    'Sign up to unlock more details.': 'Зарегистрируйтесь, чтобы увидеть больше.',
    'Create an account to access full actor profiles.': 'Создайте аккаунт, чтобы получить доступ к полным профилям актёров.',
    'Register to see full drama details, ratings, reactions, and recommendations.': 'Зарегистрируйтесь, чтобы видеть полные детали, оценки и рекомендации.',
    'Join free to save dramas, follow actors, and get personalized AI recommendations.': 'Регистрация — сохраняйте дорамы, подписывайтесь на актёров и получайте персональные рекомендации.',
    'Sign in to rate, react, comment, and build your C-Drama library.': 'Войдите, чтобы оценивать, реагировать и комментировать.',
    'Create your free account to unlock fandom rankings, watchlists, reviews, and AI picks.': 'Создайте бесплатный аккаунт — рейтинги, списки, рецензии и AI подбор.',
    'Sign Up to See More': 'Зарегистрируйтесь', 'Create Free Account': 'Создать аккаунт',
    'Unlock Full Profile': 'Открыть профиль', 'Unlock More Details': 'Подробнее',
    'Sign In to Continue': 'Войти', 'Register to Save': 'Регистрация',
    'Register to Rate': 'Регистрация', 'Register to React': 'Регистрация',
    'Your Ratings': 'Ваши оценки', 'Your Reactions': 'Ваши реакции',
    'Overall Rating': 'Общая оценка', 'OST Rating': 'Саундтрек',
    'Side Characters Rating': 'Второстепенные', 'Chemistry Score': 'Химия',
    'Recommendation Score': 'Рекомендация', 'Rewatch Score': 'Пересмотреть',
    'Rate this drama': 'Оценить дораму', 'React to this drama': 'Реакция на дораму',
    'React to this actor': 'Реакция на актёра', 'Vote on traits': 'Голосовать за черты',
    'Agree': 'Согласен', 'Disagree': 'Не согласен',
    'Welcome back': 'С возвращением', 'Create your account': 'Создайте аккаунт',
    'Email': 'Email', 'Password': 'Пароль', 'Display name': 'Имя',
    'Already have an account?': 'Уже есть аккаунт?', 'Need an account?': 'Нет аккаунта?',
    'Continue': 'Продолжить', 'Cancel': 'Отмена',
    'Follow': 'Подписаться', 'Following': 'Вы подписаны'
  },
  de: {
    'Home': 'Startseite', 'Chinese Dramas': 'C-Dramen', 'Chinese Actors': 'Chinesische Schauspieler',
    'AI Picks': 'KI-Empfehlungen', 'Rankings': 'Rankings', 'News': 'News',
    'Community': 'Community', 'Watchlist': 'Merkliste', 'Profile': 'Profil',
    'Sign In': 'Anmelden', 'Join Free': 'Kostenlos beitreten', 'Sign Up': 'Registrieren',
    'Log Out': 'Abmelden', 'My Profile': 'Mein Profil', 'My Library': 'Meine Bibliothek',
    'My Ratings': 'Meine Bewertungen', 'My Reactions': 'Meine Reaktionen',
    'My Lists': 'Meine Listen', 'Account Settings': 'Einstellungen', 'Language': 'Sprache',
    'Upgrade to Premium': 'Premium',
    'Discover Chinese Dramas & Actors': 'Entdecke chinesische Dramen & Schauspieler',
    'Explore C-Dramas': 'C-Dramen erkunden', 'Browse Chinese Actors': 'Schauspieler entdecken',
    'Get AI Recommendations': 'KI-Empfehlungen',
    'Sign in to rate': 'Anmelden zum Bewerten',
    'Sign in to react': 'Anmelden zum Reagieren',
    'Sign in to rate this drama': 'Anmelden, um dieses Drama zu bewerten',
    'Sign in to react to this actor': 'Anmelden, um zu reagieren',
    'Create an account to save this drama': 'Konto erstellen zum Speichern',
    'Create an account to save to your watchlist': 'Konto erstellen für Merkliste',
    'Join free to follow actors': 'Kostenlos beitreten, um Schauspielern zu folgen',
    'Join free to unlock your C-Drama library': 'Kostenlos beitreten und Bibliothek freischalten',
    'Want to see more? Create a free account.': 'Mehr sehen? Erstelle ein kostenloses Konto.',
    'Sign up to unlock more details.': 'Registriere dich für mehr Details.',
    'Create an account to access full actor profiles.': 'Konto erstellen für vollständige Profile.',
    'Register to see full drama details, ratings, reactions, and recommendations.': 'Registriere dich für volle Drama-Details, Bewertungen und Empfehlungen.',
    'Join free to save dramas, follow actors, and get personalized AI recommendations.': 'Kostenlos beitreten — Dramen speichern, Schauspielern folgen und personalisierte KI-Empfehlungen.',
    'Sign in to rate, react, comment, and build your C-Drama library.': 'Anmelden zum Bewerten, Reagieren und Kommentieren.',
    'Create your free account to unlock fandom rankings, watchlists, reviews, and AI picks.': 'Erstelle dein kostenloses Konto für Rankings, Listen und KI-Empfehlungen.',
    'Sign Up to See More': 'Für mehr registrieren', 'Create Free Account': 'Konto erstellen',
    'Unlock Full Profile': 'Profil freischalten', 'Unlock More Details': 'Details freischalten',
    'Sign In to Continue': 'Weiter mit Login', 'Register to Save': 'Zum Speichern',
    'Register to Rate': 'Zum Bewerten', 'Register to React': 'Zum Reagieren',
    'Your Ratings': 'Deine Bewertungen', 'Your Reactions': 'Deine Reaktionen',
    'Overall Rating': 'Gesamtbewertung', 'OST Rating': 'Soundtrack',
    'Side Characters Rating': 'Nebenfiguren', 'Chemistry Score': 'Chemie',
    'Recommendation Score': 'Empfehlung', 'Rewatch Score': 'Wieder ansehen',
    'Rate this drama': 'Drama bewerten', 'React to this drama': 'Auf Drama reagieren',
    'React to this actor': 'Auf Schauspieler reagieren', 'Vote on traits': 'Über Eigenschaften abstimmen',
    'Agree': 'Zustimmen', 'Disagree': 'Ablehnen',
    'Welcome back': 'Willkommen zurück', 'Create your account': 'Konto erstellen',
    'Email': 'E-Mail', 'Password': 'Passwort', 'Display name': 'Anzeigename',
    'Already have an account?': 'Schon ein Konto?', 'Need an account?': 'Konto benötigt?',
    'Continue': 'Weiter', 'Cancel': 'Abbrechen',
    'Follow': 'Folgen', 'Following': 'Folgt'
  },
  uk: {
    'Home': 'Головна', 'Chinese Dramas': 'Дорами Китаю', 'Chinese Actors': 'Актори',
    'AI Picks': 'AI Підбір', 'Rankings': 'Рейтинги', 'News': 'Новини',
    'Community': 'Спільнота', 'Watchlist': 'Список', 'Profile': 'Профіль',
    'Sign In': 'Увійти', 'Join Free': 'Реєстрація', 'Sign Up': 'Створити обліковий запис',
    'Log Out': 'Вийти', 'My Profile': 'Мій профіль', 'My Library': 'Моя бібліотека',
    'My Ratings': 'Мої оцінки', 'My Reactions': 'Мої реакції',
    'My Lists': 'Мої списки', 'Account Settings': 'Налаштування', 'Language': 'Мова',
    'Upgrade to Premium': 'Преміум',
    'Discover Chinese Dramas & Actors': 'Відкрий китайські дорами та акторів',
    'Explore C-Dramas': 'Дивитися дорами', 'Browse Chinese Actors': 'Актори Китаю',
    'Get AI Recommendations': 'AI рекомендації',
    'Sign in to rate': 'Увійдіть, щоб оцінити',
    'Sign in to react': 'Увійдіть, щоб залишити реакцію',
    'Sign in to rate this drama': 'Увійдіть, щоб оцінити дораму',
    'Sign in to react to this actor': 'Увійдіть, щоб залишити реакцію',
    'Create an account to save this drama': 'Створіть обліковий запис, щоб зберегти',
    'Create an account to save to your watchlist': 'Створіть обліковий запис, щоб додати',
    'Join free to follow actors': 'Реєструйтеся безкоштовно, щоб підписатися на акторів',
    'Join free to unlock your C-Drama library': 'Реєструйтеся, щоб отримати доступ до бібліотеки',
    'Want to see more? Create a free account.': 'Хочете більше? Створіть безкоштовний обліковий запис.',
    'Sign up to unlock more details.': 'Зареєструйтеся, щоб побачити більше.',
    'Create an account to access full actor profiles.': 'Створіть обліковий запис для повних профілів.',
    'Register to see full drama details, ratings, reactions, and recommendations.': 'Зареєструйтеся для повних деталей дорами, оцінок та рекомендацій.',
    'Join free to save dramas, follow actors, and get personalized AI recommendations.': 'Реєстрація — зберігайте дорами, підписуйтеся на акторів і отримуйте персональні рекомендації.',
    'Sign in to rate, react, comment, and build your C-Drama library.': 'Увійдіть, щоб оцінювати, реагувати та коментувати.',
    'Create your free account to unlock fandom rankings, watchlists, reviews, and AI picks.': 'Створіть безкоштовний обліковий запис — рейтинги, списки, рецензії та AI підбір.',
    'Sign Up to See More': 'Зареєструйтеся', 'Create Free Account': 'Створити обліковий запис',
    'Unlock Full Profile': 'Відкрити профіль', 'Unlock More Details': 'Детальніше',
    'Sign In to Continue': 'Увійти', 'Register to Save': 'Реєстрація',
    'Register to Rate': 'Реєстрація', 'Register to React': 'Реєстрація',
    'Your Ratings': 'Ваші оцінки', 'Your Reactions': 'Ваші реакції',
    'Overall Rating': 'Загальна оцінка', 'OST Rating': 'Саундтрек',
    'Side Characters Rating': 'Другорядні', 'Chemistry Score': 'Хімія',
    'Recommendation Score': 'Рекомендація', 'Rewatch Score': 'Передивитися',
    'Rate this drama': 'Оцінити дораму', 'React to this drama': 'Реакція на дораму',
    'React to this actor': 'Реакція на актора', 'Vote on traits': 'Голосувати за риси',
    'Agree': 'Згоден', 'Disagree': 'Не згоден',
    'Welcome back': 'Раді бачити знову', 'Create your account': 'Створіть обліковий запис',
    'Email': 'Email', 'Password': 'Пароль', 'Display name': 'Імʼя',
    'Already have an account?': 'Вже маєте обліковий запис?', 'Need an account?': 'Немає облікового запису?',
    'Continue': 'Продовжити', 'Cancel': 'Скасувати',
    'Follow': 'Підписатися', 'Following': 'Підписані'
  }
};

const I18nContext = createContext({ lang: 'en', setLang: () => {}, t: (s) => s });

function useI18n() {return useContext(I18nContext);}

function I18nProvider({ children }) {
  const [lang, setLang] = useState(() => localStorage.getItem('ds_lang') || 'en');
  useEffect(() => {localStorage.setItem('ds_lang', lang);document.documentElement.lang = lang;}, [lang]);
  const t = (key) => I18N[lang] && I18N[lang][key] || key;
  return <I18nContext.Provider value={{ lang, setLang, t }}>{children}</I18nContext.Provider>;
}

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

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

function AuthProvider({ children }) {
  const [user, setUser] = useState(() => {try {return JSON.parse(localStorage.getItem('ds_auth_user'));} catch {return null;}});
  const [modalMode, setModalMode] = useState(null); // null | 'signin' | 'signup'

  useEffect(() => {user ? localStorage.setItem('ds_auth_user', JSON.stringify(user)) : localStorage.removeItem('ds_auth_user');}, [user]);

  const signIn = ({ email, password }) => {
    // Mock: any email+password works. Look up stored display name if matches.
    const stored = JSON.parse(localStorage.getItem(`ds_credentials_${email}`) || 'null');
    const name = stored?.name || email.split('@')[0];
    setUser({ email, name, joinedAt: stored?.joinedAt || new Date().toISOString() });
    setModalMode(null);
  };
  const signUp = ({ email, name, password }) => {
    localStorage.setItem(`ds_credentials_${email}`, JSON.stringify({ name, joinedAt: new Date().toISOString() }));
    setUser({ email, name, joinedAt: new Date().toISOString() });
    setModalMode(null);
  };
  const signOut = () => setUser(null);
  const openSignIn = () => setModalMode('signin');
  const openSignUp = () => setModalMode('signup');
  const closeModal = () => setModalMode(null);

  return (
    <AuthContext.Provider value={{ user, signIn, signUp, signOut, openSignIn, openSignUp }}>
      {children}
      {modalMode && <AuthModal mode={modalMode} setMode={setModalMode} onClose={closeModal} />}
    </AuthContext.Provider>);

}

function AuthModal({ mode, setMode, onClose }) {
  const { signIn, signUp } = useAuth();
  const { t } = useI18n();
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [password, setPassword] = useState('');
  const [err, setErr] = useState('');

  const submit = (e) => {
    e.preventDefault();
    if (!email.trim() || !password.trim()) {setErr('Please fill out all fields.');return;}
    if (mode === 'signup' && !name.trim()) {setErr('Please enter a display name.');return;}
    if (mode === 'signup') signUp({ email: email.trim(), name: name.trim(), password });else
    signIn({ email: email.trim(), password });
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 10000, background: 'rgba(4,6,14,0.78)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, backdropFilter: 'blur(8px)',
      animation: 'fadeUp 0.2s ease'
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 420, background: 'var(--bg2)', border: '1px solid var(--border)',
        borderRadius: 16, padding: 32, position: 'relative'
      }}>
        <button onClick={onClose} style={{ position: 'absolute', top: 14, right: 18, fontSize: 22, color: 'var(--text3)' }}>×</button>
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <svg width="40" height="40" viewBox="0 0 48 48" style={{ margin: '0 auto 10px', display: 'block' }}>
            <circle cx="24" cy="24" r="22" fill="none" stroke="var(--accent)" strokeWidth="2" />
            <circle cx="24" cy="24" r="13" fill="rgba(74,158,255,0.1)" />
            <ellipse cx="24" cy="24" rx="8" ry="22" fill="none" stroke="var(--accent)" strokeWidth="1.5" opacity="0.55" />
            <ellipse cx="24" cy="24" rx="22" ry="8" fill="none" stroke="var(--accent2)" strokeWidth="1.5" opacity="0.35" />
            <circle cx="24" cy="24" r="3.5" fill="var(--accent)" />
          </svg>
          <h2 style={{ fontSize: 20, fontWeight: 800 }}>
            {mode === 'signup' ? t('Create your account') : t('Welcome back')}
          </h2>
        </div>

        <form onSubmit={submit}>
          {window.SocialLoginButtons &&
          <>
              <window.SocialLoginButtons onSelect={(p) => {
              // Mock social login — sign user in with provider name + fake email
              const fakeEmail = `user_${p.id}@dramascope.local`;
              const fakeName = `${p.id.charAt(0).toUpperCase() + p.id.slice(1)} User`;
              if (mode === 'signup') signUp({ email: fakeEmail, name: fakeName, password: 'social' });else
              signIn({ email: fakeEmail, password: 'social' });
            }} />
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14, color: 'var(--text3)', fontSize: 11 }}>
                <div style={{ flex: 1, height: 1, background: 'rgba(74,158,255,0.1)' }} />
                <span style={{ textTransform: 'uppercase', letterSpacing: '1px', fontWeight: 700 }}>or</span>
                <div style={{ flex: 1, height: 1, background: 'rgba(74,158,255,0.1)' }} />
              </div>
            </>
          }
          {mode === 'signup' &&
          <div style={{ marginBottom: 12 }}>
              <label style={{ fontSize: 11, fontWeight: 700, color: 'var(--text3)', display: 'block', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.5px' }}>{t('Display name')}</label>
              <input value={name} onChange={(e) => setName(e.target.value)}
            style={{ width: '100%', padding: '11px 14px', borderRadius: 8, background: 'var(--bg3)', border: '1px solid rgba(74,158,255,0.15)', color: 'var(--text)', fontSize: 14, outline: 'none' }} />
            </div>
          }
          <div style={{ marginBottom: 12 }}>
            <label style={{ fontSize: 11, fontWeight: 700, color: 'var(--text3)', display: 'block', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.5px' }}>{t('Email')}</label>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
            style={{ width: '100%', padding: '11px 14px', borderRadius: 8, background: 'var(--bg3)', border: '1px solid rgba(74,158,255,0.15)', color: 'var(--text)', fontSize: 14, outline: 'none' }} />
          </div>
          <div style={{ marginBottom: 18 }}>
            <label style={{ fontSize: 11, fontWeight: 700, color: 'var(--text3)', display: 'block', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.5px' }}>{t('Password')}</label>
            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)}
            style={{ width: '100%', padding: '11px 14px', borderRadius: 8, background: 'var(--bg3)', border: '1px solid rgba(74,158,255,0.15)', color: 'var(--text)', fontSize: 14, outline: 'none' }} />
          </div>
          {err && <div style={{ fontSize: 12, color: 'var(--red)', marginBottom: 10 }}>{err}</div>}
          <button type="submit" style={{
            width: '100%', padding: '12px', borderRadius: 8, background: 'var(--accent)',
            color: '#fff', fontWeight: 700, fontSize: 14, marginBottom: 14
          }}>{mode === 'signup' ? t('Sign Up') : t('Sign In')}</button>
          <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--text3)' }}>
            {mode === 'signup' ? t('Already have an account?') : t('Need an account?')}{' '}
            <button type="button" onClick={() => setMode(mode === 'signup' ? 'signin' : 'signup')} style={{ color: 'var(--accent)', fontWeight: 600 }}>
              {mode === 'signup' ? t('Sign In') : t('Sign Up')}
            </button>
          </div>
        </form>
      </div>
    </div>);

}

// ── HEADER WIDGETS ────────────────────────────────────────────────────────────
function LanguageMenu() {
  const { lang, setLang } = useI18n();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => {if (ref.current && !ref.current.contains(e.target)) setOpen(false);};
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  const cur = LANGUAGES.find((l) => l.code === lang) || LANGUAGES[0];
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen((v) => !v)} style={{
        padding: '6px 10px', borderRadius: 7, fontSize: 12, fontWeight: 700,
        color: 'var(--text2)', border: '1px solid rgba(74,158,255,0.15)',
        background: 'rgba(74,158,255,0.05)', display: 'flex', alignItems: 'center', gap: 4
      }}>
        🌐 {cur.short} <span style={{ fontSize: 9 }}>▾</span>
      </button>
      {open &&
      <div style={{
        position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 300,
        background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 10,
        padding: 6, minWidth: 170, boxShadow: '0 8px 28px rgba(0,0,0,0.6)'
      }}>
          {LANGUAGES.map((l) =>
        <button key={l.code} onClick={() => {setLang(l.code);setOpen(false);}} style={{
          width: '100%', padding: '9px 12px', borderRadius: 6, fontSize: 13, textAlign: 'left',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          background: lang === l.code ? 'rgba(74,158,255,0.15)' : 'transparent',
          color: lang === l.code ? '#fff' : 'var(--text2)', marginBottom: 1
        }}
        onMouseEnter={(e) => {if (lang !== l.code) e.currentTarget.style.background = 'rgba(74,158,255,0.08)';}}
        onMouseLeave={(e) => {if (lang !== l.code) e.currentTarget.style.background = 'transparent';}}>
          
              <span>{l.label}</span>
              <span style={{ fontSize: 10, color: 'var(--text3)', fontWeight: 700 }}>{l.short}</span>
            </button>
        )}
        </div>
      }
    </div>);

}

function AuthButtons() {
  const { openSignIn, openSignUp } = useAuth();
  const { t } = useI18n();
  return (
    <div style={{ display: 'flex', gap: 6 }}>
      <button onClick={openSignIn} style={{
        padding: '7px 14px', borderRadius: 7, fontSize: 12.5, fontWeight: 600,
        color: 'var(--text)', background: 'transparent', border: '1px solid rgba(74,158,255,0.2)'
      }}>{t('Sign In')}</button>
      <button onClick={openSignUp} style={{
        padding: '7px 14px', borderRadius: 7, fontSize: 12.5, fontWeight: 700,
        color: '#fff', background: 'var(--accent)', backgroundColor: "rgb(0, 140, 140)"
      }}>{t('Join Free')}</button>
    </div>);

}

function AvatarMenu({ onNavigate }) {
  const { user, signOut } = useAuth();
  const { t } = useI18n();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => {if (ref.current && !ref.current.contains(e.target)) setOpen(false);};
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  if (!user) return null;
  const initial = (user.name || user.email || '?').charAt(0).toUpperCase();

  const items = [
  { id: 'profile', label: t('My Profile'), page: 'profile' },
  { id: 'library', label: t('My Library'), page: 'watchlist' },
  { id: 'ratings', label: t('My Ratings'), page: 'profile' },
  { id: 'reactions', label: t('My Reactions'), page: 'profile' },
  { id: 'lists', label: t('My Lists'), page: 'watchlist' },
  null,
  { id: 'settings', label: t('Account Settings'), page: 'profile' },
  { id: 'premium', label: '✦ ' + t('Upgrade to Premium'), page: 'premium', premium: true },
  null,
  { id: 'signout', label: t('Log Out'), action: () => {signOut();setOpen(false);} }];


  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen((v) => !v)} style={{
        width: 36, height: 36, borderRadius: '50%',
        background: 'linear-gradient(135deg, var(--accent), var(--purple))',
        color: '#fff', fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center',
        border: open ? '2px solid var(--accent2)' : '2px solid transparent', transition: 'border-color 0.15s'
      }}>{initial}</button>
      {open &&
      <div style={{
        position: 'absolute', top: 'calc(100% + 8px)', right: 0, zIndex: 300,
        background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 12,
        padding: 8, minWidth: 220, boxShadow: '0 12px 36px rgba(0,0,0,0.65)'
      }}>
          <div style={{ padding: '10px 12px 12px', borderBottom: '1px solid rgba(74,158,255,0.08)', marginBottom: 6 }}>
            <div style={{ fontSize: 13, fontWeight: 700 }}>{user.name}</div>
            <div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2 }}>{user.email}</div>
          </div>
          {items.map((it, i) => {
          if (it === null) return <div key={'sep' + i} style={{ height: 1, background: 'rgba(74,158,255,0.08)', margin: '4px 8px' }} />;
          return (
            <button key={it.id} onClick={() => {setOpen(false);it.action ? it.action() : onNavigate(it.page);}} style={{
              width: '100%', padding: '8px 12px', borderRadius: 6, fontSize: 13, textAlign: 'left',
              color: it.premium ? 'var(--purple)' : it.id === 'signout' ? 'var(--red)' : 'var(--text2)',
              fontWeight: it.premium ? 600 : 500
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(74,158,255,0.07)'}
            onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
              {it.label}</button>);

        })}
        </div>
      }
    </div>);

}

// ── GUEST GATE ────────────────────────────────────────────────────────────────
// Wrap any guest-locked action with this; shows a sign-in CTA when no user.
function GuestGate({ message, ctaLabel, variant = 'inline', children }) {
  const { user, openSignUp } = useAuth();
  const { t } = useI18n();
  if (user) return children || null;
  if (variant === 'overlay' && children) {
    return (
      <div style={{ position: 'relative' }}>
        <div style={{ pointerEvents: 'none', filter: 'blur(2px) brightness(0.7)', opacity: 0.5 }}>{children}</div>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 10, padding: 20, background: 'rgba(8,10,22,0.6)', borderRadius: 12 }}>
          <div style={{ fontSize: 13, color: 'var(--text2)', textAlign: 'center', maxWidth: 340 }}>{t(message)}</div>
          <button onClick={openSignUp} style={{ padding: '9px 20px', borderRadius: 8, background: 'var(--accent)', color: '#fff', fontWeight: 700, fontSize: 13 }}>{t(ctaLabel || 'Create Free Account')}</button>
        </div>
      </div>);

  }
  // banner
  return (
    <div style={{
      background: 'linear-gradient(135deg, rgba(74,158,255,0.08), rgba(192,132,252,0.05))',
      border: '1px dashed rgba(74,158,255,0.3)', borderRadius: 10, padding: '16px 20px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14, flexWrap: 'wrap'
    }}>
      <div style={{ flex: 1, minWidth: 200 }}>
        <div style={{ fontSize: 13, color: 'var(--text2)', lineHeight: 1.6 }}>{t(message)}</div>
      </div>
      <button onClick={openSignUp} style={{
        padding: '9px 18px', borderRadius: 8, background: 'var(--accent)', color: '#fff',
        fontWeight: 700, fontSize: 12.5, flexShrink: 0, whiteSpace: 'nowrap'
      }}>{t(ctaLabel || 'Sign Up to See More')}</button>
    </div>);

}

// ── DRAMA RATING PANEL ────────────────────────────────────────────────────────
const DRAMA_RATING_KEYS = [
{ id: 'overall', label: 'Overall Rating', emoji: '⭐' },
{ id: 'ost', label: 'OST Rating', emoji: '🎵' },
{ id: 'side', label: 'Side Characters Rating', emoji: '👥' },
{ id: 'chemistry', label: 'Chemistry Score', emoji: '💞' },
{ id: 'recommendation', label: 'Recommendation Score', emoji: '💯' },
{ id: 'rewatch', label: 'Rewatch Score', emoji: '🔁' }];


function DramaRatingPanel({ dramaId }) {
  const { user, openSignIn } = useAuth();
  const { t } = useI18n();
  const storageKey = `ds_ratings_${dramaId}_${user?.email || 'guest'}`;
  const [ratings, setRatings] = useState(() => {try {return JSON.parse(localStorage.getItem(storageKey)) || {};} catch {return {};}});

  const setRating = (id, val) => {
    if (!user) return;
    const next = { ...ratings, [id]: ratings[id] === val ? 0 : val };
    setRatings(next);
    localStorage.setItem(storageKey, JSON.stringify(next));
  };

  return (
    <div style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 12, padding: 22, marginTop: 24 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18, flexWrap: 'wrap', gap: 8 }}>
        <h3 style={{ fontSize: 16, fontWeight: 700 }}>{t('Rate this drama')}</h3>
        {user && <span style={{ fontSize: 11, color: 'var(--text3)' }}>1–10 scale · auto-saved</span>}
      </div>

      {!user &&
      <div style={{ marginBottom: 18 }}>
          <GuestGate message="Sign in to rate this drama" ctaLabel="Register to Rate" />
        </div>
      }

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {DRAMA_RATING_KEYS.map((rk) =>
        <div key={rk.id}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
              <div style={{ fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
                <span>{rk.emoji}</span>
                <span style={{ color: user ? 'var(--text)' : 'var(--text3)' }}>{t(rk.label)}</span>
              </div>
              <div style={{ fontSize: 14, fontWeight: 800, color: ratings[rk.id] ? 'var(--accent)' : 'var(--text3)', minWidth: 32, textAlign: 'right' }}>
                {ratings[rk.id] ? `${ratings[rk.id]}/10` : '—'}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 3 }}>
              {Array.from({ length: 10 }).map((_, i) => {
              const val = i + 1;
              const active = (ratings[rk.id] || 0) >= val;
              return (
                <button key={val} onClick={() => user ? setRating(rk.id, val) : openSignIn()}
                disabled={!user}
                style={{
                  flex: 1, height: 30, borderRadius: 5, fontSize: 11, fontWeight: 700,
                  background: active ? 'var(--accent)' : 'var(--bg3)',
                  color: active ? '#fff' : 'var(--text3)',
                  border: `1px solid ${active ? 'var(--accent)' : 'rgba(74,158,255,0.08)'}`,
                  cursor: user ? 'pointer' : 'not-allowed',
                  opacity: user ? 1 : 0.5,
                  transition: 'background 0.15s'
                }}>{val}</button>);

            })}
            </div>
          </div>
        )}
      </div>
    </div>);

}

// ── DRAMA REACTION PANEL ──────────────────────────────────────────────────────
const DRAMA_REACTIONS = [
{ id: 'emotional_damage', label: 'Emotional Damage', emoji: '💔' },
{ id: 'comfort_drama', label: 'Comfort Drama', emoji: '🤍' },
{ id: 'insane_chemistry', label: 'Insane Chemistry', emoji: '🔥' },
{ id: 'toxic_romance', label: 'Toxic Romance', emoji: '☠️' },
{ id: 'masterpiece', label: 'Masterpiece', emoji: '👑' }];


function DramaReactionPanel({ dramaId }) {
  const { user, openSignIn } = useAuth();
  const { t } = useI18n();
  const storageKey = `ds_dreact_${dramaId}_${user?.email || 'guest'}`;
  const [reactions, setReactions] = useState(() => {try {return JSON.parse(localStorage.getItem(storageKey)) || {};} catch {return {};}});

  const toggle = (id) => {
    if (!user) return;
    const next = { ...reactions, [id]: !reactions[id] };
    setReactions(next);
    localStorage.setItem(storageKey, JSON.stringify(next));
  };

  return (
    <div style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 12, padding: 22, marginTop: 16 }}>
      <h3 style={{ fontSize: 16, fontWeight: 700, marginBottom: 14 }}>{t('React to this drama')}</h3>
      {!user &&
      <div style={{ marginBottom: 14 }}>
          <GuestGate message="Sign in to react to this drama" ctaLabel="Register to React" />
        </div>
      }
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {DRAMA_REACTIONS.map((r) => {
          const active = reactions[r.id];
          return (
            <button key={r.id} onClick={() => user ? toggle(r.id) : openSignIn()}
            style={{
              padding: '10px 16px', borderRadius: 24, fontSize: 13, fontWeight: 600,
              background: active ? 'rgba(74,158,255,0.18)' : 'var(--bg3)',
              color: active ? 'var(--accent2)' : user ? 'var(--text2)' : 'var(--text3)',
              border: `1px solid ${active ? 'var(--accent)' : 'rgba(74,158,255,0.1)'}`,
              display: 'flex', alignItems: 'center', gap: 6,
              opacity: user ? 1 : 0.55,
              transition: 'all 0.15s'
            }}>
              <span style={{ fontSize: 16 }}>{r.emoji}</span>
              <span>{r.label}</span>
            </button>);

        })}
      </div>
    </div>);

}

// ── ACTOR REACTION PANEL ──────────────────────────────────────────────────────
const ACTOR_REACTIONS = [
{ id: 'love', label: 'Love', emoji: '❤️' },
{ id: 'hot', label: 'Hot', emoji: '🔥' },
{ id: 'soft_boy', label: 'Soft Boy', emoji: '🌸' },
{ id: 'worship', label: 'Worship', emoji: '🙌' },
{ id: 'emotional_damage', label: 'Emotional Damage', emoji: '💔' },
{ id: 'red_flag', label: 'Red Flag', emoji: '🚩' }];


function ActorReactionPanel({ actorId }) {
  const { user, openSignIn } = useAuth();
  const { t } = useI18n();
  const storageKey = `ds_areact_${actorId}_${user?.email || 'guest'}`;
  const [reactions, setReactions] = useState(() => {try {return JSON.parse(localStorage.getItem(storageKey)) || {};} catch {return {};}});
  const toggle = (id) => {
    if (!user) return;
    const next = { ...reactions, [id]: !reactions[id] };
    setReactions(next);
    localStorage.setItem(storageKey, JSON.stringify(next));
  };
  return (
    <div style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 12, padding: 22, marginTop: 20 }}>
      <h3 style={{ fontSize: 16, fontWeight: 700, marginBottom: 14 }}>{t('React to this actor')}</h3>
      {!user &&
      <div style={{ marginBottom: 14 }}>
          <GuestGate message="Sign in to react to this actor" ctaLabel="Register to React" />
        </div>
      }
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {ACTOR_REACTIONS.map((r) => {
          const active = reactions[r.id];
          return (
            <button key={r.id} onClick={() => user ? toggle(r.id) : openSignIn()}
            style={{
              padding: '10px 16px', borderRadius: 24, fontSize: 13, fontWeight: 600,
              background: active ? 'rgba(74,158,255,0.18)' : 'var(--bg3)',
              color: active ? 'var(--accent2)' : user ? 'var(--text2)' : 'var(--text3)',
              border: `1px solid ${active ? 'var(--accent)' : 'rgba(74,158,255,0.1)'}`,
              display: 'flex', alignItems: 'center', gap: 6,
              opacity: user ? 1 : 0.55, transition: 'all 0.15s'
            }}>
              <span style={{ fontSize: 16 }}>{r.emoji}</span>
              <span>{r.label}</span>
            </button>);

        })}
      </div>
    </div>);

}

// ── ACTOR TRAITS PANEL ────────────────────────────────────────────────────────
const ACTOR_TRAITS = [
{ id: 'chemistry', label: 'Chemistry' },
{ id: 'acting_skills', label: 'Acting Skills' },
{ id: 'smile', label: 'Smile' },
{ id: 'emotional_acting', label: 'Emotional Acting' },
{ id: 'charisma', label: 'Charisma' },
{ id: 'overhyped', label: 'Overhyped' },
{ id: 'repetitive_roles', label: 'Repetitive Roles' }];


function ActorTraitsPanel({ actorId }) {
  const { user, openSignIn } = useAuth();
  const { t } = useI18n();
  const storageKey = `ds_traits_${actorId}_${user?.email || 'guest'}`;
  const [votes, setVotes] = useState(() => {try {return JSON.parse(localStorage.getItem(storageKey)) || {};} catch {return {};}});
  const vote = (traitId, val) => {
    if (!user) return;
    const next = { ...votes, [traitId]: votes[traitId] === val ? null : val };
    setVotes(next);
    localStorage.setItem(storageKey, JSON.stringify(next));
  };
  return (
    <div style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 12, padding: 22, marginTop: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14, flexWrap: 'wrap', gap: 8 }}>
        <h3 style={{ fontSize: 16, fontWeight: 700 }}>{t('Vote on traits')}</h3>
        {user && <span style={{ fontSize: 11, color: 'var(--text3)' }}>👍 {t('Agree')} / 👎 {t('Disagree')}</span>}
      </div>
      {!user &&
      <div style={{ marginBottom: 14 }}>
          <GuestGate message="Sign in to react to this actor" ctaLabel="Register to React" />
        </div>
      }
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {ACTOR_TRAITS.map((tr) =>
        <div key={tr.id} style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          padding: '10px 14px', background: 'var(--bg3)', borderRadius: 8,
          border: '1px solid rgba(74,158,255,0.06)'
        }}>
            <span style={{ fontSize: 13, fontWeight: 500, color: user ? 'var(--text)' : 'var(--text3)' }}>{tr.label}</span>
            <div style={{ display: 'flex', gap: 6 }}>
              <button onClick={() => user ? vote(tr.id, 'agree') : openSignIn()} style={{
              padding: '5px 12px', borderRadius: 6, fontSize: 12, fontWeight: 600,
              background: votes[tr.id] === 'agree' ? 'rgba(61,214,140,0.2)' : 'var(--bg2)',
              color: votes[tr.id] === 'agree' ? 'var(--green)' : 'var(--text3)',
              border: `1px solid ${votes[tr.id] === 'agree' ? 'rgba(61,214,140,0.4)' : 'rgba(255,255,255,0.05)'}`,
              opacity: user ? 1 : 0.5, display: 'flex', alignItems: 'center', gap: 4
            }}>👍 {t('Agree')}</button>
              <button onClick={() => user ? vote(tr.id, 'disagree') : openSignIn()} style={{
              padding: '5px 12px', borderRadius: 6, fontSize: 12, fontWeight: 600,
              background: votes[tr.id] === 'disagree' ? 'rgba(255,107,107,0.18)' : 'var(--bg2)',
              color: votes[tr.id] === 'disagree' ? 'var(--red)' : 'var(--text3)',
              border: `1px solid ${votes[tr.id] === 'disagree' ? 'rgba(255,107,107,0.4)' : 'rgba(255,255,255,0.05)'}`,
              opacity: user ? 1 : 0.5, display: 'flex', alignItems: 'center', gap: 4
            }}>👎 {t('Disagree')}</button>
            </div>
          </div>
        )}
      </div>
    </div>);

}

// ── FOLLOW BUTTON ─────────────────────────────────────────────────────────────
function FollowButton({ actorId, actorName }) {
  const { user, openSignUp } = useAuth();
  const { t } = useI18n();
  const storageKey = `ds_follows_${user?.email || 'guest'}`;
  const [follows, setFollows] = useState(() => {try {return JSON.parse(localStorage.getItem(storageKey)) || [];} catch {return [];}});
  const isFollowing = follows.some((f) => f.id === actorId);

  const toggle = () => {
    if (!user) {openSignUp();return;}
    const next = isFollowing ?
    follows.filter((f) => f.id !== actorId) :
    [...follows, { id: actorId, name: actorName }];
    setFollows(next);
    localStorage.setItem(storageKey, JSON.stringify(next));
  };

  return (
    <button onClick={toggle} style={{
      padding: '8px 18px', borderRadius: 8, fontSize: 13, fontWeight: 700,
      background: isFollowing ? 'rgba(61,214,140,0.15)' : 'var(--accent)',
      color: isFollowing ? 'var(--green)' : '#fff',
      border: isFollowing ? '1px solid rgba(61,214,140,0.35)' : 'none',
      display: 'flex', alignItems: 'center', gap: 6
    }}>
      {!user ? '🔒 ' + t('Follow') : isFollowing ? '✓ ' + t('Following') : '+ ' + t('Follow')}
    </button>);

}

// Export everything to window
Object.assign(window, {
  // i18n
  LANGUAGES, I18nContext, I18nProvider, useI18n,
  // auth
  AuthContext, AuthProvider, useAuth, AuthModal,
  // header
  LanguageMenu, AuthButtons, AvatarMenu,
  // gates and panels
  GuestGate, DramaRatingPanel, DramaReactionPanel,
  ActorReactionPanel, ActorTraitsPanel, FollowButton
});