import React, { useState, useEffect } from "react";
import { createRoot } from "react-dom/client";
import { 
  Printer, 
  Trash2, 
  Settings, 
  User, 
  Building2, 
  FileText,
  Calculator,
  Upload,
  Server,
  Wifi,
  Cpu,
  Activity,
  Zap,
  CheckCircle2,
  Plus,
  RefreshCw,
  Linkedin,
  Phone,
  Mail,
  Globe,
  Menu,
  X,
  Share2,
  Edit,
  Eye
} from "lucide-react";

// --- بيانات الشركة الموردة (ثابتة) ---
const FIXED_COMPANY_INFO = {
  name: "دواجن تك - Dawajen Tech",
  address: "القاهرة، مصر - المنطقة التكنولوجية",
  email: "sales@ai-dawajen.tech",
  phone: "+201119935714",
  manager: "الاستشاري المهندس عبد الله عزوز",
  linkedin: "https://www.linkedin.com/in/abdallh-azouz-32bb55117/",
  website: "ai-dawajen.tech"
};

// --- قاعدة البيانات ---
const INFRASTRUCTURE_ITEMS = {
  noInternetBundle: [
    { description: "تجهيزات شبكة لاسلكية (5-10 عنابر) - نطاق 500-1000م", price: 10000, unit: "مقطوعية", type: "أجهزة (مرة واحدة)" },
    { description: "اشتراك إنترنت سنوي (باقة أعمال)", price: 3000, unit: "سنة", type: "اشتراك (يجدد)" },
    { description: "خدمة تركيب وبرمجة الشبكة", price: 2000, unit: "خدمة", type: "خدمة (مرة واحدة)" }
  ]
};

const SENSOR_TYPES = [
  { 
    id: 's-temp', 
    name: "حساس حرارة فقط", 
    hardwarePrice: 3000, 
    subPrice: 300, 
    subName: "اشتراك لوحة قراءات (حساس حرارة)" 
  },
  { 
    id: 's-temp-hum', 
    name: "حساس حرارة ورطوبة", 
    hardwarePrice: 3500, 
    subPrice: 300, 
    subName: "اشتراك لوحة قراءات (حساس حرارة ورطوبة)" 
  },
  { 
    id: 's-full', 
    name: "حساس (حرارة + رطوبة + أمونيا)", 
    hardwarePrice: 6000, 
    subPrice: 300, 
    subName: "اشتراك لوحة قراءات (شامل أمونيا)" 
  },
];

const SOFTWARE_PACKAGES = [
  { id: 'sw-basic', name: "داشبورد قراءات وتحليل بياني (عنبر واحد)", price: 1000, unit: "سنة", desc: "تخزين بيانات لحساس أو أكثر - اشتراك سنوي", type: "اشتراك (يجدد)" },
  { id: 'sw-ai-pred', name: "لوحة شاملة + ذكاء اصطناعي وتحليل توقعي (عنبر واحد)", price: 2000, unit: "سنة", desc: "لحساس أو أكثر - اشتراك سنوي", type: "اشتراك (يجدد)" },
  { id: 'sw-farm-full', name: "لوحة مزرعة كاملة (5-10 عنابر)", price: 6000, unit: "سنة", desc: "تدعم 10 إلى 20 حساس - اشتراك سنوي", type: "اشتراك (يجدد)" },
  { id: 'sw-ai-expert', name: "داشبورد الخبير (AI Expert) وتحليل السلوك والأمراض", price: 10000, unit: "سنة", desc: "لمزرعة 5-10 عنابر (بيئة شاملة) - اشتراك سنوي", type: "اشتراك (يجدد)" },
];

interface LineItem {
  id: string;
  description: string;
  quantity: number;
  price: number;
  unit: string;
  type: string;
}

interface InvoiceState {
  invoiceNumber: string;
  date: string;
  dueDate: string;
  clientName: string;
  clientAddress: string;
  currency: string;
  taxRate: number;
  logo: string | null;
  notes: string;
  items: LineItem[];
}

const initialState: InvoiceState = {
  invoiceNumber: "INV-0001",
  date: new Date().toISOString().split('T')[0],
  dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
  clientName: "مزرعة الهدى للدواجن",
  clientAddress: "طريق الإسماعيلية الصحراوي",
  currency: "ج.م",
  taxRate: 14,
  logo: null,
  notes: "ملاحظات هامة:\n- الأسعار المذكورة أعلاه تشمل تكاليف السنة الأولى (الأجهزة + الاشتراكات).\n- يتم تجديد الاشتراكات (البنود الموضحة كـ 'اشتراك') بشكل سنوي.\n- ضمان عام كامل على الهاردوير ضد عيوب الصناعة.",
  items: []
};

// --- Components ---

const EditorSidebar = ({ 
  data, setData, activeTab, setActiveTab, 
  hasInternet, setHasInternet, 
  selectedSensor, setSelectedSensor, 
  sensorQty, setSensorQty, 
  softwareQty, setSoftwareQty, 
  addInfrastructure, addSensorPackage, addSoftware, addManualItem, removeItem, updateItem,
  isVisible // New prop for mobile visibility
}: any) => {

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setData((prev: any) => ({ ...prev, [name]: value }));
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => setData((prev: any) => ({ ...prev, logo: reader.result as string }));
      reader.readAsDataURL(file);
    }
  };

  return (
    <div className={`
      w-full lg:w-5/12 bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden flex-col 
      h-[calc(100vh-80px)] lg:h-[calc(100vh-2rem)] lg:sticky lg:top-4 no-print
      ${isVisible ? 'flex' : 'hidden lg:flex'}
    `}>
      <div className="bg-secondary p-4 text-white flex justify-between items-center shrink-0">
        <h2 className="text-lg font-bold flex items-center gap-2">
          <Settings className="w-5 h-5" />
          مُنشئ العرض الفني
        </h2>
        <button onClick={() => window.print()} className="bg-primary hover:bg-blue-800 text-white px-3 py-1.5 rounded-lg text-xs font-bold flex items-center gap-2 transition-colors">
          <Printer className="w-4 h-4" /> طباعة / PDF
        </button>
      </div>

      <div className="flex border-b border-gray-200 bg-gray-50 overflow-x-auto shrink-0 scrollbar-hide">
        <button onClick={() => setActiveTab('wizard')} className={`flex-1 min-w-[100px] py-4 px-2 text-sm font-bold whitespace-nowrap transition-colors ${activeTab === 'wizard' ? 'text-primary border-b-2 border-primary bg-white' : 'text-gray-500 hover:bg-gray-100'}`}>
          <Zap className="w-4 h-4 inline ml-1" /> بناء النظام
        </button>
        <button onClick={() => setActiveTab('items')} className={`flex-1 min-w-[100px] py-4 px-2 text-sm font-bold whitespace-nowrap transition-colors ${activeTab === 'items' ? 'text-primary border-b-2 border-primary bg-white' : 'text-gray-500 hover:bg-gray-100'}`}>
          <FileText className="w-4 h-4 inline ml-1" /> البنود
        </button>
        <button onClick={() => setActiveTab('details')} className={`flex-1 min-w-[100px] py-4 px-2 text-sm font-bold whitespace-nowrap transition-colors ${activeTab === 'details' ? 'text-primary border-b-2 border-primary bg-white' : 'text-gray-500 hover:bg-gray-100'}`}>
          <User className="w-4 h-4 inline ml-1" /> العميل
        </button>
        <button onClick={() => setActiveTab('settings')} className={`flex-1 min-w-[100px] py-4 px-2 text-sm font-bold whitespace-nowrap transition-colors ${activeTab === 'settings' ? 'text-primary border-b-2 border-primary bg-white' : 'text-gray-500 hover:bg-gray-100'}`}>
          <Settings className="w-4 h-4 inline ml-1" /> إعدادات
        </button>
      </div>

      <div className="flex-1 overflow-y-auto p-4 space-y-6 pb-20 lg:pb-6">
        
        {/* --- TAB 1: SYSTEM WIZARD --- */}
        {activeTab === 'wizard' && (
          <div className="space-y-6 animate-fadeIn">
            
            {/* Step 1: Infrastructure */}
            <div className="bg-gray-50 p-4 rounded-xl border border-gray-200">
              <h3 className="font-bold text-secondary mb-3 flex items-center gap-2">
                <Wifi className="w-5 h-5 text-primary" />
                1. تأسيس البنية التحتية
              </h3>
              <p className="text-sm text-gray-600 mb-4">هل يوجد نظام إنترنت في المزرعة؟</p>
              
              <div className="flex gap-3 mb-4">
                <button 
                  onClick={() => setHasInternet(true)}
                  className={`flex-1 py-3 rounded-lg border text-sm font-bold transition-all ${hasInternet === true ? 'bg-green-100 border-green-500 text-green-700 shadow-sm' : 'bg-white border-gray-300 text-gray-600 hover:bg-gray-50'}`}>
                  نعم، يوجد نت
                </button>
                <button 
                  onClick={() => setHasInternet(false)}
                  className={`flex-1 py-3 rounded-lg border text-sm font-bold transition-all ${hasInternet === false ? 'bg-red-100 border-red-500 text-red-700 shadow-sm' : 'bg-white border-gray-300 text-gray-600 hover:bg-gray-50'}`}>
                  لا يوجد نت
                </button>
              </div>

              {hasInternet === false && (
                <div className="bg-white p-4 rounded-lg border border-red-100 shadow-sm">
                  <div className="text-sm font-bold text-secondary mb-2">باقة التأسيس الكاملة (واى فاي 10 عنابر):</div>
                  <ul className="text-xs text-gray-500 list-disc list-inside mb-4 space-y-1.5">
                    <li>أجهزة واى فاى (500-1000 متر) - 10,000 ج.م <span className="text-[10px] bg-gray-200 rounded px-1.5 py-0.5">مرة واحدة</span></li>
                    <li>اشتراك إنترنت سنوي - 3,000 ج.م <span className="text-[10px] bg-yellow-100 text-yellow-700 rounded px-1.5 py-0.5">سنوي</span></li>
                    <li>خدمة تركيب - 2,000 ج.م</li>
                  </ul>
                  <button onClick={addInfrastructure} className="w-full bg-primary text-white py-3 rounded-lg text-sm font-bold hover:bg-blue-800 transition shadow-md active:scale-95 transform duration-150">
                    إضافة باقة التأسيس (15,000 ج.م)
                  </button>
                </div>
              )}
            </div>

            {/* Step 2: Sensors */}
            <div className="bg-gray-50 p-4 rounded-xl border border-gray-200">
              <h3 className="font-bold text-secondary mb-3 flex items-center gap-2">
                <Cpu className="w-5 h-5 text-primary" />
                2. الحساسات والأجهزة
              </h3>
              <div className="space-y-4">
                <div>
                  <label className="text-xs font-bold text-gray-500 block mb-1.5">نوع الحساس</label>
                  <select 
                    className="w-full p-3 border border-gray-300 rounded-lg text-sm bg-white outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                    value={selectedSensor}
                    onChange={(e) => setSelectedSensor(e.target.value)}
                  >
                    {SENSOR_TYPES.map(s => (
                      <option key={s.id} value={s.id}>{s.name} ({s.hardwarePrice} ج + {s.subPrice} اشتراك)</option>
                    ))}
                  </select>
                </div>
                <div className="flex gap-3 items-end">
                  <div className="w-1/3">
                    <label className="text-xs font-bold text-gray-500 block mb-1.5">العدد</label>
                    <input 
                      type="number" 
                      min="1"
                      className="w-full p-3 border border-gray-300 rounded-lg text-sm text-center outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                      value={sensorQty}
                      onChange={(e) => setSensorQty(parseInt(e.target.value) || 1)}
                    />
                  </div>
                  <button onClick={addSensorPackage} className="flex-1 bg-primary text-white py-3 rounded-lg text-sm font-bold hover:bg-blue-800 transition shadow-md active:scale-95 transform duration-150 h-[46px]">
                    إضافة
                  </button>
                </div>
              </div>
            </div>

            {/* Step 3: Software */}
            <div className="bg-gray-50 p-4 rounded-xl border border-gray-200">
              <h3 className="font-bold text-secondary mb-3 flex items-center gap-2">
                <Activity className="w-5 h-5 text-primary" />
                3. باقات البرمجيات
              </h3>
              
              {/* Software Quantity Input */}
              <div className="mb-4 bg-blue-50 p-4 rounded-lg border border-blue-100">
                <div className="flex items-center justify-between mb-2">
                  <label className="text-sm font-bold text-blue-900">عدد العنابر (للنسخ الفردية):</label>
                  <input 
                    type="number" 
                    min="1" 
                    value={softwareQty}
                    onChange={(e) => setSoftwareQty(Math.max(1, parseInt(e.target.value) || 1))}
                    className="w-20 p-2 text-lg text-center border-2 border-blue-200 rounded-lg font-bold text-primary outline-none focus:border-primary"
                  />
                </div>
                <p className="text-xs text-blue-600 opacity-80">* هذا العدد يطبق فقط على الباقة الأولى والثانية.</p>
              </div>

              <div className="grid grid-cols-1 gap-3">
                {SOFTWARE_PACKAGES.map(pkg => {
                   const isFarmPackage = pkg.id === 'sw-farm-full' || pkg.id === 'sw-ai-expert';
                   return (
                  <button 
                    key={pkg.id}
                    onClick={() => addSoftware(pkg)}
                    className="flex flex-col items-start p-4 bg-white border border-gray-200 rounded-xl hover:border-primary hover:bg-blue-50/50 transition text-right group relative shadow-sm active:scale-[0.98]"
                  >
                    <div className="flex justify-between items-center w-full mb-2">
                      <span className="text-sm font-bold text-secondary group-hover:text-primary">{pkg.name}</span>
                      <span className="text-sm font-bold text-primary bg-blue-50 px-2.5 py-1 rounded-md">{pkg.price.toLocaleString()} ج.م</span>
                    </div>
                    <span className="text-xs text-gray-500 mb-2 leading-relaxed">{pkg.desc}</span>
                    <div className="flex flex-wrap gap-2 mt-1 w-full justify-start">
                      <span className="text-[10px] bg-yellow-100 text-yellow-800 px-2 py-0.5 rounded-full font-bold">يجدد سنوياً</span>
                      {isFarmPackage && <span className="text-[10px] bg-green-100 text-green-800 px-2 py-0.5 rounded-full font-bold">باقة مزرعة</span>}
                    </div>
                  </button>
                )})}
              </div>
            </div>

          </div>
        )}

        {/* --- TAB 2: EDIT ITEMS --- */}
        {activeTab === 'items' && (
          <div className="space-y-4 animate-fadeIn">
            {data.items.length === 0 ? (
              <div className="text-center py-16 text-gray-400 bg-gray-50 rounded-xl border-2 border-dashed border-gray-200">
                <Server className="w-16 h-16 mx-auto mb-3 opacity-20" />
                <p className="text-base font-medium">لم يتم إضافة أي بنود.</p>
                <button onClick={() => setActiveTab('wizard')} className="text-primary text-sm font-bold mt-2 underline">الذهاب للمعالج</button>
              </div>
            ) : (
              data.items.map((item: any, index: number) => (
                <div key={item.id} className="bg-white p-4 rounded-xl border border-gray-200 shadow-sm relative group hover:shadow-md transition-shadow">
                  <button onClick={() => removeItem(item.id)} className="absolute top-3 left-3 text-gray-300 hover:text-red-500 p-1">
                    <Trash2 className="w-5 h-5" />
                  </button>
                  <div className="pr-8">
                    <input 
                      type="text" 
                      value={item.description} 
                      onChange={(e) => updateItem(item.id, 'description', e.target.value)}
                      className="w-full text-base font-bold text-secondary mb-3 border-b border-transparent focus:border-gray-300 outline-none pb-1 bg-transparent"
                    />
                    <div className="grid grid-cols-2 gap-3 mb-2">
                      <div>
                         <label className="text-[10px] text-gray-400 block mb-1">النوع</label>
                         <input type="text" value={item.type} readOnly className="w-full bg-gray-50 text-xs p-2 rounded text-gray-500 border border-transparent" />
                      </div>
                      <div>
                         <label className="text-[10px] text-gray-400 block mb-1">الإجمالي</label>
                         <div className="w-full text-xs p-2 bg-gray-100 rounded text-center font-bold text-gray-700">
                           {(item.price * item.quantity).toLocaleString()}
                         </div>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                         <label className="text-[10px] text-gray-400 block mb-1">الكمية</label>
                         <input 
                           type="number" 
                           value={item.quantity} 
                           onChange={(e) => updateItem(item.id, 'quantity', parseFloat(e.target.value) || 0)}
                           className="w-full text-sm p-2 border rounded text-center font-bold text-secondary focus:border-primary outline-none" 
                          />
                      </div>
                      <div>
                         <label className="text-[10px] text-gray-400 block mb-1">السعر</label>
                         <input 
                           type="number" 
                           value={item.price} 
                           onChange={(e) => updateItem(item.id, 'price', parseFloat(e.target.value) || 0)}
                           className="w-full text-sm p-2 border rounded text-center text-gray-600 focus:border-primary outline-none" 
                          />
                      </div>
                    </div>
                  </div>
                </div>
              ))
            )}
            <button onClick={addManualItem} className="w-full py-4 border-2 border-dashed border-gray-300 rounded-xl text-gray-500 text-sm font-bold hover:border-primary hover:text-primary transition flex items-center justify-center gap-2 bg-gray-50">
              <Plus className="w-5 h-5" /> إضافة بند يدوي
            </button>
          </div>
        )}

        {/* --- TAB 3: DETAILS --- */}
        {activeTab === 'details' && (
          <div className="space-y-5 animate-fadeIn">
            <div className="space-y-2">
              <label className="text-sm font-bold text-gray-600">لوجو الشركة</label>
              <div className="flex items-center gap-3">
                <label className="flex-1 cursor-pointer border-2 border-dashed border-gray-300 rounded-xl p-4 flex flex-col items-center justify-center hover:bg-gray-50 hover:border-primary transition group">
                  <Upload className="w-6 h-6 text-gray-400 mb-2 group-hover:text-primary" />
                  <span className="text-xs text-gray-500 font-bold">اضغط لرفع الشعار</span>
                  <input type="file" className="hidden" accept="image/*" onChange={handleFileChange} />
                </label>
                {data.logo && <div className="p-2 border rounded-xl bg-white"><img src={data.logo} className="h-20 w-20 object-contain" /></div>}
              </div>
            </div>
            
            <div className="p-4 bg-blue-50/50 rounded-xl border border-blue-100 space-y-3">
               <h4 className="text-sm font-bold text-blue-900 flex items-center gap-2">
                 <User className="w-4 h-4" /> بيانات العميل
               </h4>
               <input type="text" name="clientName" placeholder="اسم العميل / الشركة" value={data.clientName} onChange={handleInputChange} className="w-full p-3 text-sm border rounded-lg focus:ring-2 focus:ring-blue-100 outline-none" />
               <input type="text" name="clientAddress" placeholder="عنوان العميل" value={data.clientAddress} onChange={handleInputChange} className="w-full p-3 text-sm border rounded-lg focus:ring-2 focus:ring-blue-100 outline-none" />
            </div>

             <div className="p-4 bg-gray-50 rounded-xl border border-gray-200 space-y-3 relative">
               <h4 className="text-sm font-bold text-gray-700 mb-2">بيانات الشركة الموردة (ثابتة)</h4>
               <div className="text-sm space-y-2 text-gray-600 pl-4">
                  <p className="font-bold text-secondary">{FIXED_COMPANY_INFO.name}</p>
                  <p className="text-xs">{FIXED_COMPANY_INFO.address}</p>
                  <p className="text-xs">{FIXED_COMPANY_INFO.email}</p>
                  <hr className="my-3 border-gray-200" />
                  <p className="text-xs font-bold text-primary">مدير الشركة:</p>
                  <p className="text-xs">{FIXED_COMPANY_INFO.manager}</p>
               </div>
               <div className="absolute top-4 left-4">
                  <CheckCircle2 className="w-5 h-5 text-green-500" />
               </div>
            </div>
          </div>
        )}

        {/* --- TAB 4: SETTINGS --- */}
        {activeTab === 'settings' && (
          <div className="space-y-5 animate-fadeIn">
             <div className="grid grid-cols-2 gap-4">
               <div>
                 <label className="text-xs text-gray-500 font-bold block mb-1.5">رقم العرض</label>
                 <input type="text" name="invoiceNumber" value={data.invoiceNumber} onChange={handleInputChange} className="w-full p-3 text-sm border rounded-lg focus:border-primary outline-none" />
               </div>
               <div>
                 <label className="text-xs text-gray-500 font-bold block mb-1.5">الضريبة %</label>
                 <input type="number" name="taxRate" value={data.taxRate} onChange={(e) => setData((prev:any) => ({...prev, taxRate: parseFloat(e.target.value) || 0}))} className="w-full p-3 text-sm border rounded-lg focus:border-primary outline-none" />
               </div>
             </div>
             <div>
                <label className="text-xs text-gray-500 font-bold block mb-1.5">ملاحظات وشروط</label>
                <textarea name="notes" rows={8} value={data.notes} onChange={handleInputChange} className="w-full p-3 text-sm border rounded-lg focus:border-primary outline-none leading-relaxed"></textarea>
             </div>
          </div>
        )}

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

const InvoicePreview = ({ data, removeItem, isVisible }: { data: InvoiceState, removeItem: (id: string) => void, isVisible: boolean }) => {
  // Calculations
  const calculateSubtotal = () => data.items.reduce((acc, item) => acc + (item.quantity * item.price), 0);
  const calculateTax = () => calculateSubtotal() * (data.taxRate / 100);
  const calculateTotal = () => calculateSubtotal() + calculateTax();
  const calculateRenewalCost = () => {
    return data.items
      .filter(item => item.type && item.type.includes("اشتراك"))
      .reduce((acc, item) => acc + (item.quantity * item.price), 0);
  };

  // Share handler
  const handleShare = async () => {
    try {
      const json = JSON.stringify(data);
      const encoded = btoa(unescape(encodeURIComponent(json)));
      const url = `${window.location.origin}${window.location.pathname}?q=${encoded}`;
      await navigator.clipboard.writeText(url);
      alert("تم نسخ رابط العرض إلى الحافظة بنجاح!\nيمكنك إرساله للعميل مباشرة.");
    } catch (err) {
      console.error('Failed to copy: ', err);
      alert("حدث خطأ أثناء نسخ الرابط.");
    }
  };

  return (
    <div className={`
      flex-1 flex flex-col items-center bg-gray-100 invoice-wrapper relative transition-all duration-300
      ${isVisible ? 'block' : 'hidden lg:flex'}
      h-[calc(100vh-80px)] lg:h-screen lg:overflow-y-auto p-2 lg:p-8 print:p-0 print:h-auto print:overflow-visible
    `}>
      
      {/* Action Bar */}
      <div className="w-full max-w-[210mm] flex justify-end mb-4 no-print px-2 lg:px-0 mt-4 lg:mt-0">
         <button 
          onClick={handleShare}
          className="bg-white border border-gray-300 text-gray-700 hover:bg-gray-50 hover:text-primary hover:border-primary px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2 transition-all shadow-sm active:scale-95"
          title="مشاركة رابط العرض"
        >
          <Share2 className="w-4 h-4" />
          <span className="hidden sm:inline">مشاركة الرابط</span>
          <span className="sm:hidden">مشاركة</span>
        </button>
      </div>

      {/* Invoice Container Wrapper */}
      <div className="w-full flex justify-center pb-20 lg:pb-0 print:pb-0 print:block">
        <div className="invoice-container w-full lg:w-[210mm] min-h-auto lg:min-h-[297mm] bg-white shadow-xl p-4 sm:p-6 md:p-10 relative flex flex-col justify-between mb-0" id="invoice-paper">
          
          {/* Header */}
          <div className="flex flex-col-reverse lg:flex-row print:flex-row justify-between items-center lg:items-start mb-6 lg:mb-8 gap-6 lg:gap-0">
            <div className="w-full lg:w-3/5 print:w-[60%] text-center lg:text-right print:text-right">
              {data.logo ? (
                <img src={data.logo} className="h-24 object-contain mb-4 mx-auto lg:mx-0 print:mx-0" />
              ) : (
                <div className="h-20 w-20 bg-primary/10 rounded-lg flex items-center justify-center text-primary mb-4 mx-auto lg:mx-0 print:mx-0">
                  <Building2 className="w-10 h-10" />
                </div>
              )}
              <h1 className="text-2xl font-bold text-secondary mb-1">{FIXED_COMPANY_INFO.name}</h1>
              <p className="text-base text-gray-600 whitespace-pre-line mb-4 font-medium">{FIXED_COMPANY_INFO.address}</p>
              
              <div className="mt-3 space-y-2">
                <p className="text-gray-700 font-bold text-sm">مدير الشركة: <span className="text-secondary">{FIXED_COMPANY_INFO.manager}</span></p>
                
                <div className="flex flex-wrap gap-4 mt-1 items-center justify-center lg:justify-start print:justify-start">
                  <a href={`https://wa.me/${FIXED_COMPANY_INFO.phone.replace('+', '')}`} target="_blank" rel="noreferrer" className="flex items-center gap-2 text-green-700 hover:text-green-800 text-sm font-bold no-underline print:text-black">
                    <Phone className="w-4 h-4" />
                    {FIXED_COMPANY_INFO.phone}
                  </a>
                  <a href={FIXED_COMPANY_INFO.linkedin} target="_blank" rel="noreferrer" className="flex items-center gap-2 text-blue-700 hover:text-blue-800 text-sm font-bold no-underline print:text-black">
                    <Linkedin className="w-4 h-4" />
                    LinkedIn
                  </a>
                  <a href={`mailto:${FIXED_COMPANY_INFO.email}`} className="flex items-center gap-2 text-gray-600 hover:text-gray-800 text-sm font-semibold no-underline">
                    <Mail className="w-4 h-4" />
                    {FIXED_COMPANY_INFO.email}
                  </a>
                </div>
              </div>
            </div>
            
            <div className="w-full lg:w-2/5 print:w-[40%] text-center lg:text-left print:text-left rtl:lg:text-left rtl:print:text-left">
              <h2 className="text-4xl lg:text-5xl font-black text-gray-200 uppercase mb-6 tracking-wide">عرض سعر</h2>
              <div className="space-y-2 max-w-xs mx-auto lg:mx-0 print:mx-0">
                <div className="flex justify-between border-b border-gray-200 pb-2">
                  <span className="text-sm font-bold text-gray-600">رقم العرض:</span>
                  <span className="text-base font-bold text-secondary">{data.invoiceNumber}</span>
                </div>
                <div className="flex justify-between border-b border-gray-200 pb-2">
                  <span className="text-sm font-bold text-gray-600">التاريخ:</span>
                  <span className="text-base font-bold text-secondary">{data.date}</span>
                </div>
                <div className="flex justify-between border-b border-gray-200 pb-2">
                  <span className="text-sm font-bold text-gray-600">صالح حتى:</span>
                  <span className="text-base font-bold text-secondary">{data.dueDate}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Client Info */}
          <div className="bg-gray-50 p-5 rounded-lg border-r-4 border-primary mb-8 shadow-sm print:shadow-none">
            <h3 className="text-sm font-bold text-gray-500 uppercase mb-2 tracking-wide">عرض سعر موجه إلى السادة</h3>
            <p className="text-xl font-bold text-secondary mb-1">{data.clientName}</p>
            <p className="text-base font-medium text-gray-600">{data.clientAddress}</p>
          </div>

          {/* Items Table - Scrollable on mobile */}
          <div className="mb-8 flex-1 overflow-x-auto">
            <table className="w-full min-w-[600px] lg:min-w-0">
              <thead>
                <tr className="bg-secondary text-white text-sm">
                  <th className="py-3 px-4 text-right rounded-r-lg font-bold">البيان / الوصف</th>
                  <th className="py-3 px-4 text-center font-bold">النوع</th>
                  <th className="py-3 px-4 text-center font-bold">الكمية</th>
                  <th className="py-3 px-4 text-center font-bold">الوحدة</th>
                  <th className="py-3 px-4 text-center font-bold">السعر</th>
                  <th className="py-3 px-4 text-center font-bold">الإجمالي</th>
                  <th className="py-3 px-2 w-8 rounded-l-lg no-print"></th>
                </tr>
              </thead>
              <tbody className="text-base">
                {data.items.map((item, idx) => (
                  <tr key={idx} className={`border-b border-gray-200 hover:bg-gray-50 group/row transition-colors ${item.type && item.type.includes('اشتراك') ? 'bg-yellow-50/50' : ''}`}>
                    <td className="py-4 px-4 font-bold text-gray-800">
                      {item.description}
                    </td>
                    <td className="py-4 px-4 text-center text-xs font-semibold text-gray-600 whitespace-nowrap">{item.type}</td>
                    <td className="py-4 px-4 text-center font-bold text-secondary text-lg">{item.quantity}</td>
                    <td className="py-4 px-4 text-center text-sm font-semibold text-gray-600">{item.unit}</td>
                    <td className="py-4 px-4 text-center font-semibold text-gray-700">{item.price.toLocaleString()}</td>
                    <td className="py-4 px-4 text-center font-bold text-secondary text-lg">{(item.price * item.quantity).toLocaleString()}</td>
                    
                    <td className="py-4 px-2 text-center no-print align-middle">
                      <button 
                        onClick={() => removeItem(item.id)}
                        className="text-gray-300 hover:text-red-600 transition-colors p-1"
                        title="حذف البند"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </td>
                  </tr>
                ))}
                {data.items.length === 0 && (
                  <tr>
                    <td colSpan={7} className="py-12 text-center text-gray-400 text-base font-medium">لا توجد بنود.. استخدم "بناء النظام" لإضافة البنود.</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {/* Footer & Totals */}
          <div className="flex flex-col lg:flex-row print:flex-row gap-6 lg:gap-10 border-t-2 border-gray-200 pt-8">
            <div className="w-full lg:w-2/3 print:w-[66%]">
              <h4 className="text-base font-bold text-secondary mb-3">ملاحظات وشروط التعاقد</h4>
              <div className="bg-gray-50 p-4 rounded-lg text-sm font-medium text-gray-700 leading-relaxed whitespace-pre-wrap border border-gray-200 shadow-sm print:shadow-none">
                {data.notes}
              </div>
              
              {/* Renewal Cost Summary */}
              {calculateRenewalCost() > 0 && (
                <div className="mt-5 flex items-center gap-3 p-4 bg-blue-50 border border-blue-100 rounded-lg text-blue-900 shadow-sm print:shadow-none">
                  <RefreshCw className="w-5 h-5" />
                  <div className="text-sm font-bold">
                    تكلفة التجديد السنوي المتوقعة (للاشتراكات): <span className="font-mono text-base">{calculateRenewalCost().toLocaleString()} {data.currency}</span>
                  </div>
                </div>
              )}
            </div>
            <div className="w-full lg:w-1/3 print:w-[33%] space-y-3">
              <div className="flex justify-between text-base border-b border-gray-100 pb-2">
                <span className="text-gray-600 font-semibold">المجموع الفرعي (السنة الأولى)</span>
                <span className="font-bold text-secondary text-lg">{calculateSubtotal().toLocaleString()} {data.currency}</span>
              </div>
              <div className="flex justify-between text-base border-b border-gray-100 pb-2">
                <span className="text-gray-600 font-semibold">ضريبة القيمة المضافة ({data.taxRate}%)</span>
                <span className="font-bold text-secondary text-lg">{calculateTax().toLocaleString()} {data.currency}</span>
              </div>
              <div className="flex justify-between text-xl bg-secondary text-white p-4 rounded-xl shadow-md mt-4 print:shadow-none print:bg-secondary print:text-white">
                <span className="font-bold">الإجمالي (السنة الأولى)</span>
                <span className="font-bold">{calculateTotal().toLocaleString()} {data.currency}</span>
              </div>
            </div>
          </div>

          <div className="mt-auto pt-10 text-center">
            <p className="text-xs text-gray-400 font-medium">تم إصدار هذا العرض إلكترونياً بواسطة نظام دواجن تك (ai-dawajen.tech)</p>
          </div>

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

// Main App Component
const App = () => {
  const [data, setData] = useState<InvoiceState>(initialState);
  const [activeTab, setActiveTab] = useState<'wizard' | 'items' | 'details' | 'settings'>('wizard');
  const [mobileView, setMobileView] = useState<'editor' | 'preview'>('editor'); // New State for Mobile View
  
  // States for the Wizard
  const [hasInternet, setHasInternet] = useState<boolean | null>(null);
  const [selectedSensor, setSelectedSensor] = useState<string>(SENSOR_TYPES[0].id);
  const [sensorQty, setSensorQty] = useState<number>(1);
  const [softwareQty, setSoftwareQty] = useState<number>(1); 

  // Load data from URL if present
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const q = params.get('q');
    if (q) {
      try {
        const json = decodeURIComponent(escape(atob(q)));
        const loadedData = JSON.parse(json);
        if (loadedData) {
          setData(loadedData);
        }
      } catch (e) {
        console.error("Failed to parse URL data", e);
      }
    }
  }, []);

  // --- Actions ---
  const updateItem = (id: string, field: keyof LineItem, value: any) => {
    setData(prev => ({
      ...prev,
      items: prev.items.map(item => item.id === id ? { ...item, [field]: value } : item)
    }));
  };

  const removeItem = (id: string) => {
    setData(prev => ({ ...prev, items: prev.items.filter(item => item.id !== id) }));
  };

  const addInfrastructure = () => {
    const newItems = INFRASTRUCTURE_ITEMS.noInternetBundle.map(item => ({
      id: Date.now().toString() + Math.random(),
      description: item.description,
      quantity: 1,
      price: item.price,
      unit: item.unit,
      type: item.type
    }));
    setData(prev => ({ ...prev, items: [...prev.items, ...newItems] }));
  };

  const addSensorPackage = () => {
    const sensor = SENSOR_TYPES.find(s => s.id === selectedSensor);
    if (!sensor) return;
    const hwItem: LineItem = {
      id: Date.now().toString() + "-hw",
      description: `جهاز ${sensor.name}`,
      quantity: sensorQty,
      price: sensor.hardwarePrice,
      unit: "جهاز",
      type: "أجهزة (مرة واحدة)"
    };
    const subItem: LineItem = {
      id: Date.now().toString() + "-sub",
      description: `${sensor.subName} - (يجدد سنوياً)`,
      quantity: sensorQty,
      price: sensor.subPrice,
      unit: "سنة",
      type: "اشتراك (يجدد)"
    };
    setData(prev => ({ ...prev, items: [...prev.items, hwItem, subItem] }));
  };

  const addSoftware = (pkg: typeof SOFTWARE_PACKAGES[0]) => {
    const isSingleBarnPackage = pkg.id === 'sw-basic' || pkg.id === 'sw-ai-pred';
    const quantityToAdd = isSingleBarnPackage ? softwareQty : 1;

    const newItem: LineItem = {
      id: Date.now().toString() + Math.random(),
      description: pkg.name,
      quantity: quantityToAdd,
      price: pkg.price,
      unit: pkg.unit,
      type: pkg.type
    };
    setData(prev => ({ ...prev, items: [...prev.items, newItem] }));
  };

  const addManualItem = () => {
    setData(prev => ({
      ...prev,
      items: [...prev.items, { id: Date.now().toString(), description: "", quantity: 1, price: 0, unit: "عدد", type: "عام" }]
    }));
  };

  return (
    <div className="min-h-screen bg-gray-100 flex flex-col lg:flex-row gap-4 p-0 lg:p-4 lg:h-screen lg:overflow-hidden font-sans">
      
      <EditorSidebar 
        data={data}
        setData={setData}
        activeTab={activeTab}
        setActiveTab={setActiveTab}
        hasInternet={hasInternet}
        setHasInternet={setHasInternet}
        selectedSensor={selectedSensor}
        setSelectedSensor={setSelectedSensor}
        sensorQty={sensorQty}
        setSensorQty={setSensorQty}
        softwareQty={softwareQty}
        setSoftwareQty={setSoftwareQty}
        addInfrastructure={addInfrastructure}
        addSensorPackage={addSensorPackage}
        addSoftware={addSoftware}
        addManualItem={addManualItem}
        removeItem={removeItem}
        updateItem={updateItem}
        isVisible={mobileView === 'editor'}
      />
      
      <InvoicePreview 
        data={data} 
        removeItem={removeItem} 
        isVisible={mobileView === 'preview'}
      />

      {/* --- Mobile Bottom Navigation --- */}
      <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 lg:hidden flex z-50 shadow-[0_-2px_10px_rgba(0,0,0,0.1)] h-[70px] pb-1">
        <button 
          onClick={() => setMobileView('editor')}
          className={`flex-1 flex flex-col items-center justify-center gap-1 transition-all duration-200 active:scale-95
          ${mobileView === 'editor' ? 'text-primary bg-blue-50/50' : 'text-gray-400'}`}
        >
          <Edit className={`w-6 h-6 ${mobileView === 'editor' ? 'fill-current' : ''}`} />
          <span className="text-xs font-bold">تعديل البيانات</span>
        </button>
        <div className="w-[1px] bg-gray-100 my-2"></div>
        <button 
          onClick={() => setMobileView('preview')}
          className={`flex-1 flex flex-col items-center justify-center gap-1 transition-all duration-200 active:scale-95
          ${mobileView === 'preview' ? 'text-primary bg-blue-50/50' : 'text-gray-400'}`}
        >
          <Eye className={`w-6 h-6 ${mobileView === 'preview' ? 'fill-current' : ''}`} />
          <span className="text-xs font-bold">معاينة الفاتورة</span>
        </button>
      </div>
    </div>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(<App />);