// App.jsx - Main Application Component
const { useState, useEffect } = React;

function App() {
    const hasAdminSession = sessionStorage.getItem('arpitaAdminAuthenticated') === 'true';
    const [currentPage, setCurrentPage] = useState(hasAdminSession ? 'admin-dashboard' : 'home');
    const [isAdmin, setIsAdmin] = useState(hasAdminSession);
    const [enrollmentForm, setEnrollmentForm] = useState(null);
    const [enrollments, setEnrollments] = useState([]);

    // Student names and artwork titles
    const studentNames = [
        "Priya Mehta", "Alex Kim", "Sarah Thompson", "Raj Patel", "Emma Wilson", "David Chen",
        "Anjali Sharma", "Marco Rossi", "Yuki Tanaka", "Sofia Garcia", "James O'Brien", "Nina Kowalski",
        "Arjun Nair", "Lisa Anderson", "Chen Wei", "Aisha Mohammed", "Lucas Schmidt", "Maya Patel",
        "Isabella Cruz", "Omar Hassan", "Elena Popov", "William Lee", "Fatima Al-Rashid", "Diego Martinez",
        "Hannah Mueller", "Karthik Rajan", "Olivia Santos", "Michael Foster", "Zara Begum", "Takeshi Mori"
    ];

    const artworkTitles = [
        "Botanical Study", "Portrait in Charcoal", "Mountain Sunset", "Floral Sketch",
        "Nature's Details", "Abstract Composition", "Still Life with Fruit", "Portrait Sketch",
        "Botanical Illustration", "Expression Study", "City Landscape", "Portrait Drawing",
        "Geometric Forms", "Watercolor Garden", "Classical Portrait", "Ink Landscape",
        "Mixed Media Art", "Sketching Nature", "Dramatic Lighting", "Delicate Petals",
        "Portrait Mastery", "Forest Scene", "Figure Study", "Architectural Sketch",
        "Ocean View", "Mountain Peaks", "Urban Life", "Traditional Art", "Modern Touch",
        "Creative Expression", "Artistic Vision", "Masterful Strokes", "Hidden Details"
    ];

    const courseCategories = ["Portrait", "Landscape", "Botanical", "Sketching", "Composition", "Still Life"];
    const classTypes = ["Portrait Drawing", "Botanical Illustration", "Watercolor Landscapes",
                       "Charcoal Sketching", "Advanced Composition", "Still Life Fundamentals"];

    // Sample data for the application
    const [isClassWorkLoading, setIsClassWorkLoading] = useState(true);
    const [hasClassWorkFailed, setHasClassWorkFailed] = useState(false);
    const [upcomingClasses, setUpcomingClasses] = useState([
        { id: 1, title: "Botanical Illustration Workshop", date: "2026-07-25", time: "10:00 AM IST", type: "group", image: null, placeholder: "Botanical workshop class" },
        { id: 2, title: "Portrait Drawing Masterclass", date: "2026-07-28", time: "2:00 PM IST", type: "masterclass", image: null, placeholder: "Portrait drawing masterclass" },
        { id: 3, title: "Watercolor Basics", date: "2026-08-02", time: "11:00 AM IST", type: "group", image: null, placeholder: "Watercolor basics class" },
        { id: 4, title: "Charcoal & Sketching Intensive", date: "2026-08-05", time: "3:00 PM IST", type: "individual", image: null, placeholder: "Charcoal sketching class" },
        { id: 5, title: "Nature & Outdoor Sketching", date: "2026-08-08", time: "9:00 AM IST", type: "group", image: null, placeholder: "Outdoor sketching class" },
        { id: 6, title: "Special Offer: First Class Free!", date: "Limited Time", time: "New Students", type: "offer", image: null, placeholder: "Free trial class offer" }
    ]);

    const [courses, setCourses] = useState([
        { id: 1, title: "Complete Portrait Drawing", duration: "12 hours", level: "Intermediate", price: 99, image: null, placeholder: "Complete portrait drawing course", category: "Portrait", bestseller: true },
        { id: 2, title: "Watercolor Landscapes", duration: "8 hours", level: "Beginner", price: 69, image: null, placeholder: "Watercolor landscapes course", category: "Landscape" },
        { id: 3, title: "Botanical Art Essentials", duration: "10 hours", level: "All Levels", price: 79, image: null, placeholder: "Botanical art essentials course", category: "Botanical", bestseller: true },
        { id: 4, title: "Charcoal Sketching Fundamentals", duration: "6 hours", level: "Beginner", price: 49, image: null, placeholder: "Charcoal sketching course", category: "Sketching" },
        { id: 5, title: "Advanced Composition Mastery", duration: "15 hours", level: "Advanced", price: 129, image: null, placeholder: "Advanced composition course", category: "Composition" },
        { id: 6, title: "Still Life Fundamentals", duration: "8 hours", level: "Beginner", price: 59, image: null, placeholder: "Still life fundamentals course", category: "Still Life" },
        { id: 7, title: "Portrait Expression & Emotion", duration: "10 hours", level: "Intermediate", price: 89, image: null, placeholder: "Portrait expression course", category: "Portrait", bestseller: true },
        { id: 8, title: "Pen & Ink Techniques", duration: "7 hours", level: "Beginner", price: 59, image: null, placeholder: "Pen and ink techniques course", category: "Sketching" },
        { id: 9, title: "Nature & Botanical Drawing", duration: "12 hours", level: "Intermediate", price: 99, image: null, placeholder: "Nature and botanical drawing course", category: "Botanical" }
    ]);

    const buildGalleryItems = (images) => images.map((img, index) => ({
        id: index + 1,
        title: artworkTitles[index % artworkTitles.length],
        student: studentNames[index % studentNames.length],
        class: classTypes[index % classTypes.length],
        image: img,
        category: courseCategories[index % courseCategories.length]
    }));

    const [galleryItems, setGalleryItems] = useState([]);

    useEffect(() => {
        let cancelled = false;

        const loadClassWorks = async () => {
            setIsClassWorkLoading(true);
            setHasClassWorkFailed(false);

            if (typeof window.loadSupabaseClassWorkImages !== 'function') {
                if (!cancelled) {
                    setIsClassWorkLoading(false);
                    setHasClassWorkFailed(true);
                }
                return;
            }

            try {
                const storedImages = await window.loadSupabaseClassWorkImages();
                if (cancelled) return;

                if (storedImages.length === 0) {
                    setIsClassWorkLoading(false);
                    setHasClassWorkFailed(true);
                    return;
                }

                const imageUrls = storedImages.map(image => image.url);
                setGalleryItems(buildGalleryItems(imageUrls));
                setUpcomingClasses(previous => previous.map((item, index) => (
                    item.type === 'offer'
                        ? item
                        : { ...item, image: imageUrls[(index + 60) % imageUrls.length] }
                )));
                setCourses(previous => previous.map((course, index) => ({
                    ...course,
                    image: imageUrls[(index + 9) % imageUrls.length]
                })));
                setIsClassWorkLoading(false);
            } catch (error) {
                console.error('Unable to load class-work images from Supabase.', error);
                if (!cancelled) {
                    setIsClassWorkLoading(false);
                    setHasClassWorkFailed(true);
                }
            }
        };

        loadClassWorks();
        return () => {
            cancelled = true;
        };
    }, []);

    const [testimonials, setTestimonials] = useState([
        { id: 1, name: "Priya Mehta", location: "Mumbai, India", text: "Arpita's teaching transformed my artistic journey. Her patient guidance helped me master techniques I thought were impossible.", image: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=150" },
        { id: 2, name: "Alex Kim", location: "Seoul, South Korea", text: "The live classes feel incredibly personal despite being online. It's like having Arpita right beside me, guiding every stroke.", image: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150" },
        { id: 3, name: "Sarah Thompson", location: "London, UK", text: "I've taken art classes worldwide, and Arpita's academy stands out. The structured approach and supportive community are exceptional.", image: "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=150" }
    ]);

    const handleNavigate = (page) => {
        setCurrentPage(page);
        window.scrollTo(0, 0);
    };

    const handleAdminLogin = (success) => {
        if (success) {
            sessionStorage.setItem('arpitaAdminAuthenticated', 'true');
            setIsAdmin(true);
            setCurrentPage('admin-dashboard');

            // Request notification permission when admin logs in
            if ('Notification' in window && Notification.permission === 'default') {
                Notification.requestPermission().then(permission => {
                    if (permission === 'granted') {
                        console.log('Notification permission granted');
                    }
                });
            }
        }
    };

    const handleAdminLogout = () => {
        sessionStorage.removeItem('arpitaAdminAuthenticated');
        setIsAdmin(false);
        setCurrentPage('home');
    };

    const handleEnroll = (classItem) => {
        setEnrollmentForm(classItem);
    };

    const handleEnrollmentSubmit = async (enrollmentData) => {
        const newEnrollment = {
            ...enrollmentData,
            id: Date.now(),
            read: false,
            timestamp: new Date().toISOString()
        };
        setEnrollments(prev => [...prev, newEnrollment]);

        // Show browser notification
        if ('Notification' in window && Notification.permission === 'granted') {
            new Notification('🎨 New Enrollment!', {
                body: `${enrollmentData.name} enrolled in ${enrollmentData.classItem?.title || 'General Enrollment'}`,
                icon: 'https://qzezgagdxaootepuykdl.supabase.co/storage/v1/object/public/favicon.png',
                badge: 'https://qzezgagdxaootepuykdl.supabase.co/storage/v1/object/public/favicon.png',
                tag: 'new-enrollment'
            });
        } else if ('Notification' in window && Notification.permission !== 'denied') {
            Notification.requestPermission();
        }

        // Send email notification
        try {
            if (window.NotificationManager && window.NotificationManager.sendEmailNotification) {
                await window.NotificationManager.sendEmailNotification(enrollmentData, 'bappa4uall@gmail.com');
            }
        } catch (emailError) {
            console.error('Email notification failed:', emailError);
        }

        // Send SMS notification (configure your Twilio credentials)
        try {
            if (window.NotificationManager && window.NotificationManager.sendSMSNotification) {
                await window.NotificationManager.sendSMSNotification(enrollmentData, '+919876543210');
            }
        } catch (smsError) {
            console.error('SMS notification failed:', smsError);
        }

        // Send WhatsApp notification
        try {
            if (window.NotificationManager && window.NotificationManager.sendWhatsAppNotification) {
                await window.NotificationManager.sendWhatsAppNotification(enrollmentData, '+919876543210');
            }
        } catch (waError) {
            console.error('WhatsApp notification failed:', waError);
        }

        console.log('All notifications sent:', newEnrollment);
    };

    const handleMarkEnrollmentRead = (enrollmentId) => {
        setEnrollments(prev => prev.map(e =>
            e.id === enrollmentId ? { ...e, read: true } : e
        ));
    };

    const handleClearEnrollments = () => {
        setEnrollments([]);
    };

    const handleCloseEnrollmentForm = () => {
        setEnrollmentForm(null);
    };

    // Render current page
    const renderPage = () => {
        if (currentPage === 'admin') {
            return <AdminAuth onLogin={handleAdminLogin} />;
        }

        if (currentPage === 'admin-dashboard' && isAdmin) {
            return (
                <AdminDashboard
                    upcomingClasses={upcomingClasses}
                    setUpcomingClasses={setUpcomingClasses}
                    courses={courses}
                    setCourses={setCourses}
                    galleryItems={galleryItems}
                    setGalleryItems={setGalleryItems}
                    testimonials={testimonials}
                    setTestimonials={setTestimonials}
                />
            );
        }

        return (
            <div>
                <Hero onNavigate={handleNavigate} onEnroll={handleEnroll} />
                <UpcomingClasses classes={upcomingClasses} onEnroll={handleEnroll} />
                <LiveClasses onEnroll={handleEnroll} />
                <Courses courses={courses} onEnroll={handleEnroll} />
                <FeaturedWorks items={galleryItems} isLoading={isClassWorkLoading} hasFailed={hasClassWorkFailed} />
                <Gallery items={galleryItems} isLoading={isClassWorkLoading} hasFailed={hasClassWorkFailed} />
                <Testimonials testimonials={testimonials} />
                <About />

                {/* Enrollment Form Modal */}
                {enrollmentForm && (
                    <EnrollmentForm
                        classItem={enrollmentForm}
                        onClose={handleCloseEnrollmentForm}
                        onSubmit={handleEnrollmentSubmit}
                    />
                )}
            </div>
        );
    };

    return (
        <div className="min-h-screen bg-cream">
            <Navbar
                currentPage={currentPage}
                onNavigate={handleNavigate}
                isAdmin={isAdmin}
                onLogout={handleAdminLogout}
                enrollments={enrollments}
                onMarkEnrollmentRead={handleMarkEnrollmentRead}
                onClearEnrollments={handleClearEnrollments}
            />
            {renderPage()}
            <Footer />
        </div>
    );
}

// Make App available globally
window.App = App;
