
import React, { useState, useRef, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { GoogleGenAI, Type } from '@google/genai';
import { 
  Upload, 
  Search, 
  MessageSquare, 
  AlertCircle, 
  CheckCircle2, 
  Maximize2,
  Send,
  Loader2,
  Trash2,
  Info,
  Download,
  Lightbulb,
  X,
  ChevronRight,
  ChevronLeft,
  LayoutDashboard,
  FileText,
  Plus,
  Building2,
  Compass,
  Award,
  ShieldCheck,
  Shapes,
  Bot,
  User,
  TriangleAlert,
  Settings2,
  Check,
  FileDown,
  ExternalLink,
  Edit3,
  Printer,
  Home,
  Layers,
  Layout,
  ArrowDownToLine,
  Box,
  Zap,
  Star,
  Crown,
  CheckCircle,
  Coins,
  Wallet,
  TrendingUp,
  Sparkles,
  ShoppingBag,
  CreditCard,
  Lock,
  ArrowLeftRight,
  RefreshCcw,
  BarChart3,
  ArrowRight,
  FilePlus2,
  History,
  Type as TypeIcon,
  Gift,
  Wind,
  Scaling,
  Construction,
  Minus
} from 'lucide-react';

const ARCHITECT_SYSTEM_PROMPT = `أنت مهندس معماري استشاري برتبة "خبير أول" بخبرة تتجاوز 25 عاماً في مراجعة وتدقيق المخططات الهندسية. 
مهمتك إجراء تحليل نقدي معمق وشامل للمخططات المرفقة، وتقديم قيمة استشارية حقيقية تتجاوز التحليل السردي العام.

يجب أن تتبع المنهجية التالية بدقة في تقريرك:

1. التحليل البيئي والمناخي (Environmental Context):
حلل علاقة المخطط مع مسار الشمس وحركة الرياح (بناءً على سهم الشمال إن وجد). هل توزيع الفتحات يحقق كفاءة الطاقة؟

2. المطابقة التنظيمية والعمرانية (Zoning & Compliance):
هل الارتدادات والنسب البنائية تبدو منطقية ومريحة؟ انقد ضيق المساحات أو المبالغة في الارتدادات.

3. التدقيق الوظيفي والفراغي (Functional Audit):
كشف العوائق (أعمدة أو حوائط تعيق الحركة). تحليل التدفق (Circulation) والزونات (خدمي، خاص، عام). تحديد "المساحات الميتة" (Dead Spaces).

4. النقد المعماري الهندسي (Architectural Criticism):
نقد الأشكال الهندسية والتعقيدات غير المبررة التي تزيد التكلفة. الاتزان البصري وتوزيع الكتلة.

5. التقرير الختامي والتوصيات (The Expert’s Prescription):
تحديد قائمة بالنقاط "غير المقبولة معمارياً". تقديم 3 توصيات بديلة ملموسة وقابلة للتنفيذ فوراً لتحسين الكفاءة وتقليل التكلفة وزيادة جودة الحياة.

يجب أن تكون النصوص باللغة العربية الفصحى وبأسلوب مهني هندسي تقني ومباشر بعيداً عن اللغة الإنشائية العامة.`;

interface Floor {
  id: string;
  name: string;
  data: string;
}

interface AnalysisResult {
  environmentalAnalysis: string;
  zoningCompliance: string;
  functionalAudit: string;
  architecturalCriticism: string;
  unacceptablePoints: string;
  expertPrescription: string; // The 3 concrete recommendations
  overallRating: string;
}

interface CreditBundle {
  id: string;
  points: number;
  price: number;
  label: string;
  isPopular?: boolean;
}

const CREDIT_BUNDLES: CreditBundle[] = [
  { id: 'trial', points: 5, price: 1, label: 'باقة التجربة السريعة' },
  { id: 'pro', points: 25, price: 5, label: 'باقة المحترفين (وفر 20%)', isPopular: true },
  { id: 'enterprise', points: 100, price: 15, label: 'باقة المكاتب الاستشارية' }
];

const App = () => {
  const [floors, setFloors] = useState<Floor[]>([]);
  const [activeFloorIndex, setActiveFloorIndex] = useState(0);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [analysis, setAnalysis] = useState<AnalysisResult | null>(null);
  const [chatHistory, setChatHistory] = useState<{ role: 'user' | 'model'; text: string }[]>([]);
  const [userInput, setUserInput] = useState('');
  const [isSendingChat, setIsSendingChat] = useState(false);
  const [isChatOpen, setIsChatOpen] = useState(false);
  const [loadingStep, setLoadingStep] = useState('');
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);
  const [isExportModalOpen, setIsExportModalOpen] = useState(false);
  const [showWalletModal, setShowWalletModal] = useState(false);
  const [showNewProjectModal, setShowNewProjectModal] = useState(false);
  const [showWelcomeBonus, setShowWelcomeBonus] = useState(false);
  
  const [userCredits, setUserCredits] = useState<number>(() => {
    const saved = localStorage.getItem('architect_pro_credits');
    return saved !== null ? parseInt(saved) : 15;
  });

  const [isProcessingPayment, setIsProcessingPayment] = useState(false);
  const [selectedBundle, setSelectedBundle] = useState<CreditBundle | null>(null);
  const [showJustMarketCheckout, setShowJustMarketCheckout] = useState(false);

  const [projectTitle, setProjectTitle] = useState('تقرير تحليل معماري استشاري');
  const [customHeader, setCustomHeader] = useState('');
  const [customFooter, setCustomFooter] = useState('');

  const fileInputRef = useRef<HTMLInputElement>(null);
  const chatEndRef = useRef<HTMLDivElement>(null);

  const steps = [
    "تحليل المسار الشمسي وتوجيه الرياح...",
    "تدقيق الارتدادات والنسب التنظيمية...",
    "فحص كفاءة المسارات والفراغات الميتة...",
    "صياغة التوصيات الاستشارية النهائية..."
  ];

  useEffect(() => {
    localStorage.setItem('architect_pro_credits', userCredits.toString());
  }, [userCredits]);

  useEffect(() => {
    const hasBeenWelcomed = localStorage.getItem('architect_pro_welcomed');
    if (!hasBeenWelcomed) {
      setShowWelcomeBonus(true);
      localStorage.setItem('architect_pro_welcomed', 'true');
    }
  }, []);

  useEffect(() => {
    if (isChatOpen) {
      chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }
  }, [chatHistory, isChatOpen]);

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        const nameOptions = ["الدور الأرضي", "الدور الأول", "الملحق العلوي", "القبو"];
        const nextName = nameOptions[floors.length] || `مستوى ${floors.length + 1}`;
        
        const newFloor: Floor = {
          id: Math.random().toString(36).substr(2, 9),
          name: nextName,
          data: reader.result as string
        };
        setFloors([...floors, newFloor]);
        setActiveFloorIndex(floors.length);
        setAnalysis(null);
      };
      reader.readAsDataURL(file);
      e.target.value = ''; 
    }
  };

  const executeNewProject = () => {
    setFloors([]);
    setAnalysis(null);
    setChatHistory([]);
    setActiveFloorIndex(0);
    setIsChatOpen(false);
    setShowNewProjectModal(false);
  };

  const runAnalysis = async () => {
    if (floors.length === 0) return;
    if (userCredits < 5) {
      setShowWalletModal(true);
      return;
    }

    setIsAnalyzing(true);
    let stepIndex = 0;
    const interval = setInterval(() => {
      setLoadingStep(steps[stepIndex % steps.length]);
      stepIndex++;
    }, 1800);

    try {
      const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
      const parts = floors.map(floor => ({
        inlineData: { data: floor.data.split(',')[1], mimeType: 'image/jpeg' }
      }));
      
      const response = await ai.models.generateContent({
        model: 'gemini-3-pro-preview',
        contents: {
          parts: [
            ...parts,
            { text: `قم بإجراء تحليل هندسي تقني ونقدي ومباشر للمخطط المرفق وفق المنهجية المحددة. قدم التقرير بتنسيق JSON.` }
          ]
        },
        config: { 
          systemInstruction: ARCHITECT_SYSTEM_PROMPT,
          responseMimeType: "application/json",
          responseSchema: {
            type: Type.OBJECT,
            properties: {
              environmentalAnalysis: { type: Type.STRING },
              zoningCompliance: { type: Type.STRING },
              functionalAudit: { type: Type.STRING },
              architecturalCriticism: { type: Type.STRING },
              unacceptablePoints: { type: Type.STRING },
              expertPrescription: { type: Type.STRING },
              overallRating: { type: Type.STRING }
            },
            required: ["environmentalAnalysis", "zoningCompliance", "functionalAudit", "architecturalCriticism", "unacceptablePoints", "expertPrescription", "overallRating"]
          }
        }
      });

      if (response.text) {
        setAnalysis(JSON.parse(response.text));
        setUserCredits(prev => Math.max(0, prev - 5));
      }
    } catch (error) {
      console.error("Analysis failed", error);
      alert("حدث خطأ أثناء تحليل المخطط. يرجى التأكد من جودة الصورة.");
    } finally {
      clearInterval(interval);
      setIsAnalyzing(false);
    }
  };

  const handleSendMessage = async () => {
    if (!userInput.trim() || floors.length === 0 || isSendingChat) return;
    const currentMsg = userInput;
    setChatHistory(prev => [...prev, { role: 'user', text: currentMsg }]);
    setUserInput('');
    setIsSendingChat(true);

    try {
      const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
      const parts = floors.map(floor => ({
        inlineData: { data: floor.data.split(',')[1], mimeType: 'image/jpeg' }
      }));

      const response = await ai.models.generateContent({
        model: 'gemini-3-pro-preview',
        contents: {
          parts: [...parts, { text: currentMsg }]
        },
        config: { systemInstruction: ARCHITECT_SYSTEM_PROMPT }
      });
      setChatHistory(prev => [...prev, { role: 'model', text: response.text || '' }]);
    } catch (error) {
      console.error("Chat failed", error);
    } finally {
      setIsSendingChat(false);
    }
  };

  const handlePrint = () => {
    window.print();
  };

  const getFloorIcon = (name: string, active: boolean) => {
    const iconClass = `w-4 h-4 ${active ? 'text-blue-400' : 'text-slate-300'}`;
    if (name.includes("الأرضي")) return <Home className={iconClass} />;
    if (name.includes("الأول")) return <Layers className={iconClass} />;
    if (name.includes("الملحق")) return <Box className={iconClass} />;
    if (name.includes("القبو")) return <ArrowDownToLine className={iconClass} />;
    return <Compass className={iconClass} />;
  };

  return (
    <div className="h-screen flex bg-[#F0F2F5] text-slate-900 overflow-hidden font-sans selection:bg-blue-100" dir="rtl">
      
      {/* Sidebar */}
      <aside className={`bg-slate-950 text-white transition-all duration-500 flex flex-col items-center py-8 no-print shadow-2xl relative z-30 ${isSidebarOpen ? 'w-24' : 'w-0 overflow-hidden opacity-0'}`}>
        <div className="bg-gradient-to-tr from-[#0D47A1] to-blue-500 p-4 rounded-3xl mb-12 shadow-xl shadow-blue-900/40">
          <Shapes className="w-7 h-7" />
        </div>
        <nav className="flex flex-col gap-6 flex-1 w-full">
          <SidebarIcon icon={<LayoutDashboard />} active={!isChatOpen} label="الرئيسية" />
          <SidebarIcon icon={<Plus />} onClick={() => fileInputRef.current?.click()} label="إضافة مخطط" />
          <SidebarIcon 
            icon={<RefreshCcw />} 
            onClick={() => (floors.length > 0 || analysis) ? setShowNewProjectModal(true) : null} 
            label="تدقيق جديد" 
            disabled={floors.length === 0 && !analysis}
          />
          <SidebarIcon icon={<MessageSquare />} onClick={() => setIsChatOpen(!isChatOpen)} label="نقاش فني" active={isChatOpen} />
          <SidebarIcon icon={<Wallet />} onClick={() => setShowWalletModal(true)} label="محفظة Just Market" />
          <SidebarIcon 
            icon={<Download />} 
            onClick={() => analysis ? setIsExportModalOpen(true) : alert('يرجى إجراء التحليل الهندسي أولاً')} 
            label="تصدير النتائج" 
            disabled={!analysis} 
          />
        </nav>
      </aside>

      <main className="flex-1 relative flex flex-col overflow-hidden bg-[#F8FAFC] no-print">
        
        {/* Modern Header */}
        <header className="h-20 bg-white/70 backdrop-blur-xl border-b border-slate-200/60 px-10 flex items-center justify-between relative z-20">
          <div className="flex items-center gap-6">
            <button onClick={() => setIsSidebarOpen(!isSidebarOpen)} className="p-3 hover:bg-slate-100 rounded-2xl text-slate-400 transition-all">
              {isSidebarOpen ? <ChevronRight className="w-6 h-6" /> : <ChevronLeft className="w-6 h-6" />}
            </button>
            <div>
              <h1 className="text-2xl font-black text-slate-900 tracking-tight">المِعمار <span className="text-[#0D47A1]">برو</span></h1>
              <p className="text-[10px] font-bold text-[#0D47A1] tracking-widest uppercase flex items-center gap-2">
                <ShieldCheck className="w-3 h-3" />
                Just Market Credits System
              </p>
            </div>
          </div>
          
          <div className="flex items-center gap-6">
               <button 
                onClick={() => setShowWalletModal(true)}
                className="bg-[#0D47A1] px-6 py-2.5 rounded-full text-white flex items-center gap-4 hover:bg-blue-900 hover:shadow-xl hover:shadow-blue-500/20 transition-all group border-2 border-white/10"
               >
                <div className="flex flex-col items-end border-l border-white/20 pl-4">
                  <span className="text-[8px] font-black text-blue-200 uppercase tracking-widest">الرصيد الحالي</span>
                  <span className="text-sm font-black flex items-center gap-2">
                    {userCredits} <Coins className={`w-4 h-4 text-amber-400 ${userCredits > 0 ? 'animate-pulse' : ''}`} />
                  </span>
                </div>
                <div className="text-xs font-black uppercase tracking-tighter">شحن الرصيد</div>
              </button>

            <div className="flex -space-x-2 space-x-reverse items-center">
              {[1, 2, 3].map(i => (
                <div key={i} className="w-8 h-8 rounded-full border-2 border-white bg-slate-200 overflow-hidden shadow-sm">
                  <img src={`https://api.dicebear.com/7.x/avataaars/svg?seed=${i + 240}`} alt="Expert" />
                </div>
              ))}
            </div>
          </div>
        </header>

        <div className="flex-1 flex overflow-hidden p-8 gap-8">
          {/* Main Content Area - Plan Viewer */}
          <div className="flex-1 relative bg-white rounded-[40px] shadow-2xl shadow-slate-200/50 border border-slate-200/50 flex flex-col overflow-hidden">
            {floors.length > 0 && (
              <div className="flex bg-white/80 backdrop-blur-md p-3 gap-3 border-b border-slate-100/50 items-center overflow-x-auto no-scrollbar relative z-10">
                {floors.map((floor, idx) => (
                  <button 
                    key={floor.id}
                    onClick={() => setActiveFloorIndex(idx)}
                    className={`group flex items-center gap-3 px-6 py-3 rounded-[20px] text-xs font-black transition-all whitespace-nowrap ${activeFloorIndex === idx ? 'bg-slate-950 text-white shadow-xl' : 'text-slate-400 hover:bg-slate-50'}`}
                  >
                    {getFloorIcon(floor.name, activeFloorIndex === idx)}
                    {floor.name}
                  </button>
                ))}
                <button onClick={() => fileInputRef.current?.click()} className="flex items-center justify-center w-10 h-10 min-w-[40px] rounded-xl bg-slate-50 text-slate-400 hover:bg-[#0D47A1] hover:text-white transition-all border border-dashed border-slate-300 shadow-sm mr-2">
                  <Plus className="w-5 h-5" />
                </button>
              </div>
            )}

            <div className="flex-1 flex flex-col relative overflow-hidden">
                {!floors[activeFloorIndex] ? (
                  <div className="flex-1 flex flex-col items-center justify-center p-20 text-center cursor-pointer min-h-full" onClick={() => fileInputRef.current?.click()}>
                    <div className="w-32 h-32 bg-blue-50 rounded-[40px] flex items-center justify-center mb-8 shadow-2xl shadow-blue-100 transition-transform hover:scale-110">
                      <Upload className="w-12 h-12 text-[#0D47A1]" />
                    </div>
                    <h2 className="text-3xl font-black text-slate-900 mb-4">ارفع المخطط المعماري</h2>
                    <p className="text-slate-400 max-w-sm font-medium leading-relaxed">التحليل الهندسي يبدأ من هنا. ارفع مخططاتك التنفيذية الآن.</p>
                  </div>
                ) : (
                  <div className="relative flex-1 bg-slate-50/50 flex items-center justify-center p-12 overflow-hidden">
                    <img src={floors[activeFloorIndex].data} className="max-w-full max-h-[80vh] object-contain rounded-2xl shadow-2xl transition-all" alt="Blueprint" />
                    
                    {!analysis && !isAnalyzing && (
                    <button onClick={runAnalysis} className="absolute bottom-12 px-16 py-5 bg-[#0D47A1] text-white rounded-[24px] font-black text-sm shadow-2xl hover:bg-blue-900 transition-all flex items-center gap-4 group">
                        <Construction className="w-5 h-5 text-amber-400 group-hover:animate-bounce" />
                        بدء التدقيق الهندسي الشامل (5 نقاط)
                    </button>
                    )}

                    {isAnalyzing && (
                    <div className="absolute inset-0 bg-white/90 backdrop-blur-xl flex flex-col items-center justify-center z-20">
                        <Loader2 className="w-20 h-20 text-[#0D47A1] animate-spin mb-8" />
                        <p className="text-2xl font-black text-slate-900 animate-pulse">{loadingStep}</p>
                    </div>
                    )}
                  </div>
                )}
            </div>
            <input type="file" hidden ref={fileInputRef} onChange={handleImageUpload} accept="image/*" />
          </div>

          {/* Right Panel - Always Analysis */}
          <div className={`w-[520px] flex flex-col gap-6 transition-all duration-700 ${floors.length === 0 && 'opacity-30 blur-sm pointer-events-none'}`}>
            <div className="flex-1 bg-white rounded-[40px] border border-slate-200/50 shadow-2xl overflow-hidden flex flex-col relative">
                <div className="flex-1 overflow-y-auto p-8 space-y-8 custom-scrollbar">
                  {!analysis ? (
                    <div className="h-full flex flex-col items-center justify-center text-center p-12 opacity-30">
                      <Building2 className="w-16 h-16 text-slate-300 mb-6" />
                      <p className="font-bold text-slate-400">تقرير المراجعة الهندسية سيظهر هنا</p>
                    </div>
                  ) : (
                    <div className="space-y-10 pb-10">
                      <div className="flex items-center justify-between mb-4">
                        <h2 className="text-xl font-black text-slate-900">نتائج التدقيق</h2>
                        <button onClick={() => setShowNewProjectModal(true)} className="flex items-center gap-2 px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-xl text-xs font-black transition-all">
                          <FilePlus2 className="w-4 h-4" /> تدقيق جديد
                        </button>
                      </div>

                      <DetailedInsight title="التحليل البيئي" content={analysis.environmentalAnalysis} icon={<Wind />} subtitle="المسار الشمسي والرياح" />
                      <DetailedInsight title="المطابقة التنظيمية" content={analysis.zoningCompliance} icon={<Scaling />} subtitle="الارتدادات والنسب البنائية" />
                      <DetailedInsight title="التدقيق الوظيفي" content={analysis.functionalAudit} icon={<Maximize2 />} subtitle="التدفق والمساحات الميتة" />
                      <DetailedInsight title="النقد الهندسي" content={analysis.architecturalCriticism} icon={<Construction />} subtitle="الاتزان البصري والتكلفة" />

                      <div className="p-8 rounded-[35px] shadow-2xl bg-red-50 border-2 border-red-100 relative overflow-hidden">
                        <div className="flex items-center gap-4 mb-4">
                           <TriangleAlert className="w-7 h-7 text-red-600" />
                           <h3 className="text-xl font-black text-red-900">غير مقبول معمارياً</h3>
                        </div>
                        <p className="text-sm leading-[1.8] font-bold text-red-800 whitespace-pre-wrap">{analysis.unacceptablePoints}</p>
                      </div>

                      <div className="p-8 rounded-[35px] shadow-2xl bg-slate-950 text-white relative overflow-hidden">
                        <div className="relative z-10 pr-4 mt-2">
                          <div className="flex items-center gap-4 mb-6">
                            <Lightbulb className="w-7 h-7 text-amber-400" />
                            <h3 className="text-xl font-black">روشتة الخبير (3 توصيات بديلة)</h3>
                          </div>
                          <p className="text-sm leading-[1.8] font-medium whitespace-pre-wrap">{analysis.expertPrescription}</p>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
            </div>
          </div>
        </div>

        {/* Floating Chat System */}
        <div className="fixed bottom-8 right-8 z-[100] flex flex-col items-end gap-4 no-print" dir="rtl">
           {isChatOpen && (
             <div className="w-[450px] h-[600px] bg-white rounded-[40px] shadow-[0_32px_64px_-16px_rgba(0,0,0,0.2)] border border-slate-200 overflow-hidden flex flex-col animate-in slide-in-from-bottom-10 fade-in duration-300">
                {/* Chat Header */}
                <div className="bg-slate-950 p-6 text-white flex items-center justify-between">
                   <div className="flex items-center gap-4">
                      <div className="w-10 h-10 bg-[#0D47A1] rounded-xl flex items-center justify-center shadow-lg shadow-blue-900/40">
                         <Bot className="w-5 h-5 text-white" />
                      </div>
                      <div>
                         <h4 className="font-black text-sm">نقاش فني استشاري</h4>
                         <div className="flex items-center gap-2 mt-1">
                            <span className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></span>
                            <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">خبير متصل الآن</span>
                         </div>
                      </div>
                   </div>
                   <div className="flex items-center gap-2">
                      <button onClick={() => setIsChatOpen(false)} className="p-2 hover:bg-white/10 rounded-xl transition-all">
                        <Minus className="w-5 h-5 text-slate-400" />
                      </button>
                      <button onClick={() => { setChatHistory([]); setIsChatOpen(false); }} className="p-2 hover:bg-red-500/20 rounded-xl transition-all group">
                        <Trash2 className="w-5 h-5 text-slate-400 group-hover:text-red-400" />
                      </button>
                   </div>
                </div>

                {/* Chat Body */}
                <div className="flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-slate-50/30">
                  {floors.length === 0 ? (
                    <div className="h-full flex flex-col items-center justify-center text-center opacity-30 px-10">
                      <Upload className="w-12 h-12 text-slate-400 mb-4" />
                      <p className="text-sm font-black text-slate-500">يرجى رفع مخطط لبدء النقاش الفني مع الخبير</p>
                    </div>
                  ) : (
                    <>
                      {chatHistory.length === 0 && (
                        <div className="p-6 bg-[#0D47A1]/5 border border-[#0D47A1]/10 rounded-[30px] text-center mb-4">
                           <Info className="w-6 h-6 text-[#0D47A1] mx-auto mb-3" />
                           <p className="text-xs font-bold text-slate-600 leading-relaxed">
                             أهلاً بك مهندس. يمكنك سؤالي عن أي تفاصيل إنشائية، معالجات معمارية، أو نقد لزاوية محددة في مخططك.
                           </p>
                        </div>
                      )}
                      {chatHistory.map((msg, idx) => (
                          <div key={idx} className={`flex items-start gap-3 ${msg.role === 'user' ? 'flex-row-reverse' : 'flex-row'} animate-in slide-in-from-bottom-2`}>
                            <div className={`w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 shadow-sm ${msg.role === 'user' ? 'bg-slate-200 text-slate-600' : 'bg-[#0D47A1] text-white'}`}>
                              {msg.role === 'user' ? <User className="w-4 h-4" /> : <Bot className="w-4 h-4" />}
                            </div>
                            <div className={`max-w-[85%] p-4 rounded-[22px] text-sm font-medium ${msg.role === 'user' ? 'bg-slate-900 text-white rounded-tr-none' : 'bg-white border border-slate-100 text-slate-800 rounded-tl-none shadow-sm'}`}>
                              {msg.text}
                            </div>
                          </div>
                      ))}
                      {isSendingChat && (
                        <div className="flex items-start gap-3 animate-pulse">
                           <div className="w-8 h-8 rounded-lg bg-[#0D47A1] text-white flex items-center justify-center"><Bot className="w-4 h-4" /></div>
                           <div className="bg-white border border-slate-100 p-4 rounded-[22px] rounded-tl-none"><Loader2 className="w-4 h-4 animate-spin text-[#0D47A1]" /></div>
                        </div>
                      )}
                      <div ref={chatEndRef} />
                    </>
                  )}
                </div>

                {/* Chat Footer */}
                <div className="p-5 bg-white border-t border-slate-100">
                  <div className="relative flex items-center gap-3">
                    <input 
                      type="text" 
                      value={userInput} 
                      onChange={(e) => setUserInput(e.target.value)} 
                      onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()} 
                      disabled={floors.length === 0 || isSendingChat}
                      placeholder={floors.length === 0 ? "ارفع مخططاً أولاً..." : "اكتب استفسارك الهندسي هنا..."} 
                      className="flex-1 pr-5 pl-12 py-4 bg-slate-50 border border-slate-100 rounded-[20px] outline-none text-sm font-bold focus:bg-white focus:border-[#0D47A1]/30 transition-all shadow-sm disabled:opacity-50" 
                    />
                    <button 
                      onClick={handleSendMessage} 
                      disabled={floors.length === 0 || isSendingChat || !userInput.trim()}
                      className="absolute left-1.5 p-3.5 bg-[#0D47A1] text-white rounded-[16px] transition-all shadow-lg active:scale-95 disabled:opacity-50 disabled:bg-slate-300"
                    >
                      {isSendingChat ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                    </button>
                  </div>
                </div>
             </div>
           )}

           {/* Floating FAB */}
           <button 
             onClick={() => setIsChatOpen(!isChatOpen)}
             className={`w-16 h-16 rounded-full flex items-center justify-center shadow-2xl transition-all duration-500 group relative ${isChatOpen ? 'bg-slate-950 rotate-90' : 'bg-[#0D47A1] hover:bg-blue-900 hover:scale-110'}`}
           >
             {isChatOpen ? <X className="w-7 h-7 text-white" /> : <MessageSquare className="w-7 h-7 text-white" />}
             {!isChatOpen && chatHistory.length === 0 && (
               <span className="absolute -top-1 -left-1 w-5 h-5 bg-red-500 rounded-full border-4 border-[#F8FAFC] flex items-center justify-center text-[10px] text-white font-black animate-bounce">1</span>
             )}
             
             {/* Tooltip */}
             <span className="absolute right-full mr-6 px-4 py-2 bg-slate-900 text-white text-xs font-black rounded-xl opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none shadow-xl">
               نقاش فني مع الخبير
             </span>
           </button>
        </div>
      </main>

      {/* WELCOME BONUS MODAL */}
      {showWelcomeBonus && (
        <div className="fixed inset-0 bg-[#0D47A1]/40 backdrop-blur-3xl z-[300] flex items-center justify-center p-6 no-print">
           <div className="bg-white w-full max-md rounded-[50px] shadow-2xl overflow-hidden animate-in zoom-in duration-500 border-4 border-white">
              <div className="p-12 text-center">
                 <div className="w-24 h-24 bg-[#0D47A1] rounded-[35px] flex items-center justify-center mx-auto mb-8 shadow-2xl shadow-blue-200 relative">
                    <Gift className="w-10 h-10 text-white" />
                    <Sparkles className="absolute -top-2 -right-2 w-8 h-8 text-amber-400 animate-pulse" />
                 </div>
                 <h2 className="text-3xl font-black text-slate-900 mb-4 tracking-tighter">هدية ترحيبية!</h2>
                 <p className="text-slate-400 font-bold mb-8 leading-relaxed">
                   أهلاً بك في المعمار برو. لقد أضفنا <span className="text-[#0D47A1] text-xl font-black">15 نقطة مجانية</span> لحسابك لتبدأ رحلتك في تدقيق مخططاتك الهندسية فوراً.
                 </p>
                 <button 
                  onClick={() => setShowWelcomeBonus(false)}
                  className="w-full py-5 rounded-[28px] font-black text-white bg-slate-950 hover:bg-[#0D47A1] transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3"
                 >
                   شكراً، ابدأ الآن
                 </button>
              </div>
           </div>
        </div>
      )}

      {/* EXPORT SETTINGS MODAL */}
      {isExportModalOpen && (
        <div className="fixed inset-0 bg-slate-950/80 backdrop-blur-xl z-[210] flex items-center justify-center p-6 no-print">
          <div className="bg-white w-full max-w-2xl rounded-[50px] shadow-2xl overflow-hidden animate-in zoom-in duration-300 border border-slate-100">
             <div className="bg-[#0D47A1] p-10 text-white flex items-center justify-between">
                <div className="flex items-center gap-5">
                   <div className="w-12 h-12 bg-white/20 rounded-2xl flex items-center justify-center backdrop-blur-md">
                      <Download className="w-6 h-6 text-white" />
                   </div>
                   <div>
                      <h4 className="font-black text-xl tracking-tight">تصدير التقرير الهندسي</h4>
                      <p className="text-[10px] text-blue-200 uppercase font-black tracking-widest mt-1">إعدادات الطباعة والترويسة</p>
                   </div>
                </div>
                <button onClick={() => setIsExportModalOpen(false)} className="p-2 hover:bg-white/10 rounded-xl transition-all">
                  <X className="w-6 h-6 text-blue-200" />
                </button>
             </div>
             
             <div className="p-10 space-y-8">
                <div className="space-y-6">
                   <div className="space-y-2">
                      <label className="text-xs font-black text-slate-400 uppercase tracking-widest flex items-center gap-2">
                        <FileText className="w-3 h-3" /> عنوان المشروع
                      </label>
                      <input 
                        type="text" 
                        value={projectTitle}
                        onChange={(e) => setProjectTitle(e.target.value)}
                        placeholder="أدخل عنوان المشروع هنا..."
                        className="w-full px-6 py-4 bg-slate-50 border border-slate-100 rounded-2xl outline-none text-sm font-bold focus:bg-white transition-all"
                      />
                   </div>

                   <div className="space-y-2">
                      <label className="text-xs font-black text-slate-400 uppercase tracking-widest flex items-center gap-2">
                        <TypeIcon className="w-3 h-3" /> ترويسة مخصصة (Header)
                      </label>
                      <textarea 
                        rows={2}
                        value={customHeader}
                        onChange={(e) => setCustomHeader(e.target.value)}
                        placeholder="اسم المكتب الهندسي، بيانات الاستشاري..."
                        className="w-full px-6 py-4 bg-slate-50 border border-slate-100 rounded-2xl outline-none text-sm font-bold focus:bg-white transition-all resize-none"
                      />
                   </div>

                   <div className="space-y-2">
                      <label className="text-xs font-black text-slate-400 uppercase tracking-widest flex items-center gap-2">
                        <ArrowDownToLine className="w-3 h-3" /> تذييل الصفحة (Footer)
                      </label>
                      <textarea 
                        rows={2}
                        value={customFooter}
                        onChange={(e) => setCustomFooter(e.target.value)}
                        placeholder="ملاحظات ختامية، شروط وأحكام..."
                        className="w-full px-6 py-4 bg-slate-50 border border-slate-100 rounded-2xl outline-none text-sm font-bold focus:bg-white transition-all resize-none"
                      />
                   </div>
                </div>

                <div className="flex gap-4">
                   <button 
                     onClick={() => setIsExportModalOpen(false)}
                     className="flex-1 py-5 rounded-[24px] font-black text-sm bg-slate-100 text-slate-600 hover:bg-slate-200 transition-all"
                   >
                     إلغاء
                   </button>
                   <button 
                     onClick={handlePrint}
                     className="flex-[2] py-5 rounded-[24px] font-black text-sm bg-[#0D47A1] text-white shadow-xl shadow-blue-500/20 hover:bg-blue-900 transition-all flex items-center justify-center gap-3"
                   >
                     <Printer className="w-5 h-5" /> إنشاء ملف PDF وتصدير
                   </button>
                </div>
             </div>
          </div>
        </div>
      )}

      {/* PRINT-ONLY REPORT CONTAINER */}
      {analysis && (
        <div className="hidden print-container absolute inset-0 bg-white p-12 text-slate-900" dir="rtl">
           {/* Report Header */}
           <div className="border-b-4 border-[#0D47A1] pb-8 mb-10 flex justify-between items-end">
              <div>
                <h1 className="text-4xl font-black text-slate-900 mb-2">{projectTitle}</h1>
                <p className="text-sm font-bold text-slate-500">تقرير تدقيق هندسي معتمد - المعمار برو</p>
                {customHeader && <p className="text-lg font-black text-[#0D47A1] mt-4 whitespace-pre-wrap">{customHeader}</p>}
              </div>
              <div className="text-left font-black text-[#0D47A1] text-2xl">
                 Architect Pro <span className="text-slate-400">Expert</span>
              </div>
           </div>

           {/* Report Content */}
           <div className="space-y-12">
              <section className="space-y-4">
                 <h2 className="text-2xl font-black border-r-4 border-slate-900 pr-4">1. التحليل البيئي والمناخي</h2>
                 <p className="text-base leading-relaxed font-medium">{analysis.environmentalAnalysis}</p>
              </section>

              <section className="space-y-4">
                 <h2 className="text-2xl font-black border-r-4 border-slate-900 pr-4">2. المطابقة التنظيمية والعمرانية</h2>
                 <p className="text-base leading-relaxed font-medium">{analysis.zoningCompliance}</p>
              </section>

              <section className="space-y-4">
                 <h2 className="text-2xl font-black border-r-4 border-slate-900 pr-4">3. التدقيق الوظيفي والفراغي</h2>
                 <p className="text-base leading-relaxed font-medium">{analysis.functionalAudit}</p>
              </section>

              <section className="space-y-4">
                 <h2 className="text-2xl font-black border-r-4 border-slate-900 pr-4">4. النقد المعماري الهندسي</h2>
                 <p className="text-base leading-relaxed font-medium">{analysis.architecturalCriticism}</p>
              </section>

              <section className="p-8 bg-red-50 border-r-8 border-red-600 rounded-xl">
                 <h2 className="text-2xl font-black text-red-900 mb-4 flex items-center gap-3">
                    <TriangleAlert className="w-8 h-8" /> نقاط غير مقبولة معمارياً
                 </h2>
                 <p className="text-base font-bold text-red-800 whitespace-pre-wrap">{analysis.unacceptablePoints}</p>
              </section>

              <section className="p-10 bg-slate-950 text-white rounded-[40px]">
                 <h2 className="text-2xl font-black mb-6 flex items-center gap-4">
                    <Lightbulb className="w-8 h-8 text-amber-400" /> روشتة الخبير (التوصيات البديلة)
                 </h2>
                 <p className="text-base leading-loose whitespace-pre-wrap">{analysis.expertPrescription}</p>
              </section>

              <div className="flex justify-between items-center pt-10 border-t border-slate-100">
                 <div className="text-xl font-black">التقييم العام للمخطط: <span className="text-[#0D47A1]">{analysis.overallRating}</span></div>
                 <div className="text-xs font-bold text-slate-400 italic">صدر هذا التقرير بتاريخ: {new Date().toLocaleDateString('ar-SA')}</div>
              </div>
           </div>

           {/* Report Footer */}
           {customFooter && (
             <div className="mt-20 pt-10 border-t-2 border-slate-100 text-center">
                <p className="text-sm font-bold text-slate-500 whitespace-pre-wrap leading-relaxed">{customFooter}</p>
             </div>
           )}
        </div>
      )}

      {/* NEW PROJECT MODAL */}
      {showNewProjectModal && (
        <div className="fixed inset-0 bg-slate-950/80 backdrop-blur-xl z-[200] flex items-center justify-center p-6 no-print">
          <div className="bg-white w-full max-lg rounded-[60px] shadow-2xl overflow-hidden animate-in zoom-in duration-300 border border-slate-100">
            <div className="p-12 text-center">
               <div className="w-24 h-24 bg-red-50 rounded-[35px] flex items-center justify-center mx-auto mb-8 shadow-2xl shadow-red-100 animate-pulse">
                  <RefreshCcw className="w-10 h-10 text-red-500" />
               </div>
               <h2 className="text-3xl font-black text-slate-900 mb-4 tracking-tighter">بدء مشروع جديد؟</h2>
               <p className="text-slate-400 font-bold mb-10 leading-relaxed px-4">
                 سيقوم هذا الإجراء بمسح جميع المخططات الحالية، والتقارير الهندسية. هذا الإجراء <span className="text-red-500 underline">لا يمكن التراجع عنه</span>.
               </p>

               <div className="grid grid-cols-2 gap-6">
                 <button 
                   onClick={() => setShowNewProjectModal(false)}
                   className="py-5 rounded-[28px] font-black text-sm bg-slate-100 text-slate-600 hover:bg-slate-200 transition-all"
                 >
                   إلغاء الأمر
                 </button>
                 <button 
                   onClick={executeNewProject}
                   className="py-5 rounded-[28px] font-black text-sm bg-red-600 text-white shadow-xl shadow-red-500/20 hover:bg-red-700 transition-all flex items-center justify-center gap-3"
                 >
                   <Trash2 className="w-4 h-4" /> تأكيد المسح
                 </button>
               </div>
            </div>
          </div>
        </div>
      )}

      {/* WALLET MODAL */}
      {showWalletModal && (
        <div className="fixed inset-0 bg-[#020817]/95 backdrop-blur-2xl z-[120] flex items-center justify-center p-6 no-print">
          <div className="bg-white w-full max-w-4xl rounded-[60px] shadow-2xl overflow-hidden animate-in slide-in-from-bottom-20 duration-500">
            <div className="flex flex-col md:flex-row h-full">
              <div className="bg-[#0D47A1] text-white p-16 md:w-1/3 flex flex-col justify-between">
                <div>
                  <div className="w-20 h-20 bg-white rounded-[30px] flex items-center justify-center mb-10 shadow-2xl">
                    <img src="https://justmarkets.com/favicon.ico" alt="Just Market Logo" className="w-12 h-12" />
                  </div>
                  <h2 className="text-4xl font-black mb-6 leading-tight tracking-tighter">بوابة شحن<br/>Just Market</h2>
                  <p className="text-blue-100/70 font-bold text-sm leading-relaxed mb-8">اشحن رصيد نقاطك فوراً بأسعار تبدأ من <span className="text-white">1 دولار</span> لكل عملية تدقيق.</p>
                </div>
                <div className="p-8 bg-black/20 rounded-[35px] border border-white/10 backdrop-blur-md">
                  <p className="text-[10px] font-black text-blue-200 uppercase tracking-widest mb-2">رصيد النقاط الحالي</p>
                  <div className="text-4xl font-black flex items-center gap-3">{userCredits} <Coins className="text-amber-400 w-8 h-8" /></div>
                </div>
              </div>
              <div className="flex-1 p-16 bg-white relative">
                <div className="flex justify-between items-center mb-12">
                  <div className="flex items-center gap-4">
                     <ShoppingBag className="w-8 h-8 text-[#0D47A1]" />
                     <h3 className="text-3xl font-black text-slate-900 tracking-tighter">باقات الشحن</h3>
                  </div>
                  <button onClick={() => setShowWalletModal(false)} className="p-3 bg-slate-50 hover:bg-slate-100 rounded-2xl transition-all"><X className="w-6 h-6 text-slate-400" /></button>
                </div>
                <div className="space-y-6 mb-12">
                   {CREDIT_BUNDLES.map((bundle) => (
                     <div key={bundle.id} onClick={() => { setSelectedBundle(bundle); setShowJustMarketCheckout(true); }} className={`group relative p-8 rounded-[40px] border-2 cursor-pointer transition-all duration-300 flex items-center justify-between hover:border-[#0D47A1] hover:bg-blue-50/20 ${bundle.isPopular ? 'border-[#0D47A1] bg-blue-50/10' : 'border-slate-100'}`}>
                        <div className="flex items-center gap-6">
                           <div className={`w-16 h-16 rounded-[24px] flex items-center justify-center ${bundle.isPopular ? 'bg-[#0D47A1] text-white shadow-lg shadow-blue-900/40' : 'bg-slate-100 text-slate-400'}`}><Coins className="w-7 h-7" /></div>
                           <div>
                              <h4 className="font-black text-slate-900 text-lg mb-1">{bundle.label}</h4>
                              <p className="text-xs font-bold text-slate-400">تشحن حسابك بـ {bundle.points} نقطة</p>
                           </div>
                        </div>
                        <div className="text-right">
                           <div className="text-3xl font-black text-[#0D47A1]">{bundle.price}$</div>
                           <p className="text-[10px] font-black text-emerald-600 uppercase tracking-widest flex items-center gap-1 justify-end"><Lock className="w-3 h-3" /> Secure</p>
                        </div>
                     </div>
                   ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Just Market Gateway */}
      {showJustMarketCheckout && (
        <div className="fixed inset-0 bg-slate-950/60 backdrop-blur-xl z-[130] flex items-center justify-center p-6 no-print">
          <div className="bg-white w-full max-w-lg rounded-[50px] shadow-2xl overflow-hidden border border-[#0D47A1]/30 animate-in zoom-in duration-300">
             <div className="bg-[#0D47A1] p-12 text-white flex items-center justify-between">
                <div className="flex items-center gap-5">
                  <div className="w-14 h-14 bg-white rounded-2xl flex items-center justify-center"><img src="https://justmarkets.com/favicon.ico" alt="JM" className="w-8 h-8" /></div>
                  <div><h4 className="font-black text-xl tracking-tight">بوابة دفع Just Market</h4></div>
                </div>
                {!isProcessingPayment && <button onClick={() => setShowJustMarketCheckout(false)}><X className="w-6 h-6 text-blue-200" /></button>}
             </div>
             <div className="p-12 space-y-12">
                <div className="bg-slate-50 p-8 rounded-[35px] border border-slate-100 flex items-center justify-between text-center">
                   <div><p className="text-[10px] font-black text-slate-400 uppercase mb-1">المبلغ</p><h5 className="text-2xl font-black">{selectedBundle?.price}.00 USD</h5></div>
                   <ArrowRight className="text-slate-200 w-6 h-6 rotate-180" />
                   <div><p className="text-[10px] font-black text-slate-400 uppercase mb-1">النقاط</p><h5 className="text-2xl font-black text-emerald-600">+{selectedBundle?.points}</h5></div>
                </div>
                <button 
                  disabled={isProcessingPayment} 
                  onClick={() => {
                    setIsProcessingPayment(true);
                    setTimeout(() => {
                      setUserCredits(prev => prev + (selectedBundle?.points || 0));
                      setIsProcessingPayment(false);
                      setShowJustMarketCheckout(false);
                      setShowWalletModal(false);
                    }, 2000);
                  }}
                  className="w-full py-6 rounded-[28px] font-black text-lg bg-[#0D47A1] text-white shadow-2xl hover:bg-blue-900 transition-all flex items-center justify-center gap-4"
                >
                  {isProcessingPayment ? <Loader2 className="w-6 h-6 animate-spin" /> : "تأكيد الدفع"}
                </button>
             </div>
          </div>
        </div>
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 6px; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #E2E8F0; border-radius: 20px; }
        .no-scrollbar::-webkit-scrollbar { display: none; }
        
        @media print {
            .no-print { display: none !important; }
            .print-container { 
                display: block !important; 
                position: relative !important;
                visibility: visible !important;
                width: 100% !important;
                height: auto !important;
                margin: 0 !important;
                padding: 1.5cm !important;
            }
            body { 
                background: white !important; 
                margin: 0; 
                padding: 0;
            }
            #root > *:not(.print-container) { display: none !important; }
        }
      `}</style>
    </div>
  );
};

const SidebarIcon = ({ icon, active = false, onClick, label, disabled = false }: { icon: React.ReactNode, active?: boolean, onClick?: () => void, label: string, disabled?: boolean }) => (
  <div className="relative flex items-center justify-center w-full px-2">
    {/* Active Indicator Bar */}
    {active && (
      <div className="absolute right-0 w-1.5 h-10 bg-[#0D47A1] rounded-l-full shadow-[0_0_15px_rgba(13,71,161,0.6)] animate-in slide-in-from-right-2 duration-300" />
    )}
    
    <button 
      onClick={onClick} 
      disabled={disabled} 
      className={`
        relative w-14 h-14 rounded-[20px] transition-all duration-300 flex items-center justify-center group
        ${active ? 'bg-[#0D47A1]/15 text-blue-400 shadow-sm' : 'text-slate-500 hover:text-white hover:bg-white/5'} 
        ${disabled ? 'opacity-20 cursor-not-allowed' : 'hover:scale-110 active:scale-95'}
      `}
    >
      <div className="flex items-center justify-center transition-transform duration-300 group-hover:scale-110">
        {React.cloneElement(icon as React.ReactElement, { 
          size: 24,
          strokeWidth: active ? 2.5 : 2 
        })}
      </div>
      
      {/* Refined Tooltip */}
      <div className={`
        absolute right-full mr-5 px-4 py-2 bg-slate-900 text-white text-[11px] font-black rounded-xl 
        opacity-0 group-hover:opacity-100 translate-x-3 group-hover:translate-x-0 
        transition-all duration-300 whitespace-nowrap z-50 pointer-events-none shadow-[0_10px_30px_-5px_rgba(0,0,0,0.5)] border border-white/5
      `}>
        {label}
        {/* Tooltip Tail */}
        <div className="absolute top-1/2 -translate-y-1/2 -right-1.5 w-3 h-3 bg-slate-900 rotate-45 border-t border-r border-white/5" />
      </div>
    </button>
  </div>
);

const DetailedInsight = ({ title, content, icon, subtitle }: { title: string, content: string, icon: React.ReactNode, subtitle: string }) => (
  <div className="group border rounded-[35px] p-8 bg-white border-slate-100 shadow-xl shadow-slate-200/40 relative overflow-hidden transition-all hover:translate-y-[-4px]">
    <div className="relative z-10 pr-6">
      <div className="flex items-center gap-5 mb-6">
        <div className="w-14 h-14 flex items-center justify-center rounded-[22px] border bg-slate-50 border-slate-100">{React.cloneElement(icon as React.ReactElement, { className: "w-7 h-7 text-[#0D47A1]" })}</div>
        <div><h4 className="font-black text-lg text-slate-900">{title}</h4><p className="text-[10px] font-bold text-slate-400 mt-2 uppercase tracking-widest">{subtitle}</p></div>
      </div>
      <p className="text-sm leading-[1.8] font-medium text-slate-600 whitespace-pre-wrap">{content}</p>
    </div>
  </div>
);

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