
import { GoogleGenAI } from "@google/genai";

// --- بيانات الكتب والأسعار المحدثة ---
const BOOKS = [
  // القسم العلمي
  { id: 'chem', title: 'كيمياء', price: 320, track: 'علمي', image: 'https://images.unsplash.com/photo-1532187875605-2fe358511423?q=80&w=600', description: 'مريح الكيمياء للشهادة السودانية.' },
  { id: 'phys', title: 'فيزياء', price: 320, track: 'علمي', image: 'https://images.unsplash.com/photo-1636466497217-26a8cbeaf0aa?q=80&w=600', description: 'مريح الفيزياء - شامل الامتحانات والحلول.' },
  { id: 'bio', title: 'أحياء', price: 330, track: 'علمي', image: 'https://images.unsplash.com/photo-1530210124550-912dc1381cb8?q=80&w=600', description: 'مريح الأحياء - الطبعة الجديدة.' },
  { id: 'eng', title: 'هندسية', price: 330, track: 'علمي', image: 'https://images.unsplash.com/photo-1581094794329-c8112a89af12?q=80&w=600', description: 'مريح العلوم الهندسية.' },
  { id: 'cs', title: 'علوم حاسوب', price: 330, track: 'علمي', image: 'https://images.unsplash.com/photo-1517694712202-14dd9538aa97?q=80&w=600', description: 'مريح علوم الحاسوب.' },
  { id: 'math-spec', title: 'رياضيات متخصصة', price: 300, track: 'علمي', image: 'https://images.unsplash.com/photo-1635070041078-e363dbe005cb?q=80&w=600', description: 'رياضيات (2) للمساق العلمي.' },
  { id: 'math1', title: 'رياضيات "1"', price: 300, track: 'مشترك', image: 'https://images.unsplash.com/photo-1509228468518-180dd48229d4?q=80&w=600', description: 'الرياضيات الأساسية لكل المسارات.' },
  // القسم الأدبي
  { id: 'geo', title: 'جغرافيا', price: 290, track: 'أدبي', image: 'https://images.unsplash.com/photo-1521295121783-8a321d551ad2?q=80&w=600', description: 'مريح الجغرافيا والدراسات البيئية.' },
  { id: 'hist', title: 'تاريخ', price: 290, track: 'أدبي', image: 'https://images.unsplash.com/photo-1461360221794-798d196968c1?q=80&w=600', description: 'مريح التاريخ - مبوب حسب الوحدات.' }
];

const LEGAL = {
  about: { title: 'من نحن', content: 'شباب سودانيين نوفر كتب ومريحات للشهادة السودانية لتسهيل الدراسة وضمان التفوق.' },
  terms: { title: 'الشروط والأحكام', content: 'لا نشارك بياناتك مع أي جهة. البيانات تُستخدم فقط لغرض التوصيل. الدفع عند الاستلام.' },
  privacy: { title: 'سياسة الخصوصية', content: 'نحن نلتزم بحماية خصوصيتك تماماً. بياناتك في أمان ولغرض الخدمة فقط.' },
  cookies: { title: 'الكوكيز', content: 'نستخدم الكوكيز لتحسين تجربة تصفحك وحفظ سلة مشترياتك.' }
};

// --- حالة التطبيق (State) ---
let state: any = {
  step: 'catalog', // catalog | details | invoice
  cart: [],
  activeTrack: 'علمي',
  userDetails: { fullName: '', phone: '', altPhone: '', address: '' },
  isScanning: false
};

// --- محرك الرندرة (Rendering Engine) ---
const render = () => {
  const root = document.getElementById('root');
  if (!root) return;

  root.innerHTML = `
    ${renderHeader()}
    <main class="flex-grow pt-32 pb-24 px-6 md:px-16 max-w-[1600px] mx-auto w-full">
      ${state.step === 'catalog' ? renderCatalog() : state.step === 'details' ? renderDetails() : renderInvoice()}
    </main>
    ${renderFooter()}
    <div id="modal-container"></div>
    <div id="toast-container"></div>
  `;

  attachEvents();
  if (state.step === 'catalog') init3DEffects();
};

const renderHeader = () => {
  const total = state.cart.reduce((acc: any, i: any) => acc + (i.price * i.quantity), 0);
  return `
    <header class="fixed top-0 z-[100] w-full glass-nav py-4 px-6 md:px-16 no-print">
      <div class="max-w-[1600px] mx-auto flex justify-end items-center gap-8">
        <div class="flex items-center gap-8">
          <div class="hidden lg:flex items-center bg-gray-200/50 p-1 rounded-2xl border border-black/5">
            <button onclick="switchTrack('علمي')" class="px-8 py-2.5 rounded-xl text-xs font-black transition-all ${state.activeTrack === 'علمي' ? 'bg-black text-yellow-400 shadow-xl' : 'text-gray-500'}">مسار علمي</button>
            <button onclick="switchTrack('أدبي')" class="px-8 py-2.5 rounded-xl text-xs font-black transition-all ${state.activeTrack === 'أدبي' ? 'bg-black text-yellow-400 shadow-xl' : 'text-gray-500'}">مسار أدبي</button>
          </div>
          <button onclick="goToDetails()" class="relative bg-black text-yellow-400 px-6 py-3 rounded-2xl text-xs font-black flex items-center gap-3 transition-all ${state.cart.length === 0 ? 'opacity-30 grayscale cursor-not-allowed' : 'hover:scale-105'}">
            <span>🛒</span> <span>${total} ج</span>
            ${state.cart.length > 0 ? `<span class="absolute -top-2 -right-2 w-6 h-6 bg-yellow-400 text-black rounded-full flex items-center justify-center text-[10px] border-2 border-black animate-pulse">${state.cart.length}</span>` : ''}
          </button>
        </div>
      </div>
    </header>
  `;
};

const renderCatalog = () => {
  const filtered = BOOKS.filter(b => b.track === state.activeTrack || b.track === 'مشترك');
  return `
    <div class="space-y-20 fade-in">
      <section class="bg-white rounded-[3rem] p-12 md:p-20 border border-black/5 shadow-2xl relative overflow-hidden flex flex-col lg:flex-row items-center gap-16">
        <div class="relative z-10 flex-1 space-y-10 text-center lg:text-right">
          <div class="inline-flex items-center gap-3 bg-black text-yellow-400 px-6 py-2 rounded-full text-[10px] font-black uppercase">متاح الآن للطلب</div>
          <h2 class="text-5xl md:text-7xl font-black text-black leading-[1.1]">سهولة الوصول <br/> <span class="text-gray-400">لأفضل المريحات.</span></h2>
          <p class="text-gray-500 text-lg font-medium max-w-xl mx-auto lg:mx-0">سلسلة مريحات الشهادة السودانية الأصلية بين يديك. توصيل مجاني وسريع.</p>
          <div class="flex flex-wrap justify-center lg:justify-start gap-6">
            <label class="bg-black hover:bg-neutral-800 text-yellow-400 px-10 py-5 rounded-[2rem] font-black text-sm flex items-center gap-4 cursor-pointer shadow-2xl transition-all">
              📸 صور الغلاف واطلب فوراً
              <input type="file" onchange="handleScan(this)" class="hidden" />
            </label>
          </div>
        </div>
        <div class="relative hidden xl:block flex-shrink-0 perspective-1200" id="hero-trigger">
          <div id="hero-card" class="hero-card-3d w-[380px] h-[520px] bg-yellow-400 rounded-[4rem] shadow-2xl flex items-center justify-center p-12 border-[6px] border-white relative cursor-grab">
            <div class="absolute inset-0 bg-gradient-to-br from-white/30 to-transparent rounded-[3.8rem] pointer-events-none"></div>
            <div class="flex flex-col items-center gap-8" style="transform: translateZ(60px)">
               <div class="bg-black/10 p-10 rounded-[3rem] backdrop-blur-md">📚</div>
               <div class="text-center"><p class="font-black text-black text-3xl italic">المريح</p><p class="text-[10px] font-black text-black/40 tracking-[0.4em]">Sudanese Certificate</p></div>
            </div>
          </div>
        </div>
      </section>

      <div class="space-y-12">
        <h3 class="text-3xl font-black">قائمة الكتب (${state.activeTrack})</h3>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
          ${filtered.map(book => {
            const item = (state.cart as any[]).find((c: any) => c.id === book.id);
            return `
              <div class="group bg-white rounded-[2.5rem] p-6 border border-black/5 shadow-sm transition-all flex flex-col h-full book-container book-3d-card">
                <div class="relative aspect-[3.5/4.5] rounded-[2rem] overflow-hidden mb-6 bg-gray-50 border border-black/5">
                  <img src="${book.image}" class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700" />
                  <div class="absolute top-4 left-4 bg-black text-yellow-400 px-4 py-2 rounded-2xl text-xs font-black shadow-2xl">${book.price} ج</div>
                </div>
                <div class="px-2 flex-grow">
                  <h4 class="text-xl font-black text-black mb-2">${book.title}</h4>
                  <p class="text-xs text-gray-400 font-bold">${book.description}</p>
                </div>
                <div class="mt-8">
                  ${item ? `
                    <div class="flex items-center bg-gray-100 rounded-2xl p-1.5 gap-2">
                      <button onclick="updateQty('${book.id}', -1)" class="w-12 h-12 flex items-center justify-center hover:bg-white rounded-xl transition-all">-</button>
                      <span class="flex-grow text-center text-lg font-black">${item.quantity}</span>
                      <button onclick="updateQty('${book.id}', 1)" class="w-12 h-12 flex items-center justify-center hover:bg-white rounded-xl transition-all">+</button>
                    </div>
                  ` : `
                    <button onclick="addToCart('${book.id}')" class="w-full bg-black text-yellow-400 py-4.5 rounded-[1.5rem] text-xs font-black hover:bg-yellow-400 hover:text-black transition-all shadow-xl">إضافة للسلة</button>
                  `}
                </div>
              </div>
            `;
          }).join('')}
        </div>
      </div>
    </div>
  `;
};

const renderDetails = () => {
  const total = state.cart.reduce((acc: any, i: any) => acc + (i.price * i.quantity), 0);
  return `
    <div class="flex flex-col xl:grid xl:grid-cols-12 gap-16 fade-in">
      <div class="xl:col-span-7 bg-white rounded-[3rem] p-12 md:p-16 shadow-2xl border border-black/5 space-y-12">
        <h3 class="text-3xl font-black">إكمال البيانات</h3>
        <div class="grid gap-10">
          <input type="text" id="in-name" oninput="updateUser('fullName', this.value)" value="${state.userDetails.fullName}" placeholder="الاسم بالكامل" class="w-full px-8 py-5 rounded-3xl outline-none text-lg font-bold shadow-sm focus:ring-4 focus:ring-yellow-400/20 transition-all"/>
          <div class="grid md:grid-cols-2 gap-10">
            <div class="relative">
              <input type="tel" id="in-phone" oninput="updateUser('phone', this.value)" value="${state.userDetails.phone}" placeholder="01xxxxxxxxx" class="w-full px-8 py-5 pl-20 rounded-3xl outline-none text-lg font-bold ltr shadow-sm" dir="ltr"/>
              <span class="absolute left-6 top-1/2 -translate-y-1/2 text-gray-400 font-black text-sm">+20</span>
            </div>
            <input type="tel" id="in-alt" oninput="updateUser('altPhone', this.value)" value="${state.userDetails.altPhone}" placeholder="رقم إضافي" class="w-full px-8 py-5 rounded-3xl outline-none text-lg font-bold ltr shadow-sm" dir="ltr"/>
          </div>
          <textarea id="in-address" oninput="updateUser('address', this.value)" placeholder="العنوان بالتفصيل" class="w-full px-8 py-5 rounded-3xl outline-none text-lg font-bold shadow-sm h-32">${state.userDetails.address}</textarea>
        </div>
      </div>
      <div class="xl:col-span-5 flex flex-col gap-10">
        <div class="bg-black text-white rounded-[3rem] p-12 shadow-2xl flex flex-col h-full">
          <h4 class="text-xl font-black mb-10 pb-6 border-b border-white/10 uppercase tracking-widest text-gray-400">ملخص الطلبية</h4>
          <div class="space-y-6 flex-grow custom-scrollbar overflow-y-auto max-h-[400px]">
            ${state.cart.map((item: any) => `
              <div class="flex justify-between items-center">
                <div><p class="font-black text-lg">${item.title}</p><p class="text-[10px] text-gray-500">${item.quantity} نسخة</p></div>
                <span class="font-black text-xl">${item.price * item.quantity} ج</span>
              </div>
            `).join('')}
          </div>
          <div class="mt-12 pt-10 border-t border-white/10 space-y-5">
            <div class="flex justify-between text-2xl font-black text-yellow-400"><span>الإجمالي (توصيل مجاني)</span><span>${total} ج</span></div>
          </div>
          <div class="grid grid-cols-2 gap-6 mt-12">
            <button onclick="setStep('catalog')" class="py-5 rounded-2xl bg-white/5 text-xs font-black text-gray-400">العودة</button>
            <button id="submit-btn" onclick="submitOrder()" class="py-5 rounded-2xl bg-yellow-400 text-black text-xs font-black shadow-2xl hover:bg-yellow-300">إتمام الطلب</button>
          </div>
        </div>
      </div>
    </div>
  `;
};

const renderInvoice = () => {
  const total = state.cart.reduce((acc: any, i: any) => acc + (i.price * i.quantity), 0);
  const invNum = Math.floor(100000 + Math.random() * 900000);
  return `
    <div class="max-w-2xl mx-auto space-y-10 pb-24 fade-in">
      <div class="bg-yellow-400 text-black p-8 rounded-[2.5rem] text-center shadow-2xl no-print">
        <div class="w-16 h-16 bg-black text-yellow-400 rounded-full flex items-center justify-center mx-auto mb-6 text-2xl">✅</div>
        <h2 class="text-2xl font-black mb-2">تم تأكيد طلبك بنجاح!</h2>
        <p class="text-md font-bold opacity-80">سيتواصل معك فريقنا قريباً للتوصيل.</p>
      </div>

      <div class="bg-white text-black p-12 rounded-[2.5rem] shadow-2xl border-t-[10px] border-black relative">
        <div class="flex justify-between items-start mb-12">
          <div><h1 class="text-2xl font-black">المريح</h1><p class="text-[8px] text-gray-400 tracking-[0.4em]">Official Receipt</p></div>
          <div class="text-left font-black text-lg">#${invNum}</div>
        </div>

        <div class="grid md:grid-cols-2 gap-8 mb-12 border-b border-gray-100 pb-8">
          <div><p class="text-[8px] font-black text-gray-400 mb-2">المستلم</p><p class="font-black text-xl">${state.userDetails.fullName}</p><p class="text-md font-bold text-gray-500">${state.userDetails.phone}</p></div>
          <div class="md:text-left"><p class="text-[8px] font-black text-gray-400 mb-2">معلومات</p><p class="text-sm font-bold">${new Date().toLocaleDateString('ar-EG')}</p><p class="text-sm font-black text-green-600">التوصيل مجاني</p></div>
        </div>

        <table class="w-full mb-8">
          <thead class="border-b border-black text-[8px] text-gray-400"><tr><th class="text-right pb-4">الكتاب</th><th class="text-center pb-4">الكمية</th><th class="text-left pb-4">الإجمالي</th></tr></thead>
          <tbody>
            ${state.cart.map((i: any) => `<tr><td class="py-4 font-black">${i.title}</td><td class="py-4 text-center">x${i.quantity}</td><td class="py-4 text-left font-black">${i.price * i.quantity} ج</td></tr>`).join('')}
          </tbody>
        </table>

        <div class="pt-6 border-t-2 border-black border-dashed flex justify-between text-2xl font-black">
          <span>الإجمالي النهائي</span><span>${total} ج</span>
        </div>
      </div>

      <button onclick="resetApp()" class="w-full bg-black text-yellow-400 py-5 rounded-2xl font-black text-sm hover:scale-105 active:scale-95 shadow-xl transition-all">طلب جديد ➜</button>
    </div>
  `;
};

const renderFooter = () => `
  <footer class="bg-white py-16 px-16 no-print border-t border-black/5 mt-auto">
    <div class="max-w-[1600px] mx-auto flex flex-col md:flex-row justify-between items-center gap-12">
      <div class="flex items-center gap-4"><div class="bg-black p-2 rounded-xl text-yellow-400">📚</div><h1 class="text-xl font-black">المريح</h1></div>
      <div class="flex flex-wrap justify-center gap-12 text-[10px] font-black text-gray-400 uppercase tracking-[0.3em]">
        <button onclick="showLegal('about')">من نحن</button>
        <button onclick="showLegal('terms')">الشروط والأحكام</button>
        <button onclick="showLegal('privacy')">سياسة الخصوصية</button>
        <button onclick="showLegal('cookies')">الكوكيز</button>
      </div>
      <p class="text-[10px] text-gray-300 font-black">© ${new Date().getFullYear()} المريح SUDANESE CERTIFICATE</p>
    </div>
  </footer>
`;

// --- الوظائف الأساسية (Functions) ---
// Fix: Defining local functions to resolve "Cannot find name" errors and casting window to any for property access
const addToCart = (id: string) => {
  const book = BOOKS.find(b => b.id === id);
  const exists = (state.cart as any[]).find((i: any) => i.id === id);
  if (exists) {
    exists.quantity++;
  } else if (book) {
    (state.cart as any[]).push({ ...book, quantity: 1 });
  }
  render();
};
(window as any).addToCart = addToCart;

const updateQty = (id: string, delta: number) => {
  const item = (state.cart as any[]).find((i: any) => i.id === id);
  if (item) {
    item.quantity += delta;
    if (item.quantity <= 0) state.cart = (state.cart as any[]).filter((i: any) => i.id !== id);
  }
  render();
};
(window as any).updateQty = updateQty;

const switchTrack = (track: string) => {
  state.activeTrack = track;
  render();
};
(window as any).switchTrack = switchTrack;

const setStep = (step: string) => {
  state.step = step;
  render();
};
(window as any).setStep = setStep;

const goToDetails = () => {
  if (state.cart.length > 0) setStep('details');
};
(window as any).goToDetails = goToDetails;

const updateUser = (key: string, val: string) => {
  (state.userDetails as any)[key] = val;
};
(window as any).updateUser = updateUser;

const submitOrder = () => {
  if (state.userDetails.fullName && state.userDetails.phone && state.userDetails.address) {
    setStep('invoice');
  } else {
    alert('يرجى ملء جميع البيانات الأساسية');
  }
};
(window as any).submitOrder = submitOrder;

const resetApp = () => {
  state.cart = [];
  state.userDetails = { fullName: '', phone: '', altPhone: '', address: '' };
  setStep('catalog');
};
(window as any).resetApp = resetApp;

const showLegal = (key: string) => {
  const page = (LEGAL as any)[key];
  const container = document.getElementById('modal-container');
  if (container) {
    container.innerHTML = `
      <div class="fixed inset-0 z-[200] bg-black/80 backdrop-blur-md flex items-center justify-center p-6">
        <div class="bg-white w-full max-w-2xl rounded-[3rem] p-12 shadow-2xl border border-black/10 fade-in">
          <h3 class="text-3xl font-black mb-12">${page.title}</h3>
          <p class="text-gray-600 text-lg leading-relaxed font-bold mb-12">${page.content}</p>
          <button onclick="this.closest('.fixed').remove()" class="w-full bg-black text-yellow-400 py-5 rounded-2xl font-black text-sm">إغلاق</button>
        </div>
      </div>
    `;
  }
};
(window as any).showLegal = showLegal;

// --- ميزة التعرف على الصور (AI Recognition) ---
// Fix: Defining handleScan as local constant and casting reader.result to string to allow split()
const handleScan = async (input: HTMLInputElement) => {
  const file = input.files?.[0];
  if (!file) return;

  const toast = document.getElementById('toast-container');
  if (toast) {
    toast.innerHTML = `<div class="fixed bottom-12 right-12 z-[200] bg-white border-2 border-black p-6 rounded-2xl font-black animate-bounce shadow-2xl">جاري التعرف على الكتاب... 🤖</div>`;
  }

  const reader = new FileReader();
  reader.onloadend = async () => {
    const result = reader.result as string;
    const base64 = result.split(',')[1];
    const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
    const prompt = `Identify the subject of this Sudanese Secondary Certificate book. Return JSON { "subject": "name" }. Names in Arabic: كيمياء، فيزياء، أحياء، هندسية، علوم حاسوب، جغرافيا، تاريخ، رياضيات متخصصة، رياضيات "1".`;
    
    try {
      const response = await ai.models.generateContent({
        model: "gemini-3-flash-preview",
        contents: { parts: [{ text: prompt }, { inlineData: { mimeType: "image/jpeg", data: base64 } }] },
        config: { responseMimeType: "application/json" }
      });
      const res = JSON.parse(response.text || '{}');
      const book = BOOKS.find(b => res.subject && (res.subject.includes(b.title) || b.title.includes(res.subject)));
      if (book) {
        addToCart(book.id);
        if (toast) toast.innerHTML = `<div class="fixed bottom-12 right-12 z-[200] bg-yellow-400 border-2 border-black p-6 rounded-2xl font-black shadow-2xl fade-in">تمت إضافة ${book.title} بنجاح! ✅</div>`;
      } else {
        if (toast) toast.innerHTML = `<div class="fixed bottom-12 right-12 z-[200] bg-red-100 border-2 border-red-500 p-6 rounded-2xl font-black shadow-2xl">لم يتم العثور على الكتاب ❌</div>`;
      }
    } catch (e) {
      if (toast) toast.innerHTML = `<div class="fixed bottom-12 right-12 z-[200] bg-red-100 border-2 border-red-500 p-6 rounded-2xl font-black shadow-2xl">خطأ في الاتصال ⚠️</div>`;
    }
    setTimeout(() => { if (toast) toast.innerHTML = ''; }, 3000);
  };
  reader.readAsDataURL(file);
};
(window as any).handleScan = handleScan;

// --- تأثيرات الـ 3D التفاعلية ---
const init3DEffects = () => {
  const heroCard = document.getElementById('hero-card');
  const heroTrigger = document.getElementById('hero-trigger');

  if (heroCard && heroTrigger) {
    heroTrigger.addEventListener('mousemove', (e: MouseEvent) => {
      const rect = heroTrigger.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      const centerX = rect.width / 2;
      const centerY = rect.height / 2;
      const rotX = (y - centerY) / 10;
      const rotY = (centerX - x) / 10;
      heroCard.style.transform = `rotateX(${rotX}deg) rotateY(${rotY}deg) scale(1.05)`;
    });

    heroTrigger.addEventListener('mouseleave', () => {
      heroCard.style.transform = `rotateX(0deg) rotateY(0deg) scale(1)`;
    });
  }
};

const attachEvents = () => {
  // يمكن إضافة مستمعي أحداث إضافية هنا إذا لزم الأمر
};

// بدء التشغيل
render();
