const { useState, useEffect } = React;

// --- 1. FIREBASE & DATABASE SERVICE ---
const DEFAULT_CONFIG = {
  apiKey: "AIzaSyA6LnKSd04m1RWFsFxNC07YdrkTn6YzDG8",
  authDomain: "zubdah-73fa7.firebaseapp.com",
  projectId: "zubdah-73fa7",
  storageBucket: "zubdah-73fa7.firebasestorage.app",
  messagingSenderId: "534417731923",
  appId: "1:534417731923:web:0b561ddc5cef1ffeed71a6"
};

let isFirebaseInitialized = false;
let authInstance = null;
let dbInstance = null;

function initFirebase(customConfig = null) {
  const config = customConfig || DEFAULT_CONFIG;
  if (config.apiKey && typeof window.firebase !== 'undefined') {
    try {
      if (!window.firebase.apps || !window.firebase.apps.length) {
        window.firebase.initializeApp(config);
      }
      authInstance = window.firebase.auth();
      dbInstance = window.firebase.firestore();
      isFirebaseInitialized = true;
      console.log('Firebase initialized successfully with project zubdah-73fa7.');
      return true;
    } catch (err) {
      console.warn('Firebase initialization warning:', err);
      isFirebaseInitialized = false;
      return false;
    }
  }
  return false;
}

function mapFirebaseError(error) {
  if (!error) return 'حدث خطأ غير متوقع.';
  const code = error.code || '';
  switch (code) {
    case 'auth/email-already-in-use':
      return 'البريد الإلكتروني مستخدم بالفعل بحساب آخر.';
    case 'auth/invalid-email':
      return 'صيغة البريد الإلكتروني غير صالحة.';
    case 'auth/weak-password':
      return 'كلمة المرور ضعيفة (يجب أن تتكون من 6 أحرف أو أرقام على الأقل).';
    case 'auth/user-not-found':
      return 'لم يتم العثور على حساب مرتبط بهذا البريد الإلكتروني.';
    case 'auth/wrong-password':
    case 'auth/invalid-credential':
      return 'كلمة المرور أو البريد الإلكتروني غير صحيح.';
    case 'auth/too-many-requests':
      return 'تم حظر المحاولات مؤقتاً بسبب تكرار المحاولات الخاطئة. يرجى المحاولة لاحقاً.';
    case 'auth/network-request-failed':
      return 'فشل الاتصال بالإنترنت، يرجى التحقق من اتصالك.';
    case 'auth/popup-closed-by-user':
      return 'تم إغلاق نافذة تسجيل الدخول قبل إتمام العملية.';
    default:
      return error.message || 'حدث خطأ أثناء تنفيذ العملية. يرجى المحاولة لاحقاً.';
  }
}

const STORAGE_KEYS = {
  USER: 'zubdah_current_user',
  ANALYSES: 'zubdah_saved_analyses'
};

const DEFAULT_USER = {
  uid: 'user_zubdah_demo_101',
  fullName: 'أحمد محمد',
  displayName: 'أحمد محمد',
  email: 'ahmed.mohamed@example.com',
  photoURL: 'https://lh3.googleusercontent.com/aida-public/AB6AXuDhwfv0_8A02hQI8GDN0AvEvIMpK6nQ26A_ybujy8rwOtL4ebPTnEmRCpx_3Hukf_YDmZV9fOMEseLS0AtLvvJeVxfWUnJQGvIdxqKWa5FI_X5Sf5fiusej-cciBllpHQwYnKFxQ4uX6uw9-W1_6iJh94Vc75SNiPnp16uEgk5wwbDdQ6ppLZE4uKQ2I2I_mv5PjDO7IHP0NOf0I1W3e1nC90ep0x-OoXZbyVAOI7PTsShWMoQEvIIdZw',
  plan: 'عضو مسجل',
  createdAt: '2023-10-15',
  summariesCount: 3
};

function getDefaultAnalyses() {
  return [
    {
      id: 'analysis_burger_house',
      title: 'مطعم بيت البرجر',
      category: 'مطاعم وبرجر',
      type: 'restaurant',
      rating: 4.3,
      reviewCount: 1284,
      score: 82,
      gist: 'الأكل ممتاز واللحم طازج وخبز البريوش رائع، لكن الخدمة وتأخر الطلبات مشكلة متكررة في أوقات الذروة.',
      imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuCeOIIMWUuMa3zVxXvIKFpu3iNe8Dr0LNRd7fgsv5MGb-8m49IYe5js14TW0MTjOhJS3fsY6naZb6E1HarvUvTpcQ5anLq3NympfCA8-Y-ZbRsnC3GI9wMeD_n2M2zAXWhjAnGHSEWljRTCqDZianq13pwlrZSwC9UFnQQdY75EyW8EW0wcoqMgkdpbgzdywWLgv0AKo45rWRX63g8Fm64UIj5UV-O7p7YbzNV8blQoNZfzLtnrcncVJw',
      date: '15 أكتوبر 2023',
      createdAt: '2023-10-15T14:30:00Z',
      sentiment: { positive: 72, neutral: 18, negative: 10 },
      insights: [
        { label: 'جودة الطعام', score: 92, trend: 'إيجابي (نمط قوي)', icon: 'restaurant', status: 'positive' },
        { label: 'الأجواء', score: 85, trend: 'إيجابي (نمط قوي)', icon: 'wb_twilight', status: 'positive' },
        { label: 'السعر', score: 65, trend: 'آراء مختلطة', icon: 'payments', status: 'neutral' },
        { label: 'الخدمة', score: 45, trend: 'سلبي (نمط متوسط)', icon: 'room_service', status: 'negative' }
      ],
      pros: ['الطعم وجودة اللحم البقري', 'الجلسات الخارجية', 'تنوع الصوصات المبتكرة', 'خبز البريوش الطازج'],
      cons: ['تأخر تسليم الطلبات وقت الزحمة', 'ارتفاع الأسعار قليلاً', 'صعوبة العثور على موقف'],
      quotes: [
        { text: 'البرجر كلاسيكي وطعم اللحم واضح بدون بهارات زايدة. من أفضل مطاعم البرجر بالمدينة.', stars: 5, time: 'قبل أسبوعين' },
        { text: 'الأسعار مرتفعة مقارنة بالحجم، وانتظرنا 35 دقيقة للطلب في يوم الجمعة.', stars: 2, time: 'الشهر الماضي' }
      ]
    },
    {
      id: 'analysis_sony_xm5',
      title: 'سماعات سوني XM5',
      category: 'إلكترونيات وصوتيات',
      type: 'product',
      rating: 4.8,
      reviewCount: 3420,
      score: 91,
      gist: 'عزل ضجيج مذهل وراحة ممتازة، ولكن تصميم طي السماعة أقل مرونة من الجيل السابق.',
      imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuD3JIiHn_BVV6pqc7gO4eQbiv76cCeJUY6d8XuRCHhUF3DHtVKyGa7Ljzm8H4XEYG_M_Iids0chogAacC4gxbjdvrOfOC9gkWyJXTEqfJ1-cTLisfUeWVJDO0DZDtJHODldmMCe-inWRbJOhbaLxKWVRiXw0FQqO1nmUGsvfwlydJ5AgOsxc9aTaG2J2n6RlS-qo7SL4-pmd3gpKMKRnUHM-guOubhxHNOdy1wXKjG239pMk2PiDTBMzg',
      date: '02 نوفمبر 2023',
      createdAt: '2023-11-02T18:00:00Z',
      sentiment: { positive: 85, neutral: 10, negative: 5 },
      insights: [
        { label: 'عزل الضوضاء', score: 96, trend: 'إيجابي ممتاز', icon: 'headphones', status: 'positive' },
        { label: 'عمر البطارية', score: 94, trend: 'إيجابي ممتاز', icon: 'battery_full', status: 'positive' },
        { label: 'راحة الارتداء', score: 90, trend: 'إيجابي عالي', icon: 'sentiment_satisfied', status: 'positive' },
        { label: 'سهولة الحمل', score: 62, trend: 'نمط معتدل', icon: 'inventory_2', status: 'neutral' }
      ],
      pros: ['أفضل عزل صوتي ANC', 'بطارية تدوم أكثر من 30 ساعة', 'ميكروفون واضح جداً للمكالمات', 'تطبيق تحكم متطور'],
      cons: ['عدم إمكانية طيها بالكامل', 'السعر مرتفع نسبياً', 'خامة الملمس سريعة التبصيم'],
      quotes: [
        { text: 'العزل في الطائرة والمكتب خرافي، تشعر أن العالم صامت تماماً.', stars: 5, time: 'قبل 3 أيام' },
        { text: 'الحجم في الحقيبة كبير بسبب عدم الطي مثل XM4، غير ذلك ممتازة.', stars: 4, time: 'قبل شهر' }
      ]
    },
    {
      id: 'analysis_rove_hotel',
      title: 'فندق روف دبي',
      category: 'فنادق وسياحة',
      type: 'hotel',
      rating: 4.6,
      reviewCount: 2150,
      score: 85,
      gist: 'موقع استراتيجي وغرف عصرية وشبابية، مناسب للعمل والسياحة وبأسعار منافسة.',
      imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuB0Q8KRe-khICqVVgK_o8dlDPZc4RVKMMK0tjybajxR_gdXMtQZx5AVSBM8jXThxdbrG3c-aJx0mCAxeMcls902QzambAAbohKCSHPzuxkOw2mNT-JhYMOCRJv96gSeHzwsrJhlU0T9ZW44AvYtiLeiGqAiWKEcGGap4-fZkDFGziuIuWRpNXdhmBOEREKQ1V9mVQJxfwf-O93UIQj71Upr2wyA942rrumI6ia1zuAPbIfATn1Yhgg7sw',
      date: '28 نوفمبر 2023',
      createdAt: '2023-11-28T09:15:00Z',
      sentiment: { positive: 78, neutral: 14, negative: 8 },
      insights: [
        { label: 'الموقع', score: 95, trend: 'إيجابي استثنائي', icon: 'location_on', status: 'positive' },
        { label: 'النظافة والهدوء', score: 88, trend: 'إيجابي عالي', icon: 'cleaning_services', status: 'positive' },
        { label: 'القيمة مقابل السعر', score: 89, trend: 'إيجابي عالي', icon: 'savings', status: 'positive' },
        { label: 'مساحة الغرف', score: 70, trend: 'مقبول / متواضع', icon: 'hotel', status: 'neutral' }
      ],
      pros: ['قريب من المترو ومراكز التسوق', 'خدمة ذاتية ذكية وتسجيل سريع', 'واي فاي فائق السرعة', 'أجواء عصرية مريحة'],
      cons: ['الغرف صغيرة نوعاً ما للعائلات الكبيرة', 'تنوع الإفطار محدود قليلاً'],
      quotes: [
        { text: 'فندق شبابي رائع، كل شيء فيه مصمم بذكاء وسلاسة والموقع ممتاز.', stars: 5, time: 'قبل 5 أيام' },
        { text: 'الغرفة نظيفة لكن صغيرة، ينفع للمسافر الفردي أو رحلات العمل القصيرة.', stars: 4, time: 'قبل أسبوعين' }
      ]
    }
  ];
}

const authService = {
  getCurrentUser() {
    if (isFirebaseInitialized && authInstance && authInstance.currentUser) {
      const u = authInstance.currentUser;
      return {
        uid: u.uid,
        displayName: u.displayName || 'مستخدم زبدة',
        fullName: u.displayName || 'مستخدم زبدة',
        email: u.email,
        photoURL: u.photoURL || DEFAULT_USER.photoURL,
        plan: 'عضو مسجل',
        summariesCount: 0
      };
    }
    const saved = localStorage.getItem(STORAGE_KEYS.USER);
    return saved ? JSON.parse(saved) : DEFAULT_USER;
  },

  // 1. Register with Full Name, Email, Password -> Firestore users collection
  async register(fullName, email, password) {
    if (isFirebaseInitialized && authInstance) {
      try {
        const cred = await authInstance.createUserWithEmailAndPassword(email, password);
        const user = cred.user;

        await user.updateProfile({ displayName: fullName });

        const userData = {
          uid: user.uid,
          fullName: fullName,
          email: email,
          createdAt: new Date().toISOString(),
          summariesCount: 0
        };

        if (dbInstance) {
          try {
            await dbInstance.collection('users').doc(user.uid).set(userData);
          } catch (dbErr) {
            console.warn('Could not write users doc in Firestore:', dbErr);
          }
        }

        const appUser = {
          ...userData,
          displayName: fullName,
          photoURL: DEFAULT_USER.photoURL,
          plan: 'عضو مسجل'
        };

        localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(appUser));
        return { success: true, user: appUser };
      } catch (err) {
        throw new Error(mapFirebaseError(err));
      }
    }

    // Fallback Offline registration
    const fallbackUser = {
      uid: 'user_' + Math.random().toString(36).substr(2, 9),
      fullName: fullName,
      displayName: fullName,
      email: email,
      photoURL: DEFAULT_USER.photoURL,
      plan: 'عضو مسجل',
      createdAt: new Date().toISOString(),
      summariesCount: 0
    };

    localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(fallbackUser));
    return { success: true, user: fallbackUser };
  },

  async login(email, password) {
    if (isFirebaseInitialized && authInstance) {
      try {
        const cred = await authInstance.signInWithEmailAndPassword(email, password);
        const user = cred.user;
        let fullName = user.displayName || email.split('@')[0];

        if (dbInstance) {
          try {
            const docSnap = await dbInstance.collection('users').doc(user.uid).get();
            if (docSnap.exists && docSnap.data().fullName) {
              fullName = docSnap.data().fullName;
            }
          } catch (e) {
            console.warn('Fetch user doc error:', e);
          }
        }

        const appUser = {
          uid: user.uid,
          fullName: fullName,
          displayName: fullName,
          email: user.email,
          photoURL: user.photoURL || DEFAULT_USER.photoURL,
          plan: 'عضو مسجل'
        };
        localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(appUser));
        return { success: true, user: appUser };
      } catch (err) {
        throw new Error(mapFirebaseError(err));
      }
    }

    const fallbackUser = {
      uid: 'user_' + Math.random().toString(36).substr(2, 9),
      fullName: email.split('@')[0],
      displayName: email.split('@')[0],
      email: email,
      photoURL: DEFAULT_USER.photoURL,
      plan: 'عضو مسجل',
      createdAt: new Date().toISOString()
    };
    localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(fallbackUser));
    return { success: true, user: fallbackUser };
  },

  async loginWithGoogle() {
    if (isFirebaseInitialized && authInstance) {
      try {
        const provider = new window.firebase.auth.GoogleAuthProvider();
        const cred = await authInstance.signInWithPopup(provider);
        const user = cred.user;
        const fullName = user.displayName || 'مستخدم جوجل';

        const userData = {
          uid: user.uid,
          fullName: fullName,
          email: user.email,
          createdAt: new Date().toISOString(),
          summariesCount: 0
        };

        if (dbInstance) {
          try {
            await dbInstance.collection('users').doc(user.uid).set(userData, { merge: true });
          } catch (e) {}
        }

        const appUser = {
          ...userData,
          displayName: fullName,
          photoURL: user.photoURL || DEFAULT_USER.photoURL,
          plan: 'عضو مسجل'
        };

        localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(appUser));
        return { success: true, user: appUser };
      } catch (err) {
        throw new Error(mapFirebaseError(err));
      }
    }

    const googleUser = {
      uid: 'google_user_' + Math.random().toString(36).substr(2, 7),
      fullName: 'عبدالله السعيد',
      displayName: 'عبدالله السعيد',
      email: 'abdullah.alsaeed@gmail.com',
      photoURL: 'https://lh3.googleusercontent.com/aida-public/AB6AXuCqTClPFWJvfQslCacIVzJwtK_aN95KT3-W7o8CyRcGKfvke1yjJRwV-LWe_mSO48oAMVzH_YQ77iz5uRC3ilC6YpGIF82QUoFqBlpEvNPQNtTySLnH1msqLsKeOm1OpnRcQthdi4yPg4ot_Q2Ho1i89RtqPxLEZswtn5WiMDxmYApPOJXgkK4MpPujXWGWcSeHKwNL1c3E6QvSKeLBai4XhmnSixNTtO3nm1BXc7kD_ZqkoFs8GXO9OA',
      plan: 'عضو مسجل',
      createdAt: new Date().toISOString(),
      summariesCount: 0
    };
    localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(googleUser));
    return { success: true, user: googleUser };
  },

  async resetPassword(email) {
    if (isFirebaseInitialized && authInstance) {
      try {
        await authInstance.sendPasswordResetEmail(email);
        return { success: true, message: 'تم إرسال رابط استعادة كلمة المرور إلى بريدك الإلكتروني بنجاح.' };
      } catch (err) {
        throw new Error(mapFirebaseError(err));
      }
    }
    return { success: true, message: `تم إرسال رابط استعادة كلمة المرور إلى ${email} بنجاح.` };
  },

  async logout() {
    if (isFirebaseInitialized && authInstance) {
      try {
        await authInstance.signOut();
      } catch (e) {}
    }
    localStorage.removeItem(STORAGE_KEYS.USER);
    return { success: true };
  },

  updateProfile(updates) {
    const current = this.getCurrentUser();
    const updated = { ...current, ...updates };
    localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(updated));
    return updated;
  }
};

const dbService = {
  // Real-time listener for user profile from Firestore 'users' collection
  subscribeUserProfile(userId, onUpdate) {
    if (isFirebaseInitialized && dbInstance && userId) {
      try {
        return dbInstance.collection('users').doc(userId).onSnapshot((doc) => {
          if (doc.exists) onUpdate(doc.data());
        }, (err) => console.warn('Firestore profile listener warning:', err));
      } catch (e) {}
    }
    return () => {};
  },

  // Real-time listener for user analyses from Firestore 'analyses' collection
  subscribeUserAnalyses(userId, onUpdate) {
    if (isFirebaseInitialized && dbInstance && userId) {
      try {
        return dbInstance.collection('analyses').where('userId', '==', userId).onSnapshot((snap) => {
          const list = snap.docs.map(d => ({ id: d.id, ...d.data() }));
          onUpdate(list);
        }, (err) => console.warn('Firestore analyses listener warning:', err));
      } catch (e) {}
    }
    return () => {};
  },

  async getAnalyses(userId) {
    if (isFirebaseInitialized && dbInstance && userId) {
      try {
        const snap = await dbInstance.collection('analyses')
          .where('userId', '==', userId)
          .orderBy('createdAt', 'desc')
          .get();
        return snap.docs.map(doc => ({ id: doc.id, ...doc.data() }));
      } catch (err) {
        console.warn('Firestore fetch error:', err);
      }
    }
    const saved = localStorage.getItem(STORAGE_KEYS.ANALYSES);
    return saved ? JSON.parse(saved) : getDefaultAnalyses();
  },

  async saveAnalysis(analysis, userId) {
    const record = {
      ...analysis,
      id: analysis.id || 'analysis_' + Date.now(),
      userId: userId || 'anonymous',
      createdAt: analysis.createdAt || new Date().toISOString()
    };

    if (isFirebaseInitialized && dbInstance) {
      try {
        await dbInstance.collection('analyses').doc(record.id).set(record);
      } catch (err) {
        console.warn('Firestore save error:', err);
      }
    }

    const current = await this.getAnalyses(userId);
    const filtered = current.filter(a => a.id !== record.id);
    const updated = [record, ...filtered];
    localStorage.setItem(STORAGE_KEYS.ANALYSES, JSON.stringify(updated));
    return record;
  },

  async deleteAnalysis(id, userId) {
    if (isFirebaseInitialized && dbInstance) {
      try {
        await dbInstance.collection('analyses').doc(id).delete();
      } catch (err) {
        console.warn('Firestore delete error:', err);
      }
    }
    const current = await this.getAnalyses(userId);
    const updated = current.filter(a => a.id !== id);
    localStorage.setItem(STORAGE_KEYS.ANALYSES, JSON.stringify(updated));
    return true;
  }
};

// --- 2. AI SUMMARIZER SERVICE ---
const POSITIVE_KEYWORDS = ['ممتاز', 'رائع', 'لذيذ', 'نظيف', 'جميل', 'سريع', 'بطل', 'خرافي', 'مريح', 'فاخر', 'محترم', 'مميز', 'جودة', 'أنصح', 'يستاهل', 'رهيب', 'فخم', 'مرتب', 'أفضل', 'حب', 'قوي', 'أعجبني', 'استثنائي'];
const NEGATIVE_KEYWORDS = ['سيء', 'بطيء', 'غالي', 'مبالغ', 'تأخير', 'بارد', 'غير نظيف', 'زحمة', 'رديء', 'مشكلة', 'لا أنصح', 'خدمة سيئة', 'صغير', 'إزعاج', 'تعبان', 'ضيق', 'خربان', 'ما يسوى', 'ندم'];

const PRESET_PLACES = {
  burger: {
    title: 'مطعم بيت البرجر (Burger House)',
    category: 'مطاعم وبرجر',
    type: 'restaurant',
    rating: 4.3,
    reviewCount: 1284,
    score: 82,
    gist: 'الأكل ممتاز واللحم طازج وخبز البريوش رائع، لكن الخدمة وتأخر الطلبات مشكلة متكررة وقت الزحمة.',
    imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuCeOIIMWUuMa3zVxXvIKFpu3iNe8Dr0LNRd7fgsv5MGb-8m49IYe5js14TW0MTjOhJS3fsY6naZb6E1HarvUvTpcQ5anLq3NympfCA8-Y-ZbRsnC3GI9wMeD_n2M2zAXWhjAnGHSEWljRTCqDZianq13pwlrZSwC9UFnQQdY75EyW8EW0wcoqMgkdpbgzdywWLgv0AKo45rWRX63g8Fm64UIj5UV-O7p7YbzNV8blQoNZfzLtnrcncVJw',
    sentiment: { positive: 72, neutral: 18, negative: 10 },
    insights: [
      { label: 'جودة اللحم والطعم', score: 92, trend: 'إيجابي (نمط قوي)', icon: 'restaurant', status: 'positive' },
      { label: 'الأجواء والجلسات', score: 85, trend: 'إيجابي (نمط قوي)', icon: 'wb_twilight', status: 'positive' },
      { label: 'الأسعار', score: 65, trend: 'آراء مختلطة', icon: 'payments', status: 'neutral' },
      { label: 'سرعة الخدمة', score: 45, trend: 'سلبي (نمط متوسط)', icon: 'room_service', status: 'negative' }
    ],
    pros: ['جودة اللحم البقري الطازج', 'تنوع الصوصات المبتكرة', 'جلسات خارجية ممتعة', 'بطاطس مقرمشة'],
    cons: ['وقت الانتظار يصل لـ 40 دقيقة في الويكند', 'ارتفاع الأسعار مقارنة بالحجم', 'صعوبة المواقف'],
    quotes: [
      { text: 'البرجر كلاسيكي وطعم اللحم واضح بدون بهارات زائدة، أفضل مطعم جربته هذا الشهر.', stars: 5, time: 'قبل 4 أيام' },
      { text: 'الطعم خرافي 10/10 لكن انتظرنا نص ساعة حتى نلاقي طاولة و25 دقيقة للأكل.', stars: 3, time: 'قبل أسبوع' }
    ]
  },
  coffee: {
    title: 'مقهى ومحمصة الأثر (Al Athar Specialty Coffee)',
    category: 'مقاهي ومشروبات',
    type: 'cafe',
    rating: 4.7,
    reviewCount: 950,
    score: 89,
    gist: 'قهوة مختصة فاخرة وديكور هادئ ومناسب للعمل أو القراءة، إلا أن المساحة محدودة في المساء.',
    imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuDhwfv0_8A02hQI8GDN0AvEvIMpK6nQ26A_ybujy8rwOtL4ebPTnEmRCpx_3Hukf_YDmZV9fOMEseLS0AtLvvJeVxfWUnJQGvIdxqKWa5FI_X5Sf5fiusej-cciBllpHQwYnKFxQ4uX6uw9-W1_6iJh94Vc75SNiPnp16uEgk5wwbDdQ6ppLZE4uKQ2I2I_mv5PjDO7IHP0NOf0I1W3e1nC90ep0x-OoXZbyVAOI7PTsShWMoQEvIIdZw',
    sentiment: { positive: 88, neutral: 8, negative: 4 },
    insights: [
      { label: 'جودة البن والتحضير', score: 96, trend: 'إيجابي استثنائي', icon: 'local_cafe', status: 'positive' },
      { label: 'مناسب للعمل والدراسة', score: 91, trend: 'إيجابي عالي', icon: 'laptop_mac', status: 'positive' },
      { label: 'التعامل وبشاشة الطاقم', score: 94, trend: 'إيجابي عالي', icon: 'sentiment_very_satisfied', status: 'positive' },
      { label: 'توفر الجلسات مساءً', score: 58, trend: 'ازدحام ملحوظ', icon: 'chair', status: 'neutral' }
    ],
    pros: ['محاصيل بن متنوعة وممتازة كولومبية وإثيوبية', 'موسيقى هادئة وفيشات كهرباء متوفرة', 'باريستا محترف ومتعاون', 'كيكة العسل اللذيذة'],
    cons: ['قلة الطاولات في الفترة المسائية', 'لا يوجد جلسات خارجية مغطاة'],
    quotes: [
      { text: 'الـ V60 الإثيوبية هنا موزونة بالملي، والمكان بطل للمذاكرة والتركيز في الصباح.', stars: 5, time: 'أمس' },
      { text: 'قهوة ممتازة جداً وأجواء رايقة، لكن بعد العشاء زحمة وممكن ما تلقى كرسي.', stars: 4, time: 'قبل 3 أيام' }
    ]
  },
  tech: {
    title: 'سماعات سوني Sony WH-1000XM5',
    category: 'إلكترونيات وصوتيات',
    type: 'product',
    rating: 4.8,
    reviewCount: 3420,
    score: 91,
    gist: 'عزل ضجيج رائد في فئته وصوت نقي مع راحة قصوى، لكن عدم الطي الكامل يزيد حجم الحافظة.',
    imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuD3JIiHn_BVV6pqc7gO4eQbiv76cCeJUY6d8XuRCHhUF3DHtVKyGa7Ljzm8H4XEYG_M_Iids0chogAacC4gxbjdvrOfOC9gkWyJXTEqfJ1-cTLisfUeWVJDO0DZDtJHODldmMCe-inWRbJOhbaLxKWVRiXw0FQqO1nmUGsvfwlydJ5AgOsxc9aTaG2J2n6RlS-qo7SL4-pmd3gpKMKRnUHM-guOubhxHNOdy1wXKjG239pMk2PiDTBMzg',
    sentiment: { positive: 85, neutral: 10, negative: 5 },
    insights: [
      { label: 'عزل الضوضاء الفعال', score: 97, trend: 'أفضل أداء في السوق', icon: 'headphones', status: 'positive' },
      { label: 'عمر البطارية والشحن', score: 94, trend: 'إيجابي ممتاز', icon: 'battery_full', status: 'positive' },
      { label: 'الراحة أثناء الاستخدام', score: 90, trend: 'إيجابي عالي', icon: 'sentiment_satisfied', status: 'positive' },
      { label: 'سهولة الحمل والتنقل', score: 65, trend: 'حجم الحافظة كبير', icon: 'inventory_2', status: 'neutral' }
    ],
    pros: ['عزل صوتي لا مثيل له في الطائرات والمكاتب', 'وزن خفيف ووسائد مريحة جداً للأذن', 'ميكروفون الذكاء الاصطناعي نقي بالمكالمات', 'توصيل بجهازين بوقت واحد'],
    cons: ['لا تنطوي مثل موديل XM4 السابق', 'الحافظة تأخذ حيزاً كبيراً بالحقيبة', 'سعر مرتفع نسبياً'],
    quotes: [
      { text: 'وضعتها في الطائرة واختفى صوت المحرك تماماً، تجربة استماع أسطورية.', stars: 5, time: 'قبل يومين' },
      { text: 'السماعة توب ولكن تمنيت لو أنها تنطوي مثل السوني القديمة لتسهيل السفر.', stars: 4, time: 'قبل أسبوع' }
    ]
  },
  hotel: {
    title: 'فندق روف دبي (Rove Hotel)',
    category: 'فنادق وسياحة',
    type: 'hotel',
    rating: 4.6,
    reviewCount: 2150,
    score: 85,
    gist: 'موقع استراتيجي وغرف عصرية وشبابية، مناسب للعمل والسياحة وبأسعار منافسة.',
    imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuB0Q8KRe-khICqVVgK_o8dlDPZc4RVKMMK0tjybajxR_gdXMtQZx5AVSBM8jXThxdbrG3c-aJx0mCAxeMcls902QzambAAbohKCSHPzuxkOw2mNT-JhYMOCRJv96gSeHzwsrJhlU0T9ZW44AvYtiLeiGqAiWKEcGGap4-fZkDFGziuIuWRpNXdhmBOEREKQ1V9mVQJxfwf-O93UIQj71Upr2wyA942rrumI6ia1zuAPbIfATn1Yhgg7sw',
    sentiment: { positive: 78, neutral: 14, negative: 8 },
    insights: [
      { label: 'الموقع وسهولة الوصول', score: 95, trend: 'إيجابي استثنائي', icon: 'location_on', status: 'positive' },
      { label: 'النظافة والهدوء', score: 88, trend: 'إيجابي عالي', icon: 'cleaning_services', status: 'positive' },
      { label: 'القيمة مقابل السعر', score: 89, trend: 'إيجابي عالي', icon: 'savings', status: 'positive' },
      { label: 'مساحة الغرف', score: 70, trend: 'مقبول / متواضع', icon: 'hotel', status: 'neutral' }
    ],
    pros: ['قريب من المترو ومراكز التسوق', 'خدمة ذاتية ذكية وتسجيل سريع', 'واي فاي فائق السرعة', 'أجواء عصرية مريحة'],
    cons: ['الغرف صغيرة نوعاً ما للعائلات الكبيرة', 'تنوع الإفطار محدود قليلاً'],
    quotes: [
      { text: 'فندق شبابي رائع، كل شيء فيه مصمم بذكاء وسلاسة والموقع ممتاز.', stars: 5, time: 'قبل 5 أيام' },
      { text: 'الغرفة نظيفة لكن صغيرة، ينفع للمسافر الفردي أو رحلات العمل القصيرة.', stars: 4, time: 'قبل أسبوعين' }
    ]
  }
};

const aiSummarizer = {
  async analyze(input, options = {}) {
    const { onStepUpdate } = options;
    const steps = [
      'جاري قراءة التقييمات...',
      'جاري اكتشاف المواضيع المتكررة...',
      'جاري تحليل المشاعر...',
      'جاري اكتشاف الشكاوى المتكررة...',
      'جاري التحقق من اختلاف الآراء...',
      'جاري اختيار الأدلة الداعمة...',
      'اكتمل التحليل.'
    ];

    for (let i = 0; i < steps.length; i++) {
      if (onStepUpdate) onStepUpdate(i, steps[i]);
      await new Promise(r => setTimeout(r, 400));
    }

    const cleanInput = (input || '').trim().toLowerCase();

    if (cleanInput.includes('burger') || cleanInput.includes('برجر') || cleanInput.includes('مطعم')) {
      return { ...PRESET_PLACES.burger, id: 'analysis_' + Date.now(), date: new Date().toLocaleDateString('ar-SA') };
    }
    if (cleanInput.includes('sony') || cleanInput.includes('سوني') || cleanInput.includes('سماع') || cleanInput.includes('xm5')) {
      return { ...PRESET_PLACES.tech, id: 'analysis_' + Date.now(), date: new Date().toLocaleDateString('ar-SA') };
    }
    if (cleanInput.includes('rove') || cleanInput.includes('فندق') || cleanInput.includes('روف') || cleanInput.includes('hotel')) {
      return { ...PRESET_PLACES.hotel, id: 'analysis_' + Date.now(), date: new Date().toLocaleDateString('ar-SA') };
    }
    if (cleanInput.includes('coffee') || cleanInput.includes('كافيه') || cleanInput.includes('مقهى') || cleanInput.includes('أثر')) {
      return { ...PRESET_PLACES.coffee, id: 'analysis_' + Date.now(), date: new Date().toLocaleDateString('ar-SA') };
    }

    // Dynamic Generic Analyzer
    let title = 'تحليل مراجعات مخصصة';
    if (input.startsWith('http')) {
      try {
        const u = new URL(input);
        title = `تحليل رابط: ${u.hostname.replace('www.', '')}`;
      } catch (e) {
        title = 'تحليل رابط خارجي';
      }
    } else if (input.length > 0) {
      title = input.substring(0, 30) + '...';
    }

    let pos = 0, neg = 0;
    POSITIVE_KEYWORDS.forEach(k => { if (input.includes(k)) pos += 2; });
    NEGATIVE_KEYWORDS.forEach(k => { if (input.includes(k)) neg += 2; });

    let posPct = Math.min(Math.max(Math.round((pos / (pos + neg || 1)) * 75) + 15, 60), 92);
    let negPct = Math.min(Math.max(Math.round((neg / (pos + neg || 1)) * 50) + 5, 8), 30);
    let neuPct = Math.max(100 - posPct - negPct, 5);
    let score = Math.round(posPct * 0.95);

    return {
      id: 'analysis_' + Date.now(),
      title,
      category: 'خدمات ومنتجات',
      type: 'general',
      rating: +(score / 20).toFixed(1),
      reviewCount: 420,
      score,
      gist: 'إشادة عامة بالجودة ومستوى الخدمة، مع وجود بعض الملاحظات البسيطة في أوقات الذروة.',
      imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuAvePk_FhBCfCSCwsBMCYJ6GpUJr68W0woHLEZiMMZdQ1g3g_983y6y3hqPiZ-wPgvdyi16FuBihkPPnc6lX_EWnnYnwrrsU6cFqELML_RFoOUIjjQGS2jhX4ii_RQrh0X6LIf5P4duXzxDknhnrcPTkyLIUpm70JTZCYqqmndQp5R-kFj6EzKtdCbJBvudybzBFmFhWQjEC29NiRzXPPc6H66FMowKcE-6JwyFxXB4RuwdZzcuQ_kung',
      date: new Date().toLocaleDateString('ar-SA'),
      createdAt: new Date().toISOString(),
      sentiment: { positive: posPct, neutral: neuPct, negative: negPct },
      insights: [
        { label: 'مستوى الجودة', score: score + 2, trend: 'إيجابي (نمط قوي)', icon: 'auto_awesome', status: 'positive' },
        { label: 'التجربة العامة', score: score, trend: 'إيجابي', icon: 'thumb_up', status: 'positive' },
        { label: 'السعر والقيمة', score: Math.max(score - 15, 55), trend: 'آراء مختلطة', icon: 'payments', status: 'neutral' },
        { label: 'السرعة والخدمة', score: Math.max(score - 25, 45), trend: 'متوسط', icon: 'speed', status: 'negative' }
      ],
      pros: ['جودة الأداء والمستوى العام', 'سهولة التجربة ورضا الأغلبية', 'تجاوب جيد ومظهر أنيق'],
      cons: ['أوقات الذروة تشهد بعض البطء', 'تفاوت بسيط في آراء العملاء حول السعر'],
      quotes: [
        { text: 'المكان ممتاز ويستحق التجربة، والخدمة كانت سريعة والموظفون متعاونون جداً.', stars: 5, time: 'قبل 3 أيام' },
        { text: 'تجربة جيدة لكن تحتاج لبعض التطوير في تنظيم المواعيد وسرعة التجاوب.', stars: 3, time: 'قبل أسبوع' }
      ]
    };
  }
};

// --- 3. UI COMPONENTS ---

function Navbar({ activePage, setActivePage, user, onOpenAuth, onLogout }) {
  const navItems = [
    { id: 'home', label: 'الرئيسية', icon: 'home' },
    { id: 'history', label: 'تحليلاتي', icon: 'analytics' },
    { id: 'compare', label: 'مقارنة', icon: 'compare_arrows' },
    { id: 'profile', label: 'حسابي', icon: 'person' },
  ];

  return (
    <header className="sticky top-0 z-40 w-full bg-surface-container-lowest/90 backdrop-blur-md border-b border-outline-variant/30 shadow-sm transition-colors duration-200">
      <div className="max-w-7xl mx-auto px-4 md:px-8 h-16 flex items-center justify-between">
        
        {/* Brand Logo */}
        <div 
          onClick={() => setActivePage('home')}
          className="flex items-center gap-2 cursor-pointer select-none group"
        >
          <div className="w-10 h-10 rounded-xl bg-primary flex items-center justify-center text-on-primary shadow-md shadow-primary/20 group-hover:scale-105 transition-transform">
            <span className="material-symbols-outlined text-[24px]" style={{ fontVariationSettings: "'FILL' 1" }}>
              auto_awesome
            </span>
          </div>
          <div className="flex flex-col">
            <span className="font-headline-md text-xl font-bold text-primary tracking-tight">زبدة</span>
            <span className="text-[10px] text-on-surface-variant font-medium -mt-1">ذكاء التقييمات</span>
          </div>
        </div>

        {/* Desktop Navigation Links */}
        <nav className="hidden md:flex items-center gap-2">
          {navItems.map((item) => {
            const isActive = activePage === item.id;
            return (
              <button
                key={item.id}
                onClick={() => setActivePage(item.id)}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg font-label-md transition-all duration-150 ${
                  isActive
                    ? 'bg-primary-container/20 text-primary font-bold shadow-xs'
                    : 'text-on-surface-variant hover:text-primary hover:bg-surface-container-low'
                }`}
              >
                <span 
                  className="material-symbols-outlined text-[20px]"
                  style={{ fontVariationSettings: isActive ? "'FILL' 1" : "'FILL' 0" }}
                >
                  {item.icon}
                </span>
                <span>{item.label}</span>
              </button>
            );
          })}
        </nav>

        {/* Header Right Actions */}
        <div className="flex items-center gap-3">
          <button
            onClick={() => setActivePage('home')}
            className="hidden sm:flex items-center gap-1.5 bg-primary hover:bg-surface-tint text-on-primary font-label-md px-4 py-2 rounded-full shadow-sm hover:shadow-md transition-all active:scale-95 text-xs md:text-sm font-bold"
          >
            <span className="material-symbols-outlined text-[18px]">add_circle</span>
            <span>تحليل جديد</span>
          </button>

          {user ? (
            <div 
              onClick={() => setActivePage('profile')}
              className="flex items-center gap-2.5 p-1 pr-2 rounded-full hover:bg-surface-container-low cursor-pointer border border-outline-variant/30 transition-colors"
            >
              <div className="hidden lg:flex flex-col text-right">
                <span className="text-xs font-semibold text-on-surface leading-tight">
                  {user.fullName || user.displayName || 'أحمد محمد'}
                </span>
                <span className="text-[10px] text-secondary font-medium">{user.plan || 'عضو مسجل'}</span>
              </div>
              <div className="w-9 h-9 rounded-full overflow-hidden border-2 border-primary/20 shrink-0">
                <img 
                  src={user.photoURL || 'https://lh3.googleusercontent.com/aida-public/AB6AXuDhwfv0_8A02hQI8GDN0AvEvIMpK6nQ26A_ybujy8rwOtL4ebPTnEmRCpx_3Hukf_YDmZV9fOMEseLS0AtLvvJeVxfWUnJQGvIdxqKWa5FI_X5Sf5fiusej-cciBllpHQwYnKFxQ4uX6uw9-W1_6iJh94Vc75SNiPnp16uEgk5wwbDdQ6ppLZE4uKQ2I2I_mv5PjDO7IHP0NOf0I1W3e1nC90ep0x-OoXZbyVAOI7PTsShWMoQEvIIdZw'} 
                  alt={user.displayName}
                  className="w-full h-full object-cover"
                />
              </div>
            </div>
          ) : (
            <button
              onClick={onOpenAuth}
              className="flex items-center gap-1.5 bg-surface-container-high hover:bg-surface-container-highest text-on-surface font-label-md px-3.5 py-1.5 rounded-lg border border-outline-variant/40 transition-colors text-xs font-bold"
            >
              <span className="material-symbols-outlined text-[18px]">login</span>
              <span>دخول / تسجيل</span>
            </button>
          )}
        </div>

      </div>
    </header>
  );
}

function BottomNav({ activePage, setActivePage }) {
  const tabs = [
    { id: 'home', label: 'الرئيسية', icon: 'home' },
    { id: 'analyze_input', label: 'تحليل', icon: 'search' },
    { id: 'history', label: 'تحليلاتي', icon: 'analytics' },
    { id: 'compare', label: 'مقارنة', icon: 'compare_arrows' },
    { id: 'profile', label: 'حسابي', icon: 'person' },
  ];

  const handleTabClick = (id) => {
    if (id === 'analyze_input') {
      setActivePage('home');
      setTimeout(() => {
        const input = document.getElementById('main-url-input');
        if (input) input.focus();
      }, 100);
    } else {
      setActivePage(id);
    }
  };

  return (
    <nav className="md:hidden fixed bottom-0 left-0 right-0 w-full z-50 bg-surface-container-lowest/95 backdrop-blur-lg border-t border-outline-variant/30 shadow-[0_-4px_20px_rgba(0,0,0,0.06)] pb-safe">
      <div className="flex items-center justify-around h-16 px-2">
        {tabs.map((tab) => {
          const isActive = (activePage === tab.id) || (tab.id === 'analyze_input' && activePage === 'home');
          return (
            <button
              key={tab.id}
              onClick={() => handleTabClick(tab.id)}
              className={`flex flex-col items-center justify-center flex-1 h-full py-1 transition-all duration-150 active:scale-90 ${
                isActive ? 'text-primary' : 'text-on-surface-variant hover:text-on-surface'
              }`}
            >
              <div className={`w-12 h-7 flex items-center justify-center rounded-full transition-colors ${
                isActive ? 'bg-primary-fixed text-on-primary-fixed-variant shadow-xs' : ''
              }`}>
                <span 
                  className="material-symbols-outlined text-[22px]"
                  style={{ fontVariationSettings: isActive ? "'FILL' 1" : "'FILL' 0" }}
                >
                  {tab.icon}
                </span>
              </div>
              <span className={`text-[11px] mt-0.5 ${isActive ? 'font-bold text-primary' : 'font-medium text-on-surface-variant'}`}>
                {tab.label}
              </span>
            </button>
          );
        })}
      </div>
    </nav>
  );
}

function SentimentBar({ positive = 70, neutral = 20, negative = 10 }) {
  const total = positive + neutral + negative || 100;
  const pPct = Math.round((positive / total) * 100);
  const nPct = Math.round((neutral / total) * 100);
  const negPct = 100 - pPct - nPct;

  return (
    <div className="bg-surface-container-lowest rounded-2xl p-6 shadow-ambient border border-outline-variant/20">
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-title-lg text-title-lg text-on-surface flex items-center gap-2">
          <span className="material-symbols-outlined text-primary">pie_chart</span>
          <span>توزيع مشاعر التقييمات</span>
        </h3>
        <span className="text-xs font-semibold text-secondary bg-secondary-container/30 px-2.5 py-1 rounded-full border border-secondary/20">
          {pPct}% مشاعر إيجابية
        </span>
      </div>

      <div className="w-full flex h-4 rounded-full overflow-hidden mb-4 bg-surface-container shadow-inner">
        <div className="bg-secondary transition-all duration-700 hover:opacity-90" style={{ width: `${pPct}%` }} title={`إيجابي: ${pPct}%`} />
        <div className="bg-outline-variant transition-all duration-700 hover:opacity-90" style={{ width: `${nPct}%` }} title={`محايد: ${nPct}%`} />
        <div className="bg-error transition-all duration-700 hover:opacity-90" style={{ width: `${negPct}%` }} title={`سلبي: ${negPct}%`} />
      </div>

      <div className="flex flex-wrap justify-between items-center gap-3 pt-1 text-xs md:text-sm">
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded-full bg-secondary"></div>
          <span className="text-on-surface-variant font-medium">إيجابي <strong className="text-on-surface">{pPct}%</strong></span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded-full bg-outline-variant"></div>
          <span className="text-on-surface-variant font-medium">محايد <strong className="text-on-surface">{nPct}%</strong></span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded-full bg-error"></div>
          <span className="text-on-surface-variant font-medium">سلبي <strong className="text-on-surface">{negPct}%</strong></span>
        </div>
      </div>
    </div>
  );
}

function ScoreBadge({ score = 80 }) {
  let label = 'أداء جيد جداً وموثوق';
  let icon = 'trending_up';
  
  if (score >= 90) {
    label = 'أداء استثنائي ممتاز';
    icon = 'verified';
  } else if (score < 60) {
    label = 'يحتاج لمراجعة وحذر';
    icon = 'warning';
  }

  return (
    <div className="bg-gradient-to-br from-primary to-primary-container text-on-primary rounded-2xl p-6 shadow-ambient flex flex-col items-center justify-center text-center relative overflow-hidden group">
      <div className="absolute top-0 left-0 w-32 h-32 bg-white/15 rounded-full blur-2xl -translate-x-1/2 -translate-y-1/2 group-hover:scale-125 transition-transform"></div>
      
      <span className="font-label-md text-xs text-white/90 mb-2 z-10 font-semibold tracking-wide">
        درجة زبدة الذكية
      </span>

      <div className="flex items-baseline gap-1 z-10 my-1">
        <span className="font-display-lg text-5xl md:text-6xl font-bold tracking-tight">{score}</span>
        <span className="font-title-lg text-title-lg text-white/75">/ 100</span>
      </div>

      <div className="mt-4 w-full bg-white/20 rounded-full h-2 z-10 overflow-hidden">
        <div className="bg-white h-2 rounded-full transition-all duration-1000 ease-out" style={{ width: `${score}%` }}></div>
      </div>

      <div className="font-label-sm text-xs mt-3 text-white/95 z-10 flex items-center justify-center gap-1.5 bg-white/15 px-3 py-1 rounded-full backdrop-blur-xs">
        <span className="material-symbols-outlined text-[16px]">{icon}</span>
        <span>{label}</span>
      </div>
    </div>
  );
}

function AnalysisCard({ analysis, onClick, onDelete, isCompareSelected, onToggleCompare }) {
  const { id, title, score, gist, date, imageUrl, category } = analysis;

  return (
    <div 
      onClick={() => onClick && onClick(analysis)}
      className={`bg-surface-container-lowest rounded-2xl shadow-sm hover:shadow-md border transition-all duration-200 p-4 md:p-5 flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 cursor-pointer group ${
        isCompareSelected 
          ? 'border-primary ring-2 ring-primary/20 bg-primary/5' 
          : 'border-outline-variant/30 hover:border-primary/30'
      }`}
    >
      <div className="flex items-center gap-4 flex-1">
        <div className="w-20 h-20 md:w-24 md:h-24 rounded-xl overflow-hidden shrink-0 bg-surface-container-low flex items-center justify-center border border-outline-variant/20 relative">
          <img 
            src={imageUrl} 
            alt={title}
            className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
            onError={(e) => {
              e.target.onerror = null;
              e.target.src = 'https://lh3.googleusercontent.com/aida-public/AB6AXuCeOIIMWUuMa3zVxXvIKFpu3iNe8Dr0LNRd7fgsv5MGb-8m49IYe5js14TW0MTjOhJS3fsY6naZb6E1HarvUvTpcQ5anLq3NympfCA8-Y-ZbRsnC3GI9wMeD_n2M2zAXWhjAnGHSEWljRTCqDZianq13pwlrZSwC9UFnQQdY75EyW8EW0wcoqMgkdpbgzdywWLgv0AKo45rWRX63g8Fm64UIj5UV-O7p7YbzNV8blQoNZfzLtnrcncVJw';
            }}
          />
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center justify-between gap-2 mb-1">
            <h3 className="font-title-lg text-base md:text-lg font-bold text-on-surface group-hover:text-primary transition-colors truncate">
              {title}
            </h3>
            {score && (
              <div className="hidden md:flex items-center gap-1 bg-primary/10 text-primary px-2.5 py-0.5 rounded-full text-xs font-bold shrink-0">
                <span>{score}</span>
                <span className="material-symbols-outlined text-[13px]" style={{ fontVariationSettings: "'FILL' 1" }}>star</span>
              </div>
            )}
          </div>

          <p className="text-xs md:text-sm text-on-surface-variant line-clamp-2 mb-2 font-normal leading-relaxed">
            "{gist}"
          </p>

          <div className="flex items-center justify-between text-xs text-outline pt-1 border-t border-outline-variant/20">
            <span className="flex items-center gap-1">
              <span className="material-symbols-outlined text-[14px]">calendar_today</span>
              <span>{date || 'مؤخراً'}</span>
              {category && <span className="mr-2 text-on-surface-variant font-medium">• {category}</span>}
            </span>

            <span className="text-[11px] text-primary font-bold bg-primary/10 px-2 py-0.5 rounded">
              زبدة
            </span>
          </div>
        </div>
      </div>

      <div className="flex sm:flex-col items-center justify-end gap-2 shrink-0 border-t sm:border-t-0 sm:border-r border-outline-variant/20 pt-2 sm:pt-0 sm:pr-3">
        {onToggleCompare && (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              onToggleCompare(analysis);
            }}
            className={`p-2 rounded-lg text-xs flex items-center gap-1 transition-colors ${
              isCompareSelected
                ? 'bg-primary text-on-primary font-bold'
                : 'text-on-surface-variant hover:bg-surface-container-high'
            }`}
            title="إضافة للمقارنة"
          >
            <span className="material-symbols-outlined text-[18px]">compare_arrows</span>
            <span className="hidden sm:inline">{isCompareSelected ? 'محدد' : 'قارن'}</span>
          </button>
        )}

        {onDelete && (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              onDelete(id);
            }}
            className="p-2 rounded-lg text-on-surface-variant hover:text-error hover:bg-error-container/30 transition-colors"
            title="حذف من السجل"
          >
            <span className="material-symbols-outlined text-[18px]">delete</span>
          </button>
        )}
      </div>
    </div>
  );
}

// --- 4. MAIN APP COMPONENT ---
function App() {
  const [activePage, setActivePage] = useState('splash');
  const [user, setUser] = useState(null);
  const [userProfileData, setUserProfileData] = useState(null);
  const [userSummariesCount, setUserSummariesCount] = useState(0);
  const [analyses, setAnalyses] = useState([]);
  const [currentAnalysis, setCurrentAnalysis] = useState(null);
  const [analyzingStep, setAnalyzingStep] = useState(0);
  const [analyzingQuery, setAnalyzingQuery] = useState('');
  const [compareList, setCompareList] = useState([]);
  const [showAuthModal, setShowAuthModal] = useState(false);
  const [authModalMode, setAuthModalMode] = useState('register'); // Default to Sign Up when user asks for it

  // Auth & Firestore real-time initialization
  useEffect(() => {
    initFirebase();
    const currentUser = authService.getCurrentUser();
    setUser(currentUser);
    setUserProfileData(currentUser);

    const loadData = async () => {
      const list = await dbService.getAnalyses(currentUser?.uid || 'guest');
      setAnalyses(list);
      if (list && list.length > 0) {
        setCurrentAnalysis(list[0]);
      }
    };
    loadData();
  }, []);

  // Real-time Firestore sync for Profile & Summaries Count
  useEffect(() => {
    if (!user || !user.uid) return;

    // Real-time profile from Firestore 'users'
    const unsubUser = dbService.subscribeUserProfile(user.uid, (data) => {
      if (data) {
        setUserProfileData(prev => ({ ...prev, ...data }));
      }
    });

    // Real-time user analyses count from Firestore 'analyses'
    const unsubAnalyses = dbService.subscribeUserAnalyses(user.uid, (userList) => {
      if (userList) {
        setUserSummariesCount(userList.length);
        setAnalyses(userList);
      }
    });

    return () => {
      unsubUser();
      unsubAnalyses();
    };
  }, [user]);

  const handleStartAnalysis = async (inputQuery) => {
    setAnalyzingQuery(inputQuery);
    setAnalyzingStep(0);
    setActivePage('analyzing');

    try {
      const result = await aiSummarizer.analyze(inputQuery, {
        onStepUpdate: (stepIndex) => {
          setAnalyzingStep(stepIndex);
        }
      });

      const saved = await dbService.saveAnalysis(result, user?.uid);
      setCurrentAnalysis(saved);
      
      setAnalyses(prev => {
        const filtered = prev.filter(a => a.id !== saved.id);
        return [saved, ...filtered];
      });

      setTimeout(() => {
        setActivePage('result');
      }, 500);

    } catch (err) {
      console.error('Analysis error:', err);
      setActivePage('home');
      alert('حدث خطأ أثناء معالجة التقييمات.');
    }
  };

  const handleOpenPreset = (presetKey) => {
    const list = getDefaultAnalyses();
    const found = list.find(item => item.id.includes(presetKey)) || list[0];
    setCurrentAnalysis(found);
    setActivePage('result');
  };

  const handleDeleteAnalysis = async (id) => {
    if (window.confirm('هل أنت متأكد من رغبتك في حذف هذا التحليل؟')) {
      await dbService.deleteAnalysis(id, user?.uid);
      setAnalyses(prev => prev.filter(a => a.id !== id));
      if (currentAnalysis?.id === id) {
        setCurrentAnalysis(analyses.find(a => a.id !== id) || null);
      }
    }
  };

  const handleToggleCompare = (analysis) => {
    setCompareList(prev => {
      const exists = prev.some(a => a.id === analysis.id);
      if (exists) {
        return prev.filter(a => a.id !== analysis.id);
      } else {
        if (prev.length >= 2) return [prev[1], analysis];
        return [...prev, analysis];
      }
    });
  };

  // Auth Success Callback: Redirect directly to Home page
  const handleAuthSuccess = async (authUser) => {
    setUser(authUser);
    setUserProfileData(authUser);
    setShowAuthModal(false);
    setActivePage('home'); // Redirect to Home
    
    // Load fresh user data
    const userAnalyses = await dbService.getAnalyses(authUser.uid);
    setAnalyses(userAnalyses);
    setUserSummariesCount(userAnalyses.length);
  };

  return (
    <div className="min-h-screen bg-background text-on-background flex flex-col font-body-md">
      
      {/* Top Navbar */}
      {activePage !== 'splash' && activePage !== 'analyzing' && (
        <Navbar
          activePage={activePage}
          setActivePage={setActivePage}
          user={userProfileData || user}
          onOpenAuth={() => {
            setAuthModalMode('login');
            setShowAuthModal(true);
          }}
        />
      )}

      {/* Pages Switcher */}
      <div className="flex-1">
        
        {/* Splash Page */}
        {activePage === 'splash' && (
          <div className="min-h-screen bg-background text-on-background flex flex-col items-center justify-center relative overflow-hidden font-body-md px-4 select-none">
            <div className="fixed inset-0 pointer-events-none overflow-hidden z-0">
              <div className="absolute top-[-10%] right-[-10%] w-[55vw] h-[55vw] rounded-full bg-primary-container/15 blur-3xl animate-pulse"></div>
              <div className="absolute bottom-[-10%] left-[-10%] w-[65vw] h-[65vw] rounded-full bg-secondary-container/20 blur-3xl"></div>
            </div>

            <main className="flex flex-col items-center justify-center w-full max-w-md h-full relative z-10 text-center py-12">
              <div className="mb-6 flex flex-col items-center animate-bounce-short">
                <div className="w-28 h-28 md:w-36 md:h-36 bg-gradient-to-tr from-primary to-primary-container rounded-3xl flex items-center justify-center shadow-xl shadow-primary/25 mb-4 relative overflow-hidden group hover:scale-105 transition-transform">
                  <span className="material-symbols-outlined text-on-primary text-[56px] md:text-[72px] z-10" style={{ fontVariationSettings: "'FILL' 1" }}>
                    auto_awesome
                  </span>
                  <div className="absolute inset-0 bg-gradient-to-tr from-transparent via-white/10 to-white/30 z-0"></div>
                </div>

                <h1 className="font-display-lg text-4xl md:text-5xl font-bold text-primary tracking-tight">
                  زبدة
                </h1>
                <span className="text-xs uppercase tracking-widest text-on-surface-variant font-semibold mt-1">
                  Zubdah • AI Review Intelligence
                </span>
              </div>

              <div className="mb-8 px-4 max-w-sm">
                <p className="font-title-lg text-lg md:text-xl text-on-surface-variant leading-relaxed">
                  خلّ زبدة تختصر لك آراء العملاء.
                </p>
                <p className="text-sm md:text-base text-on-surface-variant/80 mt-2 leading-relaxed">
                  حلّل تقييمات المطاعم والمنتجات واحصل على خلاصة واضحة لأهم الإيجابيات والسلبيات والشكاوى في ثوانٍ.
                </p>
              </div>

              <div className="w-full px-4 flex flex-col gap-3 items-center justify-center">
                <button 
                  onClick={() => setActivePage('home')}
                  className="bg-primary hover:bg-surface-tint active:scale-95 text-on-primary transition-all duration-200 font-label-md py-4 px-8 rounded-full shadow-lg shadow-primary/25 hover:shadow-xl w-full max-w-sm flex items-center justify-center gap-2 group text-base font-bold"
                >
                  <span>ابدأ الآن</span>
                  <span className="material-symbols-outlined transform group-hover:-translate-x-1.5 transition-transform">
                    arrow_back
                  </span>
                </button>

                <button
                  onClick={() => {
                    setAuthModalMode('register');
                    setShowAuthModal(true);
                  }}
                  className="bg-surface-container-high hover:bg-surface-container-highest text-primary font-bold text-xs py-2.5 px-6 rounded-full border border-primary/20 transition-all w-full max-w-sm"
                >
                  إنشاء حساب جديد
                </button>
              </div>
            </main>
          </div>
        )}

        {/* Home Page */}
        {activePage === 'home' && (
          <div className="min-h-screen bg-background text-on-background pb-24 md:pb-16 font-body-md">
            <main className="pt-8 md:pt-14 px-4 md:px-8 max-w-6xl mx-auto">
              
              <section className="text-center py-6 md:py-10 mb-8 max-w-4xl mx-auto">
                <div className="inline-flex items-center gap-2 bg-primary/10 text-primary px-4 py-1.5 rounded-full font-label-md text-xs md:text-sm font-semibold mb-4 border border-primary/20 animate-fade-in">
                  <span className="material-symbols-outlined text-[18px]">auto_awesome</span>
                  <span>الجيل الجديد من ملخصات التقييمات الذكية</span>
                </div>

                <h1 className="font-display-lg text-3xl md:text-5xl lg:text-6xl font-bold text-on-background mb-4 tracking-tight leading-tight">
                  لا تقرأ كل التقييمات. <span className="text-primary">خذ الزبدة.</span>
                </h1>

                <p className="font-body-lg text-base md:text-lg text-on-surface-variant max-w-2xl mx-auto mb-8 leading-relaxed">
                  ألصق رابط مطعم أو منتج من خرائط جوجل أو أمازون أو جاهز، وسيقوم الذكاء الاصطناعي باستخراج خلاصة واضحة لأهم الإيجابيات والسلبيات والشكاوى المتكررة.
                </p>

                {/* Input Form */}
                <form 
                  onSubmit={(e) => {
                    e.preventDefault();
                    const val = document.getElementById('main-url-input')?.value;
                    if (val) handleStartAnalysis(val);
                  }} 
                  className="max-w-2xl mx-auto relative flex flex-col md:flex-row gap-3 items-stretch justify-center"
                >
                  <div className="relative flex-1">
                    <input
                      id="main-url-input"
                      type="text"
                      placeholder="ألصق رابط المطعم أو المنتج هنا (Google Maps, Amazon, Jahez...)"
                      className="w-full bg-surface-container-lowest border border-outline-variant/60 text-on-surface font-body-md text-sm md:text-base rounded-2xl md:rounded-full py-4 pl-4 pr-12 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all shadow-sm placeholder:text-outline h-14"
                      required
                    />
                    <span className="material-symbols-outlined absolute right-4 top-1/2 -translate-y-1/2 text-outline text-[22px]">
                      link
                    </span>
                  </div>

                  <button
                    type="submit"
                    className="bg-primary hover:bg-surface-tint active:scale-95 text-on-primary font-label-md rounded-2xl md:rounded-full px-8 py-4 h-14 hover:shadow-lg transition-all shadow-md flex items-center justify-center gap-2 font-bold whitespace-nowrap text-sm md:text-base"
                  >
                    <span>تحليل التقييمات</span>
                    <span className="material-symbols-outlined text-[20px]">analytics</span>
                  </button>
                </form>

                {/* Quick Demo Chips */}
                <div className="mt-6 flex flex-wrap items-center justify-center gap-2">
                  <span className="text-xs text-on-surface-variant font-medium ml-2">أمثلة سريعة للتجربة:</span>
                  {[
                    { label: '🍔 مطعم بيت البرجر', q: 'burger' },
                    { label: '🎧 سماعات سوني XM5', q: 'sony' },
                    { label: '🏨 فندق روف دبي', q: 'rove' },
                    { label: '☕ مقهى الأثر المختص', q: 'coffee' }
                  ].map((chip, idx) => (
                    <button
                      key={idx}
                      type="button"
                      onClick={() => handleStartAnalysis(chip.q)}
                      className="bg-surface-container hover:bg-surface-container-high text-on-surface text-xs font-semibold px-3 py-1.5 rounded-full border border-outline-variant/30 transition-all hover:scale-105 active:scale-95"
                    >
                      {chip.label}
                    </button>
                  ))}
                </div>

              </section>

              {/* Visual Example Card */}
              <section className="max-w-4xl mx-auto mb-16">
                <div 
                  onClick={() => handleOpenPreset('burger')}
                  className="bg-surface-container-lowest rounded-2xl shadow-[0_4px_24px_rgba(99,102,241,0.06)] border border-outline-variant/40 p-6 md:p-8 hover:shadow-[0_8px_32px_rgba(99,102,241,0.12)] hover:border-primary/30 transition-all duration-300 cursor-pointer group"
                >
                  <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 pb-6 border-b border-outline-variant/30 gap-4">
                    <div>
                      <div className="flex items-center gap-2 mb-2">
                        <span className="material-symbols-outlined text-primary text-2xl">restaurant</span>
                        <h2 className="font-headline-md text-xl md:text-2xl font-bold text-on-surface group-hover:text-primary transition-colors">
                          مطعم بيت البرجر
                        </h2>
                      </div>
                      <div className="flex items-center gap-2 text-on-surface-variant text-xs md:text-sm font-medium">
                        <span className="material-symbols-outlined text-tertiary text-[18px]" style={{ fontVariationSettings: "'FILL' 1" }}>star</span>
                        <span className="font-bold text-on-surface">4.3</span>
                        <span>(1,284 تقييم حقيقي)</span>
                      </div>
                    </div>

                    <div className="bg-surface-container py-3 px-5 rounded-xl text-right border border-outline-variant/20 max-w-md">
                      <p className="text-xs text-on-surface-variant font-bold mb-1 flex items-center gap-1">
                        <span className="material-symbols-outlined text-primary text-[15px]">auto_awesome</span>
                        الزبدة
                      </p>
                      <p className="font-title-lg text-sm md:text-base font-semibold text-primary">
                        "الأكل ممتاز واللحم طازج، لكن الخدمة وتأخر الطلبات مشكلة متكررة وقت الزحمة."
                      </p>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="bg-surface-container-low rounded-xl p-5 border border-outline-variant/20 flex flex-col items-center justify-center text-center">
                      <div className="flex items-center gap-1.5 mb-2 text-secondary bg-secondary-container/40 px-3 py-1 rounded-full border border-secondary/20 text-xs font-bold">
                        <span className="material-symbols-outlined text-[16px]">trending_up</span>
                        <span>نمط قوي</span>
                      </div>
                      <h3 className="font-title-lg text-base font-bold text-on-surface mb-1">جودة الأكل</h3>
                      <p className="font-display-lg text-3xl font-bold text-secondary mb-1">92%</p>
                      <p className="text-xs text-on-surface-variant font-medium">إيجابي للغاية</p>
                    </div>

                    <div className="bg-surface-container-low rounded-xl p-5 border border-outline-variant/20 flex flex-col items-center justify-center text-center">
                      <div className="flex items-center gap-1.5 mb-2 text-error bg-error-container/40 px-3 py-1 rounded-full border border-error/20 text-xs font-bold">
                        <span className="material-symbols-outlined text-[16px]">trending_down</span>
                        <span>نمط متكرر</span>
                      </div>
                      <h3 className="font-title-lg text-base font-bold text-on-surface mb-1">وقت الانتظار والخدمة</h3>
                      <p className="font-display-lg text-3xl font-bold text-error mb-1">45%</p>
                      <p className="text-xs text-on-surface-variant font-medium">سلبي (شكاوى متكررة)</p>
                    </div>
                  </div>

                  <div className="mt-4 pt-3 text-center border-t border-outline-variant/20 text-xs font-bold text-primary flex items-center justify-center gap-1">
                    <span>انقر للاطلاع على التقرير التفصيلي الكامل</span>
                    <span className="material-symbols-outlined text-[16px]">arrow_back</span>
                  </div>
                </div>
              </section>

              {/* How it works */}
              <section className="py-8 max-w-5xl mx-auto mb-12">
                <div className="text-center mb-10">
                  <h2 className="font-headline-md text-2xl md:text-3xl font-bold text-on-background mb-2">
                    كيف يعمل زبدة؟
                  </h2>
                  <p className="text-sm text-on-surface-variant">ثلاث خطوات بسيطة توفر عليك ساعات من القراءة والتشتت</p>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div className="bg-surface-container-lowest p-6 rounded-2xl border border-outline-variant/30 flex flex-col items-center text-center shadow-xs">
                    <div className="w-16 h-16 rounded-2xl bg-surface-container-high flex items-center justify-center mb-4 text-primary shadow-xs">
                      <span className="material-symbols-outlined text-[32px]">content_paste</span>
                    </div>
                    <h3 className="font-title-lg text-lg font-bold text-on-surface mb-2">١. ألصق</h3>
                    <p className="font-body-md text-xs md:text-sm text-on-surface-variant leading-relaxed">
                      ألصق رابط المنتج أو المطعم من خرائط جوجل أو المتاجر الإلكترونية أو تطبيقات التوصيل.
                    </p>
                  </div>

                  <div className="bg-surface-container-lowest p-6 rounded-2xl border border-primary/30 flex flex-col items-center text-center shadow-sm relative">
                    <div className="w-16 h-16 rounded-2xl bg-primary flex items-center justify-center mb-4 text-on-primary shadow-md shadow-primary/20">
                      <span className="material-symbols-outlined text-[32px]">psychology</span>
                    </div>
                    <h3 className="font-title-lg text-lg font-bold text-primary mb-2">٢. حلّل</h3>
                    <p className="font-body-md text-xs md:text-sm text-on-surface-variant leading-relaxed">
                      يقوم محرك الذكاء الاصطناعي بقراءة مئات التقييمات وتحليل المشاعر وتصنيف المواضيع.
                    </p>
                  </div>

                  <div className="bg-surface-container-lowest p-6 rounded-2xl border border-outline-variant/30 flex flex-col items-center text-center shadow-xs">
                    <div className="w-16 h-16 rounded-2xl bg-surface-container-high flex items-center justify-center mb-4 text-secondary shadow-xs">
                      <span className="material-symbols-outlined text-[32px]">insights</span>
                    </div>
                    <h3 className="font-title-lg text-lg font-bold text-on-surface mb-2">٣. خذ الزبدة</h3>
                    <p className="font-body-md text-xs md:text-sm text-on-surface-variant leading-relaxed">
                      احصل على درجة الجودة وملخص دقيق للإيجابيات وأبرز الشكاوى الموثقة بأدلة العملاء.
                    </p>
                  </div>
                </div>
              </section>

            </main>
          </div>
        )}

        {/* Analyzing Progress Page */}
        {activePage === 'analyzing' && (
          <div className="min-h-screen bg-surface text-on-surface font-body-md flex flex-col items-center justify-center p-4 md:p-8 overflow-hidden relative select-none">
            <div className="fixed inset-0 pointer-events-none z-0 overflow-hidden">
              <div className="absolute top-[-10%] right-[-5%] w-[40vw] h-[40vw] bg-surface-container-high rounded-full blur-3xl opacity-40 animate-pulse"></div>
              <div className="absolute bottom-[-10%] left-[-10%] w-[50vw] h-[50vw] bg-surface-container-highest rounded-full blur-3xl opacity-30"></div>
            </div>

            <main className="w-full max-w-2xl relative z-10 flex flex-col items-center justify-center py-8">
              <div className="text-center mb-8">
                <div className="w-16 h-16 rounded-2xl bg-primary text-on-primary flex items-center justify-center mx-auto mb-3 shadow-lg shadow-primary/25 animate-bounce-short">
                  <span className="material-symbols-outlined text-[36px]" style={{ fontVariationSettings: "'FILL' 1" }}>
                    auto_awesome
                  </span>
                </div>
                <h1 className="font-display-lg text-3xl md:text-4xl font-bold text-primary mb-2">زبدة</h1>
                <p className="font-title-lg text-base md:text-lg text-on-surface-variant">الذكاء الاصطناعي يقوم بتحليل البيانات</p>
              </div>

              <div className="bg-surface-container-lowest rounded-2xl shadow-sm border border-outline-variant/30 w-full p-6 md:p-8 relative overflow-hidden backdrop-blur-sm">
                <div className="space-y-4 relative z-10">
                  {[
                    'جاري قراءة التقييمات...',
                    'جاري اكتشاف المواضيع المتكررة...',
                    'جاري تحليل المشاعر...',
                    'جاري اكتشاف الشكاوى المتكررة...',
                    'جاري التحقق من اختلاف الآراء...',
                    'جاري اختيار الأدلة الداعمة...',
                    'اكتمل التحليل.'
                  ].map((stepLabel, idx) => {
                    const isCompleted = idx < analyzingStep;
                    const isActive = idx === analyzingStep;
                    return (
                      <div
                        key={idx}
                        className={`flex items-center gap-4 transition-all duration-300 ${
                          isActive ? 'scale-[1.02] transform' : isCompleted ? 'opacity-60' : 'opacity-25'
                        }`}
                      >
                        {isCompleted ? (
                          <div className="w-8 h-8 rounded-full bg-secondary-container text-on-secondary-container flex items-center justify-center shrink-0 shadow-xs">
                            <span className="material-symbols-outlined text-[18px] font-bold">check</span>
                          </div>
                        ) : isActive ? (
                          <div className="w-8 h-8 rounded-full bg-primary-container text-on-primary-container flex items-center justify-center shrink-0 relative shadow-md shadow-primary/30">
                            <div className="w-2.5 h-2.5 rounded-full bg-on-primary-container animate-ping"></div>
                            <div className="w-2.5 h-2.5 rounded-full bg-on-primary-container absolute"></div>
                          </div>
                        ) : (
                          <div className="w-8 h-8 rounded-full border-2 border-outline-variant/40 flex items-center justify-center shrink-0">
                            <span className="text-[11px] font-bold text-outline">{idx + 1}</span>
                          </div>
                        )}

                        <span className={`text-sm md:text-base ${isActive ? 'font-headline-md font-bold text-primary' : isCompleted ? 'text-on-surface' : 'text-on-surface-variant font-medium'}`}>
                          {stepLabel}
                        </span>
                      </div>
                    );
                  })}
                </div>
              </div>

              <div className="mt-8 text-center">
                <p className="font-title-lg text-sm md:text-base text-primary bg-primary-fixed-dim/40 px-6 py-2 rounded-full inline-block shadow-xs border border-primary/20">
                  هذه هي زبدة.
                </p>
              </div>
            </main>
          </div>
        )}

        {/* Result Details Page */}
        {activePage === 'result' && currentAnalysis && (
          <div className="min-h-screen bg-background text-on-background pb-28 md:pb-16 font-body-md">
            <main className="max-w-6xl mx-auto px-4 md:px-8 py-6 md:py-10 space-y-8">
              
              <div className="flex flex-wrap items-center justify-between gap-4 border-b border-outline-variant/30 pb-4">
                <button
                  onClick={() => setActivePage('home')}
                  className="inline-flex items-center gap-1.5 text-xs md:text-sm font-bold text-on-surface-variant hover:text-primary bg-surface-container-low hover:bg-surface-container px-4 py-2 rounded-full transition-colors"
                >
                  <span className="material-symbols-outlined text-[18px]">arrow_forward</span>
                  <span>العودة للبحث</span>
                </button>

                <div className="flex items-center gap-2">
                  <button
                    onClick={() => {
                      dbService.saveAnalysis(currentAnalysis, user?.uid);
                      alert('تم حفظ التحليل في سجل تحليلاتك!');
                    }}
                    className="flex items-center gap-1 text-xs md:text-sm font-semibold px-4 py-2 rounded-full bg-surface-container-lowest text-on-surface border border-outline-variant/40 hover:bg-surface-container-low transition-all"
                  >
                    <span className="material-symbols-outlined text-[18px]">bookmark</span>
                    <span>حفظ التحليل</span>
                  </button>

                  <button
                    onClick={() => {
                      handleToggleCompare(currentAnalysis);
                      setActivePage('compare');
                    }}
                    className="flex items-center gap-1 text-xs md:text-sm font-semibold px-4 py-2 rounded-full bg-primary-container/20 text-primary border border-primary/30 hover:bg-primary-container/30 transition-all"
                  >
                    <span className="material-symbols-outlined text-[18px]">compare_arrows</span>
                    <span>مقارنة</span>
                  </button>
                </div>
              </div>

              {/* Profile Header */}
              <section className="bg-surface-container-lowest rounded-2xl p-6 md:p-8 shadow-sm border border-outline-variant/30 flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
                <div className="flex items-center gap-5">
                  <div className="w-20 h-20 md:w-24 md:h-24 rounded-2xl overflow-hidden shrink-0 bg-surface-container-low border border-outline-variant/30 shadow-xs">
                    <img 
                      src={currentAnalysis.imageUrl} 
                      alt={currentAnalysis.title}
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <div>
                    <div className="flex flex-wrap items-center gap-2 mb-2">
                      <h1 className="font-headline-lg text-2xl md:text-3xl font-bold text-on-surface">
                        {currentAnalysis.title}
                      </h1>
                      {currentAnalysis.category && (
                        <span className="bg-primary/10 text-primary text-xs font-semibold px-3 py-1 rounded-full">
                          {currentAnalysis.category}
                        </span>
                      )}
                    </div>
                    <div className="flex items-center gap-3 text-xs md:text-sm text-on-surface-variant font-medium">
                      <div className="flex items-center gap-1 text-tertiary font-bold bg-tertiary/10 px-2 py-0.5 rounded-md">
                        <span className="material-symbols-outlined text-[16px]" style={{ fontVariationSettings: "'FILL' 1" }}>star</span>
                        <span>{currentAnalysis.rating}</span>
                      </div>
                      <span>•</span>
                      <span>بناءً على <strong>{(currentAnalysis.reviewCount || 1200).toLocaleString()}</strong> تقييم حقيقي</span>
                    </div>
                  </div>
                </div>
              </section>

              {/* The Gist & Score */}
              <section className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="md:col-span-2 bg-surface-container-lowest rounded-2xl p-6 md:p-8 shadow-ambient border border-outline-variant/30 flex flex-col justify-between">
                  <div>
                    <div className="flex items-center gap-3 mb-4">
                      <div className="p-2 bg-primary-container rounded-xl text-on-primary-container shadow-xs">
                        <span className="material-symbols-outlined text-[24px]">auto_awesome</span>
                      </div>
                      <h3 className="font-headline-md text-xl md:text-2xl font-bold text-on-surface">الزبدة</h3>
                    </div>
                    <p className="font-title-lg text-base md:text-lg text-on-surface-variant leading-relaxed font-semibold">
                      "{currentAnalysis.gist}"
                    </p>
                  </div>

                  <div className="mt-6 pt-4 border-t border-outline-variant/20 flex items-center justify-between text-xs text-outline font-medium">
                    <span className="flex items-center gap-1 text-secondary font-bold">
                      <span className="material-symbols-outlined text-[16px]">verified</span>
                      <span>خلاصة محايدة ومستخلصة بدقة الذكاء الاصطناعي</span>
                    </span>
                    <span>تحديث فوري</span>
                  </div>
                </div>

                <ScoreBadge score={currentAnalysis.score} />
              </section>

              {/* Key Insights */}
              <section>
                <div className="flex items-center justify-between mb-4">
                  <h3 className="font-title-lg text-lg md:text-xl font-bold text-on-surface flex items-center gap-2">
                    <span className="material-symbols-outlined text-primary">insights</span>
                    <span>أهم الرؤى والأنماط</span>
                  </h3>
                  <span className="text-xs text-on-surface-variant">تحليل مفصل للمحاور الأساسية</span>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                  {currentAnalysis.insights?.map((item, idx) => {
                    const isPos = item.status === 'positive';
                    const isNeg = item.status === 'negative';
                    return (
                      <div key={idx} className="bg-surface-container-lowest rounded-2xl p-5 shadow-ambient border border-outline-variant/20 flex flex-col justify-between">
                        <div className="flex justify-between items-start mb-3">
                          <span className="text-xs md:text-sm font-semibold text-on-surface-variant">{item.label}</span>
                          <span className={`material-symbols-outlined ${isPos ? 'text-secondary' : isNeg ? 'text-error' : 'text-tertiary'}`}>
                            {item.icon || 'star'}
                          </span>
                        </div>
                        <div className="font-headline-md text-2xl md:text-3xl font-bold text-on-surface mb-2">
                          {item.score}%
                        </div>
                        <div className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-bold ${
                          isPos ? 'bg-secondary/10 text-secondary border border-secondary/20' : isNeg ? 'bg-error/10 text-error border border-error/20' : 'bg-tertiary/10 text-tertiary border border-tertiary/20'
                        }`}>
                          <span className="material-symbols-outlined text-[14px]">
                            {isPos ? 'arrow_upward' : isNeg ? 'arrow_downward' : 'horizontal_rule'}
                          </span>
                          <span>{item.trend}</span>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </section>

              {/* Pros & Cons */}
              <section className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="bg-surface-container-lowest rounded-2xl p-6 md:p-7 shadow-ambient border border-secondary/20 bg-gradient-to-b from-surface-container-lowest to-secondary-container/5">
                  <h3 className="font-title-lg text-lg font-bold text-on-surface mb-4 flex items-center gap-2">
                    <span className="material-symbols-outlined text-secondary" style={{ fontVariationSettings: "'FILL' 1" }}>
                      favorite
                    </span>
                    <span>ماذا يحب الناس؟ (أبرز الإيجابيات)</span>
                  </h3>
                  <div className="flex flex-wrap gap-2.5">
                    {currentAnalysis.pros?.map((pro, idx) => (
                      <span key={idx} className="bg-secondary/10 text-secondary border border-secondary/20 px-3.5 py-2 rounded-xl text-xs md:text-sm font-semibold flex items-center gap-1.5 shadow-xs">
                        <span className="material-symbols-outlined text-[15px]">check_circle</span>
                        <span>{pro}</span>
                      </span>
                    ))}
                  </div>
                </div>

                <div className="bg-surface-container-lowest rounded-2xl p-6 md:p-7 shadow-ambient border border-error/20 bg-gradient-to-b from-surface-container-lowest to-error-container/5">
                  <h3 className="font-title-lg text-lg font-bold text-on-surface mb-4 flex items-center gap-2">
                    <span className="material-symbols-outlined text-error" style={{ fontVariationSettings: "'FILL' 1" }}>
                      report_problem
                    </span>
                    <span>أبرز الشكاوى والملاحظات المتكررة</span>
                  </h3>
                  <div className="flex flex-wrap gap-2.5">
                    {currentAnalysis.cons?.map((con, idx) => (
                      <span key={idx} className="bg-error/10 text-error border border-error/20 px-3.5 py-2 rounded-xl text-xs md:text-sm font-semibold flex items-center gap-1.5 shadow-xs">
                        <span className="material-symbols-outlined text-[15px]">error</span>
                        <span>{con}</span>
                      </span>
                    ))}
                  </div>
                </div>
              </section>

              {/* Supporting Quotes */}
              <section>
                <div className="flex items-center justify-between mb-4">
                  <h3 className="font-title-lg text-lg md:text-xl font-bold text-on-surface flex items-center gap-2">
                    <span className="material-symbols-outlined text-primary">format_quote</span>
                    <span>لماذا قالت زبدة ذلك؟ (أدلة من تقييمات العملاء)</span>
                  </h3>
                  <span className="text-xs text-on-surface-variant">اقتباسات موثقة من مراجعات حقيقية</span>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {currentAnalysis.quotes?.map((quote, idx) => (
                    <div key={idx} className={`bg-surface-container-low rounded-2xl p-5 border-r-4 flex items-start gap-4 ${quote.stars >= 4 ? 'border-secondary' : 'border-error'}`}>
                      <span className="material-symbols-outlined text-on-surface-variant opacity-40 text-3xl mt-0.5">format_quote</span>
                      <div className="flex-1">
                        <p className="font-body-md text-xs md:text-sm text-on-surface italic leading-relaxed">
                          "{quote.text}"
                        </p>
                        <div className="flex items-center justify-between text-[11px] text-on-surface-variant mt-3 pt-2 border-t border-outline-variant/20">
                          <span className="flex items-center gap-1 font-bold">
                            <span className="material-symbols-outlined text-[14px] text-tertiary" style={{ fontVariationSettings: "'FILL' 1" }}>star</span>
                            <span>تقييم {quote.stars} نجوم</span>
                          </span>
                          <span>{quote.time}</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </section>

              {/* Sentiment Bar */}
              <SentimentBar 
                positive={currentAnalysis.sentiment?.positive}
                neutral={currentAnalysis.sentiment?.neutral}
                negative={currentAnalysis.sentiment?.negative}
              />

            </main>
          </div>
        )}

        {/* History Page */}
        {activePage === 'history' && (
          <div className="min-h-screen bg-background text-on-background pb-28 md:pb-16 font-body-md">
            <main className="max-w-5xl mx-auto px-4 md:px-8 py-6 md:py-10">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
                <div>
                  <h1 className="font-headline-lg text-2xl md:text-3xl font-bold text-on-background flex items-center gap-2">
                    <span className="material-symbols-outlined text-primary text-3xl">analytics</span>
                    <span>تحليلاتي المحفوظة</span>
                  </h1>
                  <p className="text-xs md:text-sm text-on-surface-variant mt-1">
                    جميع التقارير والملخصات التي قمت بتحليلها سابقاً محفوظة هنا
                  </p>
                </div>

                <button
                  onClick={() => setActivePage('home')}
                  className="self-start sm:self-auto bg-primary hover:bg-surface-tint text-on-primary font-label-md px-5 py-2.5 rounded-full shadow-sm hover:shadow-md transition-all flex items-center gap-1.5 text-xs md:text-sm font-bold active:scale-95"
                >
                  <span className="material-symbols-outlined text-[18px]">add</span>
                  <span>تحليل جديد</span>
                </button>
              </div>

              {analyses.length > 0 ? (
                <div className="space-y-4">
                  {analyses.map((item) => (
                    <AnalysisCard
                      key={item.id}
                      analysis={item}
                      onClick={(a) => {
                        setCurrentAnalysis(a);
                        setActivePage('result');
                      }}
                      onDelete={handleDeleteAnalysis}
                      isCompareSelected={compareList.some(c => c.id === item.id)}
                      onToggleCompare={handleToggleCompare}
                    />
                  ))}
                </div>
              ) : (
                <div className="bg-surface-container-lowest rounded-2xl p-12 text-center border border-outline-variant/30 shadow-xs">
                  <h3 className="font-title-lg text-lg font-bold text-on-surface mb-2">لا توجد تحليلات محفوظة</h3>
                  <button onClick={() => setActivePage('home')} className="bg-primary text-on-primary px-6 py-2 rounded-full text-xs font-bold">
                    ابدأ أول تحليل
                  </button>
                </div>
              )}
            </main>
          </div>
        )}

        {/* Compare Page */}
        {activePage === 'compare' && (
          <div className="min-h-screen bg-background text-on-background pb-28 md:pb-16 font-body-md">
            <main className="max-w-6xl mx-auto px-4 md:px-8 py-6 md:py-10">
              <div className="text-center mb-8">
                <div className="inline-flex items-center gap-1.5 bg-primary/10 text-primary px-3.5 py-1 rounded-full text-xs font-semibold mb-2">
                  <span className="material-symbols-outlined text-[16px]">compare_arrows</span>
                  <span>مقارنة ذكية مدعومة بالذكاء الاصطناعي</span>
                </div>
                <h1 className="font-headline-lg text-2xl md:text-3xl font-bold text-on-background">
                  مقارنة الخيارات وتحديد الزبدة
                </h1>
              </div>

              {analyses.length >= 2 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {[analyses[0], analyses[1]].map((item, idx) => (
                    <div key={idx} className="bg-surface-container-lowest rounded-2xl p-6 border border-outline-variant/30 shadow-sm flex flex-col justify-between">
                      <div>
                        <div className="flex items-center gap-4 mb-4">
                          <img src={item.imageUrl} alt={item.title} className="w-16 h-16 rounded-xl object-cover" />
                          <div>
                            <h2 className="font-bold text-lg text-on-surface">{item.title}</h2>
                            <span className="text-xs text-on-surface-variant font-medium">{item.category}</span>
                          </div>
                        </div>

                        <div className="bg-surface-container-low p-4 rounded-xl mb-4 flex items-center justify-between">
                          <span className="text-xs font-bold text-on-surface-variant">درجة زبدة:</span>
                          <span className="text-2xl font-bold text-primary">{item.score} / 100</span>
                        </div>

                        <div className="mb-4">
                          <span className="text-xs font-bold text-outline block mb-1">الزبدة:</span>
                          <p className="text-xs md:text-sm text-on-surface-variant italic">"{item.gist}"</p>
                        </div>
                      </div>

                      <button
                        onClick={() => {
                          setCurrentAnalysis(item);
                          setActivePage('result');
                        }}
                        className="w-full bg-surface-container hover:bg-surface-container-high text-primary font-bold py-2.5 rounded-xl text-xs transition-colors mt-4"
                      >
                        عرض التقرير الكامل
                      </button>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-12">
                  <p className="text-on-surface-variant mb-4">قم بإجراء تحليلين على الأقل للبدء في مقارنتهما جنباً إلى جنب.</p>
                  <button onClick={() => setActivePage('home')} className="bg-primary text-on-primary px-6 py-2 rounded-full text-xs font-bold">
                    إجراء تحليل
                  </button>
                </div>
              )}
            </main>
          </div>
        )}

        {/* Profile Page */}
        {activePage === 'profile' && (
          <div className="min-h-screen bg-background text-on-background pb-28 md:pb-16 font-body-md">
            <main className="max-w-6xl mx-auto px-4 md:px-8 py-6 md:py-10 grid grid-cols-1 md:grid-cols-12 gap-6">
              <div className="md:col-span-4 flex flex-col gap-6">
                <div className="bg-surface-container-lowest rounded-2xl shadow-sm border border-outline-variant/30 p-6 flex flex-col items-center text-center">
                  <div className="w-24 h-24 rounded-full overflow-hidden border-4 border-surface-container-low mb-4 relative shadow-sm">
                    <img 
                      src={userProfileData?.photoURL || user?.photoURL || 'https://lh3.googleusercontent.com/aida-public/AB6AXuDhwfv0_8A02hQI8GDN0AvEvIMpK6nQ26A_ybujy8rwOtL4ebPTnEmRCpx_3Hukf_YDmZV9fOMEseLS0AtLvvJeVxfWUnJQGvIdxqKWa5FI_X5Sf5fiusej-cciBllpHQwYnKFxQ4uX6uw9-W1_6iJh94Vc75SNiPnp16uEgk5wwbDdQ6ppLZE4uKQ2I2I_mv5PjDO7IHP0NOf0I1W3e1nC90ep0x-OoXZbyVAOI7PTsShWMoQEvIIdZw'} 
                      alt="Profile"
                      className="w-full h-full object-cover"
                    />
                  </div>
                  
                  {/* Real-time Name */}
                  <h2 className="font-title-lg text-lg font-bold text-on-surface mb-1">
                    {userProfileData?.fullName || userProfileData?.displayName || user?.fullName || user?.displayName || 'مستخدم زبدة'}
                  </h2>
                  
                  {/* Real-time Email */}
                  <p className="text-xs text-on-surface-variant mb-4 font-mono select-all">
                    {userProfileData?.email || user?.email || 'user@example.com'}
                  </p>
                  
                  <div className="inline-flex items-center gap-1 bg-secondary/10 text-secondary border border-secondary/20 px-3.5 py-1 rounded-full text-xs font-bold mb-6">
                    <span className="material-symbols-outlined text-[15px]" style={{ fontVariationSettings: "'FILL' 1" }}>verified</span>
                    <span>حساب مفعل • {userProfileData?.plan || 'عضو مسجل'}</span>
                  </div>

                  <button
                    onClick={async () => {
                      await authService.logout();
                      setUser(null);
                      setUserProfileData(null);
                      setActivePage('home');
                    }}
                    className="w-full flex items-center justify-center gap-1.5 text-error bg-error-container/25 hover:bg-error-container/40 font-bold py-2.5 rounded-xl text-xs transition-colors border border-error-container"
                  >
                    <span className="material-symbols-outlined text-[18px]">logout</span>
                    <span>تسجيل الخروج</span>
                  </button>
                </div>

                {/* Firestore Real-Time Dynamic Stats */}
                <div className="bg-surface-container-lowest rounded-2xl shadow-sm border border-outline-variant/30 p-5 space-y-4">
                  <h3 className="font-title-lg text-sm font-bold text-on-surface flex items-center gap-1.5">
                    <span className="material-symbols-outlined text-primary text-[20px]">equalizer</span>
                    <span>إحصائياتك من Firestore (Real-time)</span>
                  </h3>

                  <div className="grid grid-cols-2 gap-3 text-center">
                    <div className="bg-surface-container-low p-4 rounded-xl border border-outline-variant/20">
                      <span className="text-3xl font-bold text-primary block leading-none mb-1">
                        {userSummariesCount}
                      </span>
                      <span className="text-[11px] text-on-surface-variant font-semibold">
                        ملخصاتك الفعلية
                      </span>
                    </div>
                    <div className="bg-surface-container-low p-4 rounded-xl border border-outline-variant/20">
                      <span className="text-3xl font-bold text-secondary block leading-none mb-1">
                        98.4%
                      </span>
                      <span className="text-[11px] text-on-surface-variant font-semibold">
                        دقة الذكاء الاصطناعي
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <div className="md:col-span-8 space-y-6">
                <div className="bg-surface-container-lowest rounded-2xl shadow-sm border border-outline-variant/30 p-6 md:p-8 space-y-6">
                  <h2 className="font-headline-md text-xl font-bold text-on-surface flex items-center gap-2 border-b border-outline-variant/20 pb-4">
                    <span className="material-symbols-outlined text-primary">settings</span>
                    <span>معلومات الحساب المسجلة بقاعدة بيانات Firebase</span>
                  </h2>

                  <div className="bg-surface-container-low p-5 rounded-2xl border border-outline-variant/20 flex items-center justify-between gap-4">
                    <div className="flex items-center gap-3.5">
                      <div className="text-2xl">🔥</div>
                      <div>
                        <h3 className="font-bold text-sm text-on-surface">مشروع Firebase (zubdah-73fa7)</h3>
                        <p className="text-xs text-on-surface-variant">المصادقة ومجموعة users ومجموعة analyses نشطة ومتزامنة.</p>
                      </div>
                    </div>
                    <span className="bg-secondary/15 text-secondary text-xs font-bold px-3 py-1 rounded-full border border-secondary/20">
                      متصل ونشط
                    </span>
                  </div>

                  <div className="p-4 bg-surface-container-low rounded-xl text-xs space-y-2.5 border border-outline-variant/20">
                    <div className="flex justify-between items-center">
                      <span className="text-on-surface-variant">معرف المستخدم (UID):</span>
                      <span className="font-mono text-outline select-all text-[11px]">{userProfileData?.uid || user?.uid || 'N/A'}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-on-surface-variant">الاسم الكامل (users.fullName):</span>
                      <span className="font-bold text-on-surface">{userProfileData?.fullName || user?.fullName || 'غير محدد'}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-on-surface-variant">البريد الإلكتروني (users.email):</span>
                      <span className="font-semibold text-primary">{userProfileData?.email || user?.email || 'غير محدد'}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-on-surface-variant">عدد الملخصات المحسوبة من Firestore:</span>
                      <span className="font-bold text-secondary bg-secondary/10 px-2 py-0.5 rounded-md">{userSummariesCount} ملخص</span>
                    </div>
                  </div>
                </div>
              </div>
            </main>
          </div>
        )}

      </div>

      {/* Bottom Nav on Mobile */}
      {activePage !== 'splash' && activePage !== 'analyzing' && (
        <BottomNav activePage={activePage} setActivePage={setActivePage} />
      )}

      {/* Auth Modal: Sign Up / Login / Forgot Password */}
      {showAuthModal && (
        <AuthModal
          initialMode={authModalMode}
          onAuthSuccess={handleAuthSuccess}
          onClose={() => setShowAuthModal(false)}
        />
      )}

    </div>
  );
}

// Full Interactive Auth Modal (Sign Up, Login, Forgot Password)
function AuthModal({ initialMode = 'register', onAuthSuccess, onClose }) {
  const [mode, setMode] = useState(initialMode);
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [errorMsg, setErrorMsg] = useState('');
  const [successMsg, setSuccessMsg] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setErrorMsg('');
    setSuccessMsg('');

    if (mode === 'register') {
      if (!fullName.trim()) {
        setErrorMsg('يرجى كتابة الاسم الكامل.');
        return;
      }
      if (password.length < 6) {
        setErrorMsg('كلمة المرور يجب أن تتكون من 6 خانات على الأقل.');
        return;
      }
      if (password !== confirmPassword) {
        setErrorMsg('كلمة المرور وتأكيد كلمة المرور غير متطابقين.');
        return;
      }
    }

    setLoading(true);

    try {
      if (mode === 'forgot') {
        const res = await authService.resetPassword(email.trim());
        setSuccessMsg(res.message);
        setLoading(false);
        return;
      }

      if (mode === 'register') {
        const res = await authService.register(fullName.trim(), email.trim(), password);
        if (res.success && res.user) {
          onAuthSuccess(res.user);
        }
      } else {
        const res = await authService.login(email.trim(), password);
        if (res.success && res.user) {
          onAuthSuccess(res.user);
        }
      }
    } catch (err) {
      setErrorMsg(err.message || 'حدث خطأ أثناء تنفيذ العملية.');
    } finally {
      setLoading(false);
    }
  };

  const handleGoogleAuth = async () => {
    setErrorMsg('');
    setLoading(true);
    try {
      const res = await authService.loginWithGoogle();
      if (res.success && res.user) {
        onAuthSuccess(res.user);
      }
    } catch (err) {
      setErrorMsg(err.message || 'تعذر تسجيل الدخول عبر Google.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 overflow-y-auto font-body-md select-none">
      <div className="bg-surface rounded-3xl max-w-4xl w-full shadow-2xl border border-outline-variant/40 overflow-hidden flex flex-col md:flex-row relative animate-scale-in my-8">
        
        {/* Close Button */}
        {onClose && (
          <button
            onClick={onClose}
            className="absolute top-4 left-4 z-20 w-9 h-9 rounded-full bg-surface-container-high/80 text-on-surface hover:bg-surface-container-highest flex items-center justify-center transition-colors shadow-xs"
            title="إغلاق"
          >
            <span className="material-symbols-outlined text-[20px]">close</span>
          </button>
        )}

        {/* Form Container */}
        <div className="w-full md:w-1/2 p-6 md:p-10 flex flex-col justify-center">
          
          <div className="text-center mb-6">
            <div className="inline-flex items-center gap-2 mb-2">
              <div className="w-10 h-10 rounded-xl bg-primary text-on-primary flex items-center justify-center shadow-md shadow-primary/20">
                <span className="material-symbols-outlined text-[22px]" style={{ fontVariationSettings: "'FILL' 1" }}>
                  auto_awesome
                </span>
              </div>
              <span className="font-headline-md text-2xl font-bold text-primary">زبدة</span>
            </div>

            <h1 className="font-title-lg text-xl md:text-2xl font-bold text-on-surface">
              {mode === 'login' && 'تسجيل الدخول'}
              {mode === 'register' && 'إنشاء حساب جديد'}
              {mode === 'forgot' && 'استعادة كلمة المرور'}
            </h1>
            <p className="text-xs text-on-surface-variant mt-1">
              {mode === 'login' && 'مرحباً بك مجدداً! أدخل بياناتك للوصول إلى تحليلاتك'}
              {mode === 'register' && 'أنشئ حسابك واحفظ ملخصاتك الذكية في سحابة Firebase'}
              {mode === 'forgot' && 'أدخل بريدك الإلكتروني لإرسال رابط الاستعادة'}
            </p>
          </div>

          {/* Feedback Messages */}
          {errorMsg && (
            <div className="bg-error-container text-on-error-container p-3 rounded-xl text-xs font-semibold mb-4 border border-error/20 flex items-center gap-2 animate-fade-in">
              <span className="material-symbols-outlined text-[18px]">error</span>
              <span>{errorMsg}</span>
            </div>
          )}

          {successMsg && (
            <div className="bg-secondary-container text-on-secondary-container p-3 rounded-xl text-xs font-semibold mb-4 border border-secondary/20 flex items-center gap-2 animate-fade-in">
              <span className="material-symbols-outlined text-[18px]">check_circle</span>
              <span>{successMsg}</span>
            </div>
          )}

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-3.5 text-xs">
            
            {mode === 'register' && (
              <div>
                <label className="block font-semibold mb-1 text-on-surface">الاسم الكامل</label>
                <div className="relative">
                  <span className="material-symbols-outlined absolute right-3.5 top-1/2 -translate-y-1/2 text-outline text-[18px]">
                    person
                  </span>
                  <input
                    type="text"
                    required
                    value={fullName}
                    onChange={(e) => setFullName(e.target.value)}
                    placeholder="مثال: أحمد محمد"
                    className="w-full bg-surface-container-low border border-outline-variant/50 rounded-xl pr-10 pl-3 py-2.5 text-on-surface focus:outline-none focus:ring-2 focus:ring-primary font-medium"
                  />
                </div>
              </div>
            )}

            <div>
              <label className="block font-semibold mb-1 text-on-surface">البريد الإلكتروني</label>
              <div className="relative">
                <span className="material-symbols-outlined absolute right-3.5 top-1/2 -translate-y-1/2 text-outline text-[18px]">
                  mail
                </span>
                <input
                  type="email"
                  required
                  dir="ltr"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="name@example.com"
                  className="w-full bg-surface-container-low border border-outline-variant/50 rounded-xl pr-10 pl-3 py-2.5 text-on-surface focus:outline-none focus:ring-2 focus:ring-primary font-medium"
                />
              </div>
            </div>

            {mode !== 'forgot' && (
              <div>
                <div className="flex items-center justify-between mb-1">
                  <label className="font-semibold text-on-surface">
                    كلمة المرور {mode === 'register' && '(6 خانات على الأقل)'}
                  </label>
                  {mode === 'login' && (
                    <button
                      type="button"
                      onClick={() => setMode('forgot')}
                      className="text-[11px] text-primary hover:underline font-semibold"
                    >
                      نسيت كلمة المرور؟
                    </button>
                  )}
                </div>
                <div className="relative">
                  <span className="material-symbols-outlined absolute right-3.5 top-1/2 -translate-y-1/2 text-outline text-[18px]">
                    lock
                  </span>
                  <input
                    type="password"
                    required
                    dir="ltr"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="••••••••"
                    className="w-full bg-surface-container-low border border-outline-variant/50 rounded-xl pr-10 pl-3 py-2.5 text-on-surface focus:outline-none focus:ring-2 focus:ring-primary font-medium"
                  />
                </div>
              </div>
            )}

            {mode === 'register' && (
              <div>
                <label className="block font-semibold mb-1 text-on-surface">تأكيد كلمة المرور</label>
                <div className="relative">
                  <span className="material-symbols-outlined absolute right-3.5 top-1/2 -translate-y-1/2 text-outline text-[18px]">
                    lock_reset
                  </span>
                  <input
                    type="password"
                    required
                    dir="ltr"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    placeholder="••••••••"
                    className="w-full bg-surface-container-low border border-outline-variant/50 rounded-xl pr-10 pl-3 py-2.5 text-on-surface focus:outline-none focus:ring-2 focus:ring-primary font-medium"
                  />
                </div>
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              className="w-full bg-primary hover:bg-surface-tint active:scale-98 text-on-primary font-bold py-3 px-4 rounded-xl shadow-md hover:shadow-lg transition-all flex items-center justify-center gap-2 mt-4 text-xs md:text-sm disabled:opacity-50"
            >
              {loading ? (
                <span className="animate-spin material-symbols-outlined text-[18px]">progress_activity</span>
              ) : (
                <>
                  <span>
                    {mode === 'login' && 'تسجيل الدخول'}
                    {mode === 'register' && 'إنشاء حساب'}
                    {mode === 'forgot' && 'إرسال الرابط'}
                  </span>
                  <span className="material-symbols-outlined text-[18px]">arrow_back</span>
                </>
              )}
            </button>

          </form>

          {/* Social Auth */}
          {mode !== 'forgot' && (
            <>
              <div className="relative flex items-center my-4">
                <div className="flex-grow border-t border-outline-variant/40"></div>
                <span className="flex-shrink-0 mx-3 text-[11px] text-outline font-semibold">أو</span>
                <div className="flex-grow border-t border-outline-variant/40"></div>
              </div>

              <button
                type="button"
                onClick={handleGoogleAuth}
                disabled={loading}
                className="w-full flex items-center justify-center gap-2.5 bg-surface-container-lowest border border-outline-variant/50 text-on-surface font-semibold py-2.5 px-4 rounded-xl hover:bg-surface-container-low transition-all text-xs mb-2.5 shadow-2xs"
              >
                <svg className="w-4 h-4" viewBox="0 0 24 24">
                  <path 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" fill="#4285F4"/>
                  <path 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" fill="#34A853"/>
                  <path 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" fill="#FBBC05"/>
                  <path 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" fill="#EA4335"/>
                </svg>
                <span>{mode === 'register' ? 'التسجيل عبر Google' : 'الدخول عبر Google'}</span>
              </button>
            </>
          )}

          {/* Mode Switchers */}
          <div className="text-center mt-5 text-xs text-on-surface-variant">
            {mode === 'login' && (
              <p>
                ليس لديك حساب؟{' '}
                <button
                  type="button"
                  onClick={() => {
                    setErrorMsg('');
                    setMode('register');
                  }}
                  className="text-primary font-bold hover:underline"
                >
                  أنشئ حساب جديد
                </button>
              </p>
            )}

            {mode === 'register' && (
              <p>
                عندك حساب؟{' '}
                <button
                  type="button"
                  onClick={() => {
                    setErrorMsg('');
                    setMode('login');
                  }}
                  className="text-primary font-bold hover:underline"
                >
                  سجّل دخول
                </button>
              </p>
            )}

            {mode === 'forgot' && (
              <p>
                <button
                  type="button"
                  onClick={() => {
                    setErrorMsg('');
                    setMode('login');
                  }}
                  className="text-primary font-bold hover:underline inline-flex items-center gap-1"
                >
                  <span className="material-symbols-outlined text-[16px]">arrow_forward</span>
                  العودة لتسجيل الدخول
                </button>
              </p>
            )}
          </div>

        </div>

        {/* Brand Showcase Panel */}
        <div className="hidden md:flex md:w-1/2 relative bg-surface-container-high overflow-hidden flex-col justify-end p-8 bg-gradient-to-tr from-primary to-primary-container text-on-primary">
          <div className="absolute inset-0 opacity-15 bg-[radial-gradient(#fff_1px,transparent_1px)] [background-size:16px_16px]"></div>
          
          <div className="relative z-10 bg-white/10 backdrop-blur-md p-6 rounded-2xl border border-white/20 shadow-lg">
            <div className="flex items-center gap-2 mb-2">
              <span className="material-symbols-outlined text-white text-[24px]">verified_user</span>
              <span className="font-bold text-sm text-white">حساب زبدة الذكي</span>
            </div>
            <p className="text-xs text-white/90 leading-relaxed font-medium">
              احفظ تحليلاتك وشارك تقاريرك وقارن بين المنتجات والمطاعم بكل سهولة مع قاعدة بياناتك السحابية الخاصة.
            </p>
          </div>
        </div>

      </div>
    </div>
  );
}

const rootElement = document.getElementById('root');
if (rootElement) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(<App />);
}
