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()}
${state.step === 'catalog' ? renderCatalog() : state.step === 'details' ? renderDetails() : renderInvoice()}
${renderFooter()}
`;
attachEvents();
if (state.step === 'catalog') init3DEffects();
};
const renderHeader = () => {
const total = state.cart.reduce((acc: any, i: any) => acc + (i.price * i.quantity), 0);
return `
`;
};
const renderCatalog = () => {
const filtered = BOOKS.filter(b => b.track === state.activeTrack || b.track === 'مشترك');
return `
متاح الآن للطلب
سهولة الوصول
لأفضل المريحات.
سلسلة مريحات الشهادة السودانية الأصلية بين يديك. توصيل مجاني وسريع.
📚
المريح
Sudanese Certificate
قائمة الكتب (${state.activeTrack})
${filtered.map(book => {
const item = (state.cart as any[]).find((c: any) => c.id === book.id);
return `
${book.price} ج
${book.title}
${book.description}
${item ? `
${item.quantity}
` : `
`}
`;
}).join('')}
`;
};
const renderDetails = () => {
const total = state.cart.reduce((acc: any, i: any) => acc + (i.price * i.quantity), 0);
return `
ملخص الطلبية
الإجمالي (توصيل مجاني)${total} ج
`;
};
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 `
✅
تم تأكيد طلبك بنجاح!
سيتواصل معك فريقنا قريباً للتوصيل.
المستلم
${state.userDetails.fullName}
${state.userDetails.phone}
معلومات
${new Date().toLocaleDateString('ar-EG')}
التوصيل مجاني
| الكتاب | الكمية | الإجمالي |
${state.cart.map((i: any) => `| ${i.title} | x${i.quantity} | ${i.price * i.quantity} ج |
`).join('')}
الإجمالي النهائي${total} ج
`;
};
const renderFooter = () => `
`;
// --- الوظائف الأساسية (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 = `
${page.title}
${page.content}
`;
}
};
(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 = `جاري التعرف على الكتاب... 🤖
`;
}
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 = `تمت إضافة ${book.title} بنجاح! ✅
`;
} else {
if (toast) toast.innerHTML = `لم يتم العثور على الكتاب ❌
`;
}
} catch (e) {
if (toast) toast.innerHTML = `خطأ في الاتصال ⚠️
`;
}
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();