/* Add custom CSS styles below */ 
import React, { useState, useEffect, useRef } from 'react';
import { MessageCircle, BarChart3, Shield, Zap, CheckCircle, ArrowLeft, Menu, X, CheckCheck, Send, Mic, Paperclip, MoreVertical, Phone, Video, Sparkles, FileText, PieChart } from 'lucide-react';

export default function LandingPage() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const chatContainerRef = useRef(null);
  
  // --- Gemini Integration State ---
  const [inputValue, setInputValue] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [messages, setMessages] = useState([
    {
      id: 1,
      type: 'bot',
      text: "مرحباً بك في المحاسب الذكي! 🤖📊\nأنا هنا لمساعدتك. جربني الآن!\n\nاكتب معاملة مالية، مثلاً:\n- 'بعت تصميم بـ 500 ريال'\n- 'قهوة 15 ريال'",
      time: new Date().toLocaleTimeString('ar-SA', { hour: '2-digit', minute: '2-digit' })
    }
  ]);

  // Auto-scroll to bottom
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [messages, isTyping]);

  // --- Gemini API Functions ---

  // 1. Core Transaction Handler
  const callGeminiAccountant = async (userText) => {
    const apiKey = ""; // سيتم تزويده تلقائياً عند التشغيل
    const systemPrompt = `
      You are 'المحاسب الذكي' (Smart Accountant), a friendly WhatsApp bot for tracking finances in Saudi Arabia.
      
      Your Role:
      1. Analyze the user's input (Standard Arabic or Saudi Dialect) to detect if it's an INCOME or EXPENSE.
      2. Extract the amount.
      3. Reply in Arabic, very concise, friendly, using emojis.
      
      Response Styles:
      - Income: "✅ تم تسجيل إيراد: [Item] مبلغ [Amount]. رصيدك زاد! 💰"
      - Expense: "📉 تم تسجيل مصروف: [Item] مبلغ [Amount]. 💸"
      - General: Welcome them politely.
      
      Dialect Understanding:
      - "قطيت", "حولت", "سددت", "شريت" -> Expense usually.
      - "جاني", "استلمت", "نزل لي" -> Income usually.
    `;

    try {
      const response = await fetch(
        `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            contents: [{ parts: [{ text: userText }] }],
            systemInstruction: { parts: [{ text: systemPrompt }] },
          }),
        }
      );

      const data = await response.json();
      return data.candidates?.[0]?.content?.parts?.[0]?.text || "عذراً، حدث خطأ في الاتصال. 🔌";
    } catch (error) {
      console.error("Gemini Error:", error);
      return "لا يمكنني الاتصال بالخادم حالياً.";
    }
  };

  // 2. Financial Analysis Feature
  const generateAnalysis = async () => {
    setIsTyping(true);
    const apiKey = "";
    
    // Convert messages to a simple string log
    const history = messages.map(m => `${m.type === 'user' ? 'المستخدم' : 'البوت'}: ${m.text}`).join('\n');
    
    const prompt = `
      Based on the following chat history, provide a very short, bulleted "Financial Health" summary in Arabic.
      Focus on what the user spent money on. Give a friendly advice.
      
      Chat History:
      ${history}
    `;

    try {
      const response = await fetch(
        `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            contents: [{ parts: [{ text: prompt }] }],
          }),
        }
      );

      const data = await response.json();
      const analysis = data.candidates?.[0]?.content?.parts?.[0]?.text || "لا توجد بيانات كافية للتحليل.";
      
      setIsTyping(false);
      setMessages(prev => [...prev, {
        id: Date.now(),
        type: 'bot',
        text: `📊 *التحليل المالي الذكي:*\n\n${analysis}`,
        time: new Date().toLocaleTimeString('ar-SA', { hour: '2-digit', minute: '2-digit' })
      }]);

    } catch (error) {
      setIsTyping(false);
    }
  };

  const handleSend = async (textToSend = inputValue) => {
    if (!textToSend.trim()) return;

    // 1. Add User Message
    const userMsg = {
      id: Date.now(),
      type: 'user',
      text: textToSend,
      time: new Date().toLocaleTimeString('ar-SA', { hour: '2-digit', minute: '2-digit' })
    };
    setMessages(prev => [...prev, userMsg]);
    setInputValue('');
    setIsTyping(true);

    // 2. Call Gemini
    const replyText = await callGeminiAccountant(textToSend);

    // 3. Add Bot Message
    setIsTyping(false);
    setMessages(prev => [...prev, {
      id: Date.now() + 1,
      type: 'bot',
      text: replyText,
      time: new Date().toLocaleTimeString('ar-SA', { hour: '2-digit', minute: '2-digit' })
    }]);
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') handleSend();
  };

  // Feature: Simulate Voice Note (Dialect)
  const handleSimulateVoice = () => {
    // This simulates a "Voice to Text" result with slang
    const dialectText = "يا غالي اليوم مريت الورشة غيرت زيت بـ ٩٠ ريال وعبيت بنزين فل بـ ٧٠";
    handleSend(dialectText);
  };

  return (
    <div className="min-h-screen bg-white font-sans text-gray-800" dir="rtl">
      
      {/* Navbar */}
      <nav className="fixed w-full bg-white/90 backdrop-blur-md z-50 border-b border-gray-100">
        <div className="container mx-auto px-6 py-4 flex justify-between items-center">
          <div className="flex items-center gap-2">
            <div className="w-10 h-10 bg-emerald-600 rounded-lg flex items-center justify-center text-white font-bold text-xl">
              م
            </div>
            <span className="text-xl font-bold text-gray-800">المحاسب الذكي</span>
          </div>
          
          <div className="hidden md:flex items-center gap-8">
            <a href="#features" className="text-gray-600 hover:text-emerald-600 transition">المميزات</a>
            <a href="#demo" className="text-gray-600 hover:text-emerald-600 transition">كيف يعمل؟</a>
            <a href="#pricing" className="text-gray-600 hover:text-emerald-600 transition">الأسعار</a>
            <button className="bg-emerald-600 text-white px-5 py-2 rounded-full font-medium hover:bg-emerald-700 transition flex items-center gap-2">
              <MessageCircle className="w-4 h-4" />
              جربه مجاناً
            </button>
          </div>

          <button onClick={() => setIsMenuOpen(!isMenuOpen)} className="md:hidden text-gray-600">
            {isMenuOpen ? <X /> : <Menu />}
          </button>
        </div>
        
        {/* Mobile Menu */}
        {isMenuOpen && (
          <div className="md:hidden bg-white border-t border-gray-100 px-6 py-4 flex flex-col gap-4">
            <a href="#features" className="text-gray-600">المميزات</a>
            <a href="#demo" className="text-gray-600">كيف يعمل؟</a>
            <a href="#pricing" className="text-gray-600">الأسعار</a>
            <button className="bg-emerald-600 text-white px-5 py-2 rounded-lg text-center">جربه مجاناً</button>
          </div>
        )}
      </nav>

      {/* Hero Section */}
      <section className="pt-32 pb-20 bg-gradient-to-b from-emerald-50 to-white overflow-hidden">
        <div className="container mx-auto px-6 flex flex-col md:flex-row items-center gap-12">
          
          {/* Text Content */}
          <div className="flex-1 text-center md:text-right order-2 md:order-1">
            <h1 className="text-4xl md:text-6xl font-bold leading-tight mb-6 text-gray-900">
              محاسبك الشخصي.. <br />
              <span className="text-emerald-600">يفهم كلامك!</span>
            </h1>
            <p className="text-lg text-gray-600 mb-8 leading-relaxed max-w-lg mx-auto md:mx-0">
              محاسب في وتسابك! سجل مصاريفك وإيراداتك بمجرد محادثة، واحصل على تقاريرك فوراً دون الحاجة لتطبيقات معقدة.
            </p>
            
            <div className="flex flex-col sm:flex-row gap-4 justify-center md:justify-start">
              <button className="bg-emerald-600 text-white px-8 py-4 rounded-xl font-bold text-lg hover:bg-emerald-700 transition flex items-center justify-center gap-2 shadow-lg shadow-emerald-200">
                <MessageCircle className="w-6 h-6" />
                ابدأ المحادثة الآن
              </button>
              <button className="bg-white text-gray-700 border border-gray-200 px-8 py-4 rounded-xl font-bold text-lg hover:bg-gray-50 transition flex items-center justify-center gap-2">
                شاهد الفيديو
              </button>
            </div>
          </div>

          {/* Phone Mockup / Live Demo */}
          <div className="flex-1 relative flex justify-center order-1 md:order-2 scale-90 md:scale-100">
            {/* Background blobs */}
            <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] bg-emerald-200/50 rounded-full blur-3xl -z-10"></div>
            
            {/* Phone Frame */}
            <div className="relative w-[340px] h-[700px] bg-gray-900 rounded-[3rem] border-8 border-gray-900 shadow-2xl overflow-hidden ring-1 ring-gray-900/5 flex flex-col">
              {/* Notch */}
              <div className="absolute top-0 left-1/2 -translate-x-1/2 w-32 h-6 bg-gray-900 rounded-b-xl z-20"></div>
              
              {/* Screen Content */}
              <div className="w-full h-full bg-[#efe7dd] flex flex-col font-sans relative">
                
                {/* Whatsapp Header */}
                <div className="bg-[#008069] p-3 pt-10 flex items-center justify-between text-white shadow-md z-10 shrink-0">
                  <div className="flex items-center gap-2">
                    <ArrowLeft className="w-5 h-5 cursor-pointer" />
                    <div className="w-9 h-9 rounded-full bg-white flex items-center justify-center overflow-hidden border border-gray-300">
                      <span className="text-xl">🤖</span>
                    </div>
                    <div className="flex flex-col">
                      <span className="font-bold text-sm leading-tight">المحاسب الذكي</span>
                      <span className="text-[10px] text-gray-200">
                        {isTyping ? 'يكتب الآن...' : 'متصل الآن'}
                      </span>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <Video className="w-4 h-4" />
                    <Phone className="w-4 h-4" />
                    <MoreVertical className="w-4 h-4" />
                  </div>
                </div>

                {/* Messages Body */}
                <div 
                  ref={chatContainerRef}
                  className="flex-1 p-3 space-y-3 overflow-y-auto scrollbar-hide relative bg-cover bg-center transition-all scroll-smooth"
                  style={{ 
                    backgroundImage: "url('https://user-images.githubusercontent.com/15075759/28719144-86dc0f70-73b1-11e7-911d-60d70fcded21.png')",
                    backgroundSize: "400px"
                  }}
                >
                   {/* Encryption Notice */}
                   <div className="flex justify-center mb-4">
                     <div className="bg-[#ffeecd] text-[#5e5e5e] text-[10px] px-2 py-1 rounded-lg text-center shadow-sm max-w-[85%] leading-tight">
                       🔒 الرسائل والبيانات المالية مشفرة تماماً.
                     </div>
                   </div>

                   {/* Date Divider */}
                   <div className="flex justify-center mb-4">
                      <span className="bg-[#e1f3fb] text-[#5b6b72] text-[10px] px-2 py-1 rounded-lg shadow-sm">اليوم</span>
                   </div>

                   {/* Render Messages */}
                   {messages.map((msg) => (
                     <div 
                       key={msg.id}
                       className={`flex ${msg.type === 'user' ? 'justify-start' : 'justify-end'} animate-in fade-in slide-in-from-bottom-2 duration-300`}
                     >
                       <div 
                         className={`max-w-[85%] rounded-lg p-2 px-3 shadow-sm relative text-[13px] leading-relaxed break-words ${
                           msg.type === 'user' 
                             ? 'bg-[#d9fdd3] rounded-tr-none text-gray-900' 
                             : 'bg-white rounded-tl-none text-gray-900'
                         }`}
                       >
                         <p className="whitespace-pre-line">{msg.text}</p>
                         <div className="flex items-center justify-end gap-1 mt-1">
                           <span className="text-[10px] text-gray-500 min-w-[35px] text-left">{msg.time}</span>
                           {msg.type === 'user' && (
                             <CheckCheck className="w-3 h-3 text-[#53bdeb]" />
                           )}
                         </div>
                       </div>
                     </div>
                   ))}

                   {/* Typing Indicator */}
                   {isTyping && (
                      <div className="flex justify-end animate-pulse">
                        <div className="bg-white rounded-lg rounded-tl-none px-3 py-2 shadow-sm">
                          <div className="flex gap-1">
                            <div className="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce"></div>
                            <div className="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce delay-75"></div>
                            <div className="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce delay-150"></div>
                          </div>
                        </div>
                      </div>
                   )}
                </div>

                {/* Input Bar */}
                <div className="bg-[#f0f2f5] p-2 flex items-center gap-2 z-20 shrink-0">
                  <div className="flex-1 bg-white h-10 rounded-full px-2 flex items-center shadow-sm border border-gray-100 justify-between">
                     <input
                        type="text"
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        onKeyPress={handleKeyPress}
                        placeholder="اكتب معاملة مالية..."
                        className="w-full bg-transparent outline-none text-gray-700 text-sm px-2 placeholder-gray-400"
                        disabled={isTyping}
                     />
                     <div className="flex gap-2 text-gray-400 px-1">
                        <Paperclip className="w-4 h-4 rotate-45 cursor-pointer hover:text-gray-600" />
                     </div>
                  </div>
                  <button 
                    onClick={() => handleSend(inputValue)}
                    disabled={!inputValue || isTyping}
                    className={`w-10 h-10 rounded-full flex items-center justify-center text-white shadow-sm transition-all ${
                        inputValue ? 'bg-[#008069] hover:bg-[#006a57] active:scale-95' : 'bg-[#008069] opacity-80'
                    }`}
                  >
                     {inputValue ? <Send className="w-4 h-4 ml-1" /> : <Mic className="w-5 h-5" />}
                  </button>
                </div>

              </div>
            </div>
          </div>

        </div>
      </section>

      {/* Features Section */}
      <section id="features" className="py-20 bg-white">
        <div className="container mx-auto px-6">
          <div className="text-center mb-16">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">لماذا تختار المحاسب الذكي؟</h2>
            <p className="text-gray-600 max-w-2xl mx-auto">دمجنا سهولة واتساب مع قوة نماذج Gemini 2.5 للذكاء الاصطناعي.</p>
          </div>

          <div className="grid md:grid-cols-3 gap-8">
            <FeatureCard 
              icon={<Zap className="w-8 h-8 text-yellow-500" />}
              title="فهم اللهجات العامية"
              desc="جرب أن تكتب 'قطيت مع الشباب' أو 'حولت لراعي البقالة'، سيفهمك Gemini فوراً دون الحاجة للغة رسمية."
            />
            <FeatureCard 
              icon={<BarChart3 className="w-8 h-8 text-blue-500" />}
              title="تقارير PDF تلقائية"
              desc="اطلب 'تقرير الشهر' وسيقوم البوت بإرسال ملف PDF منظم يحتوي على كل الحركات المالية."
            />
            <FeatureCard 
              icon={<Shield className="w-8 h-8 text-emerald-500" />}
              title="أمان وخصوصية"
              desc="بياناتك مشفرة ومحفوظة بأمان. لا نشارك بياناتك المالية مع أي طرف ثالث."
            />
          </div>
        </div>
      </section>

      {/* Pricing */}
      <section id="pricing" className="py-20 bg-gray-50">
        <div className="container mx-auto px-6">
          <div className="text-center mb-16">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">باقات تناسب الجميع</h2>
            <p className="text-gray-600">اختر الخطة التي تناسب حجم أعمالك</p>
          </div>
          
          <div className="grid md:grid-cols-3 gap-8 max-w-6xl mx-auto">
            
            {/* Basic Plan - 19 SAR */}
            <div className="bg-white p-8 rounded-2xl shadow-sm border border-gray-100 hover:shadow-lg transition flex flex-col">
              <h3 className="text-xl font-bold text-gray-900 mb-2">الباقة الأساسية</h3>
              <div className="text-4xl font-bold text-gray-900 mb-6">19 <span className="text-lg text-gray-500 font-normal">ريال / شهر</span></div>
              <ul className="space-y-4 mb-8 flex-1">
                <ListItem text="عدد غير محدود من العمليات" active />
                <ListItem text="تسجيل عبر الرسائل النصية" active />
                <ListItem text="تسجيل عبر الرسائل الصوتية" active />
                <ListItem text="تقارير" active />
              </ul>
              <button className="w-full py-3 rounded-xl border-2 border-emerald-600 text-emerald-600 font-bold hover:bg-emerald-50 transition">
                اشترك الآن
              </button>
            </div>

            {/* Pro Plan - 39 SAR */}
            <div className="bg-white p-8 rounded-2xl shadow-xl border-2 border-emerald-500 relative transform md:-translate-y-4 flex flex-col">
              <div className="absolute top-0 right-1/2 translate-x-1/2 -translate-y-1/2 bg-emerald-500 text-white px-3 py-1 rounded-full text-sm font-bold">
                الأكثر طلباً
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-2">الباقة المتقدمة</h3>
              <div className="text-4xl font-bold text-gray-900 mb-6">39 <span className="text-lg text-gray-500 font-normal">ريال / شهر</span></div>
              <ul className="space-y-4 mb-8 flex-1">
                <ListItem text="كل مميزات الباقة الأساسية" active />
                <ListItem text="تحليل صور الفواتير (OCR)" active />
                <ListItem text="قراءة ملفات PDF" active />
              </ul>
              <button className="w-full py-3 rounded-xl bg-emerald-600 text-white font-bold hover:bg-emerald-700 transition shadow-lg shadow-emerald-200">
                اشترك الآن
              </button>
            </div>

            {/* Annual Plan */}
            <div className="bg-gray-900 text-white p-8 rounded-2xl shadow-lg border border-gray-800 hover:shadow-xl transition flex flex-col">
              <div className="flex justify-between items-start">
                 <h3 className="text-xl font-bold mb-2">الباقة السنوية</h3>
                 <span className="bg-yellow-500 text-black text-xs font-bold px-2 py-1 rounded">وفر 15%</span>
              </div>
              <div className="text-4xl font-bold mb-6">399 <span className="text-lg text-gray-400 font-normal">ريال / سنة</span></div>
              <ul className="space-y-4 mb-8 flex-1">
                <ListItem text="جميع مميزات الباقة المتقدمة" active darkMode />
                <ListItem text="شهر مجاناً" active darkMode />
              </ul>
              <button className="w-full py-3 rounded-xl bg-white text-gray-900 font-bold hover:bg-gray-100 transition">
                وفر واشترك سنوياً
              </button>
            </div>

          </div>
        </div>
      </section>

      {/* Footer */}
      <footer className="bg-gray-900 text-gray-400 py-12">
        <div className="container mx-auto px-6">
          <div className="grid md:grid-cols-4 gap-8 mb-8">
            <div className="col-span-2">
              <div className="flex items-center gap-2 mb-4">
                <div className="w-8 h-8 bg-emerald-600 rounded flex items-center justify-center text-white font-bold">م</div>
                <span className="text-xl font-bold text-white">المحاسب الذكي</span>
              </div>
              <p className="text-sm leading-relaxed max-w-sm">
                نساعد الأفراد والشركات الصغيرة على إدارة شؤونهم المالية بأسهل طريقة ممكنة عبر دمج الذكاء الاصطناعي مع تطبيقات المحادثة اليومية.
              </p>
            </div>
            <div>
              <h4 className="text-white font-bold mb-4">روابط سريعة</h4>
              <ul className="space-y-2 text-sm">
                <li><a href="#" className="hover:text-emerald-500">عن الخدمة</a></li>
                <li><a href="#" className="hover:text-emerald-500">سياسة الخصوصية</a></li>
                <li><a href="#" className="hover:text-emerald-500">الشروط والأحكام</a></li>
              </ul>
            </div>
            <div>
              <h4 className="text-white font-bold mb-4">تواصل معنا</h4>
              <ul className="space-y-2 text-sm">
                <li>support@smartaccountant.com</li>
                <li>واتساب: +966 50 000 0000</li>
              </ul>
            </div>
          </div>
          <div className="border-t border-gray-800 pt-8 text-center text-xs">
            © 2024 المحاسب الذكي. جميع الحقوق محفوظة.
          </div>
        </div>
      </footer>
    </div>
  );
}

// Helper Components
function FeatureCard({ icon, title, desc }) {
  return (
    <div className="p-6 rounded-2xl bg-gray-50 hover:bg-white hover:shadow-lg transition duration-300 border border-transparent hover:border-gray-100">
      <div className="mb-4 bg-white w-14 h-14 rounded-full flex items-center justify-center shadow-sm">
        {icon}
      </div>
      <h3 className="text-xl font-bold mb-3 text-gray-900">{title}</h3>
      <p className="text-gray-600 leading-relaxed">{desc}</p>
    </div>
  );
}

function ListItem({ text, active = false, darkMode = false }) {
  return (
    <li className={`flex items-center gap-3 text-sm ${darkMode ? 'text-gray-300' : 'text-gray-600'}`}>
      <CheckCircle className={`w-5 h-5 ${active ? (darkMode ? 'text-yellow-500' : 'text-emerald-500') : 'text-gray-300'}`} />
      {text}
    </li>
  );
}