    /**
     * @file App.jsx
     * @description Główny plik aplikacji MAKE3D. Zawiera pełny system e-commerce: 
     * katalog, koszyk, zamówienia, profile użytkowników oraz potężny panel administracyjny.
     * Wersja zoptymalizowana pod urządzenia mobilne (RWD).
     */


    const { useState, useEffect, useMemo, useCallback, useRef, Fragment } = React;
    const sb = window.supabaseClient;

    // ============================================================================
    // 1. KONFIGURACJA I STAŁE SYSTEMOWE
    // ============================================================================
    const ADMIN_EMAIL = 'make3d.kontakt@gmail.com';
    const BLIK_NUMBER = '502 152 556';
    const DELIVERY_FEE = 16.00;
    const FREE_DELIVERY_THRESHOLD = 60.00; // Darmowa dostawa powyżej tej kwoty

    // ============================================================================
    // 2. SYSTEM STYLÓW (UI KIT)
    // ============================================================================
    const Theme = {
        bg: "bg-[#F8F9FA]",
        text: "text-slate-900",
        card: "bg-white border border-gray-100/80 rounded-[2rem] md:rounded-[3.5rem] shadow-[0_8px_30px_rgb(0,0,0,0.04)] overflow-hidden transition-all duration-500",
        input: "w-full bg-gray-50/80 border-2 border-gray-100/50 focus:border-purple-300 focus:bg-white p-4 md:p-5 rounded-2xl font-bold text-sm outline-none transition-all duration-300",
        select: "w-full bg-gray-50/80 border-2 border-gray-100/50 focus:border-purple-300 focus:bg-white p-4 md:p-5 rounded-2xl font-bold text-sm outline-none transition-all duration-300 appearance-none",
        btnPrimary: "bg-slate-900 text-white hover:bg-purple-600 px-6 md:px-8 py-4 rounded-2xl font-black uppercase text-[10px] tracking-[0.2em] transition-all duration-300 active:scale-95 disabled:opacity-30 disabled:hover:bg-slate-900 disabled:cursor-not-allowed shadow-xl shadow-black/10 hover:shadow-purple-500/20",
        btnGhost: "bg-transparent border-2 border-gray-200 text-gray-500 hover:border-slate-900 hover:text-slate-900 px-6 md:px-8 py-4 rounded-2xl font-black uppercase text-[10px] tracking-[0.2em] transition-all duration-300 active:scale-95 disabled:opacity-30",
        btnDanger: "bg-rose-50 text-rose-500 hover:bg-rose-500 hover:text-white px-6 md:px-8 py-4 rounded-2xl font-black uppercase text-[10px] tracking-[0.2em] transition-all duration-300 active:scale-95",
        badge: (type) => {
            const s = {
                purple: "bg-purple-600 text-white shadow-lg shadow-purple-200/50 border border-purple-500",
                green: "bg-emerald-500 text-white shadow-lg shadow-emerald-200/50 border border-emerald-400",
                rose: "bg-rose-500 text-white shadow-lg shadow-rose-200/50 border border-rose-400",
                dark: "bg-slate-900 text-white shadow-lg shadow-slate-200/50",
                outline: "border-2 border-gray-100 text-gray-500 bg-white"
            };
            return `px-3 md:px-4 py-1.5 rounded-full text-[8px] md:text-[9px] font-black uppercase tracking-widest ${s[type] || s.outline}`;
        }
    };

    // ============================================================================
    // 3. ZESTAW IKON SVG (Rozszerzony dla Mobile i Admina)
    // ============================================================================
    const Icons = {
        Menu: () => <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="4" x2="20" y1="12" y2="12"/><line x1="4" x2="20" y1="6" y2="6"/><line x1="4" x2="20" y1="18" y2="18"/></svg>,
        Search: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>,
        Cart: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="8" cy="21" r="1"/><circle cx="19" cy="21" r="1"/><path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"/></svg>,
        User: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
        Trash: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>,
        Edit: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>,
        Package: () => <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m7.5 4.27 9 5.15"/><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>,
        Check: () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>,
        X: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>,
        Star: ({ filled }) => <svg width="18" height="18" viewBox="0 0 24 24" fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>,
        LogOut: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>,
        Settings: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
        Clock: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>,
        Truck: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="3" width="15" height="13"/><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>,
    };

    // ============================================================================
    // 4. KOMPONENTY WSPÓŁDZIELONE (UI)
    // ============================================================================

    /**
     * Komponent Przełącznika (Toggle) z pełną dostępnością.
     */
    const ToggleSwitch = ({ checked, onChange, label }) => (
        <label className="flex items-center justify-between cursor-pointer p-4 bg-white border border-gray-100 rounded-2xl hover:border-purple-200 transition-all shadow-sm">
            <span className="text-[10px] font-black uppercase tracking-widest text-gray-600 select-none">{label}</span>
            <div className="relative">
                <input type="checkbox" className="sr-only" checked={checked} onChange={(e) => onChange(e.target.checked)} />
                <div className={`block w-12 h-7 rounded-full transition-colors duration-300 ${checked ? 'bg-purple-600' : 'bg-gray-200'}`}></div>
                <div className={`absolute left-1 top-1 bg-white w-5 h-5 rounded-full transition-transform duration-300 shadow-sm ${checked ? 'transform translate-x-5' : ''}`}></div>
            </div>
        </label>
    );

    /**
     * Komponent Pustego Stanu (Empty State) - responsywny.
     */
    const EmptyState = ({ icon, title, desc }) => (
        <div className="flex flex-col items-center justify-center py-20 md:py-32 px-6 text-center border-4 border-dashed border-gray-100/50 rounded-[2rem] md:rounded-[4rem] bg-white/50 backdrop-blur-sm">
            <div className="text-gray-300 mb-6 scale-125 md:scale-150">{icon}</div>
            <h3 className="text-xl md:text-2xl font-black text-gray-400 uppercase tracking-[0.2em] md:tracking-[0.3em] italic mb-3">{title}</h3>
            {desc && <p className="text-xs md:text-sm font-bold text-gray-400 max-w-md leading-relaxed">{desc}</p>}
        </div>
    );

    /**
     * Globalny Modal Systemowy
     */
    const CustomModal = ({ isOpen, title, content, onConfirm, onCancel, confirmText = "Tak", cancelText = "Anuluj", isDanger = false }) => {
        if (!isOpen) return null;
        return (
            <div className="fixed inset-0 z-[9999] flex items-center justify-center px-4 bg-slate-900/60 backdrop-blur-sm transition-opacity">
                <div className="bg-white rounded-[2rem] p-6 md:p-8 w-full max-w-md shadow-2xl animate-in zoom-in-95 duration-200">
                    <h3 className="text-xl font-black uppercase tracking-tighter mb-4 text-slate-900">{title}</h3>
                    <p className="text-sm font-bold text-gray-500 mb-8 leading-relaxed">{content}</p>
                    <div className="flex gap-4">
                        <button onClick={onCancel} className={`${Theme.btnGhost} flex-1 py-3`}>{cancelText}</button>
                        <button onClick={onConfirm} className={`${isDanger ? Theme.btnDanger : Theme.btnPrimary} flex-1 py-3`}>{confirmText}</button>
                    </div>
                </div>
            </div>
        );
    };





    // ============================================================================
    // 5. GŁÓWNY KONTROLER APLIKACJI (App)
    // ============================================================================
    function App() {
        // --- STANY RDZENIA ---
        const [view, setView] = useState('home'); // home, details, cart, orders, admin
        const [user, setUser] = useState(null);
        const [loading, setLoading] = useState(true);
        const [toast, setToast] = useState({ show: false, msg: '', type: 'success' });

        // --- STANY UI I MOBILNOŚCI ---
        const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
        const [modalConfig, setModalConfig] = useState({ isOpen: false });

        // --- DANE Z BAZY ---
        const [products, setProducts] = useState([]);
        const [categories, setCategories] = useState([]);
        const [orders, setOrders] = useState([]);
        const [reviews, setReviews] = useState([]);
        const [cart, setCart] = useState([]);
        const [activeOrderId, setActiveOrderId] = useState(null);

        // --- STANY SKLEPU ---
        const [activeCategory, setActiveCategory] = useState('Wszystkie');
        const [search, setSearch] = useState('');
        const [sortBy, setSortBy] = useState('newest'); // newest, price_asc, price_desc

        // --- STANY PRODUKTU ---
        const [selectedProduct, setSelectedProduct] = useState(null);
        const [selectedVariant, setSelectedVariant] = useState(null);
        const [quantity, setQuantity] = useState(1);

        // ==========================================
        // INICJALIZACJA I POBIERANIE DANYCH
        // ==========================================
        useEffect(() => {
            const init = async () => {
                const { data: { session } } = await sb.auth.getSession();
                setUser(session?.user ?? null);
                await refreshAllData();

                // Odzyskaj koszyk z localStorage
                const savedCart = localStorage.getItem('make3d_cart');
                if (savedCart) setCart(JSON.parse(savedCart));

                setLoading(false);
            };
            init();

            const { data: { subscription } } = sb.auth.onAuthStateChange((_e, s) => {
                setUser(s?.user ?? null);
                if (!s && view === 'admin') setView('home');
            });
            return () => subscription.unsubscribe();
        }, [view]);

        // Zapis koszyka
        useEffect(() => {
            if (!loading) localStorage.setItem('make3d_cart', JSON.stringify(cart));
        }, [cart, loading]);

        // Blokada scrolla gdy menu mobilne otwarte
        useEffect(() => {
            if (isMobileMenuOpen) document.body.style.overflow = 'hidden';
            else document.body.style.overflow = 'unset';
            return () => { document.body.style.overflow = 'unset'; }
        }, [isMobileMenuOpen]);

        const refreshAllData = async () => {
            const [pResp, cResp, oResp, rResp] = await Promise.all([
                sb.from('products').select('*, product_variants(*)').order('created_at', { ascending: false }),
                sb.from('categories').select('*').order('name'),
                sb.from('orders').select('*').order('created_at', { ascending: false }),
                sb.from('reviews').select('*').order('created_at', { ascending: false })
            ]);
            setProducts(pResp.data || []);
            setCategories(cResp.data || []);
            setOrders(oResp.data || []);
            setReviews(rResp.data || []);
        };

        // ==========================================
        // NARZĘDZIA POMOCNICZE
        // ==========================================
        const showToast = (msg, type = 'success') => {
            setToast({ show: true, msg, type });
            setTimeout(() => setToast({ show: false, msg: '', type: 'success' }), 4000);
        };

        const confirmAction = (title, content, onConfirm, isDanger = false) => {
            setModalConfig({
                isOpen: true, title, content, isDanger,
                onConfirm: () => { onConfirm(); setModalConfig({ isOpen: false }); },
                onCancel: () => setModalConfig({ isOpen: false })
            });
        };

        const navigateTo = (newView) => {
            setView(newView);
            setIsMobileMenuOpen(false);
            window.scrollTo({ top: 0, behavior: 'smooth' });
        };

        // ... tutaj kończy się funkcja navigateTo

        // Funkcja sukcesu płatności
        // Pomocnicza funkcja walidacji
        const validateAddress = () => {
            const fields = {
                name: document.getElementById('chk-name')?.value?.trim(),
                street: document.getElementById('chk-street')?.value?.trim(),
                zip: document.getElementById('chk-zip')?.value?.trim(),
                city: document.getElementById('chk-city')?.value?.trim(),
                phone: document.getElementById('chk-phone')?.value?.trim()
            };

            if (Object.values(fields).some(val => !val)) {
                return null;
            }
            return fields;
        };

        const finalizeOrderUI = async (msg, type = "success") => {
            setCart([]);
            localStorage.removeItem('make3d_cart');
            showToast(msg, type);
            await refreshAllData();
            setView('orders');
        };

        // Dodaj stan w głównym komponencie, jeśli go nie masz:
        // const [activeOrderId, setActiveOrderId] = useState(null);

        const [checkoutData, setCheckoutData] = useState({
            street: '',
            zip: '',
            city: '',
            phone: ''
        });

        useEffect(() => {
            // 1. Warunki wejściowe
            if (!window.paypal || !user || cart.length === 0) return;

            const container = document.getElementById("paypal-button-container");
            if (!container) return;

            // Zapobieganie dublowaniu przycisków
            container.innerHTML = "";

            window.paypal.Buttons({
                style: {
                    layout: "vertical",
                    color: "gold",
                    shape: "rect",
                    label: "pay",
                },

                createOrder: async () => {
                    // Ważne: upewnij się, że wysyłasz poprawne dane
                    const { data, error } = await sb.functions.invoke("Paypal-Buy", {
                        body: {
                            action: "create",
                            amount: cartTotal, // musi być np. 50.00
                            customer_email: user.email,
                            items: cart.map(i => `${i.name} (${i.qty})`).join(", "),
                            address: checkoutData, // upewnij się, że to obiekt {street, city, zip}
                        },
                    });

                    if (error || !data?.paypalOrderId) {
                        console.error("Błąd funkcji:", error);
                        throw new Error("Nie udało się utworzyć zamówienia w systemie.");
                    }

                    // Zapisujemy ID z naszej bazy w pamięci, by użyć go przy Capture
                    window.currentDbOrderId = data.dbOrderId;
                    return data.paypalOrderId;
                },

                onApprove: async (data) => {
                    try {
                        const { data: captureData, error } = await sb.functions.invoke("Paypal-Buy", {
                            body: {
                                action: "capture",
                                paypalOrderId: data.orderID,
                                dbOrderId: window.currentDbOrderId,
                            },
                        });

                        if (error) throw error;

                        showToast("Płatność zaakceptowana!", "success");
                        setCart([]);
                        setTimeout(() => setView("orders"), 1000);
                    } catch (err) {
                        console.error("Capture error:", err);
                        showToast("Błąd podczas finalizacji płatności", "error");
                    }
                },

                onCancel: () => showToast("Płatność została anulowana", "info"),
                onError: (err) => {
                    console.error("PayPal SDK Error:", err);
                    showToast("Wystąpił błąd z systemem PayPal", "error");
                }
            }).render("#paypal-button-container");

            return () => {
                if (container) container.innerHTML = "";
            };
        }, [view, user, cart, checkoutData, cartTotal]);
        // ZARAZ POD TYM POWINIENEŚ MIEĆ:
        // if (loading) { return ... }
        // return ( ... )

        // ==========================================
        // LOGIKA KOSZYKA
        // ==========================================
        const handleAddToCart = () => {
            if (!selectedProduct.is_available) return showToast("PRODUKT NIEDOSTĘPNY", "error");

            const hasVariants = selectedProduct.product_variants?.length > 0;
            if (hasVariants) {
                if (!selectedVariant) return showToast("WYBIERZ KOLOR/WARIANT", "error");
                if (!selectedVariant.is_available) return showToast("WYBRANY KOLOR NIEDOSTĘPNY", "error");
            }

            const itemPrice = selectedVariant?.price ? parseFloat(selectedVariant.price) : parseFloat(selectedProduct.price);

            setCart(prev => [...prev, {
                cartId: crypto.randomUUID(),
                productId: selectedProduct.id,
                name: selectedProduct.name,
                variantId: selectedVariant?.id || null,
                variantName: selectedVariant?.color_name || 'Standard',
                price: itemPrice,
                img: selectedVariant?.image_url || selectedProduct.image_url,
                qty: quantity
            }]);

            showToast("DODANO DO KOSZYKA!");
        };

        const removeFromCart = (cartId) => setCart(prev => prev.filter(i => i.cartId !== cartId));

        const cartSubtotal = cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
        const cartDelivery = cartSubtotal >= FREE_DELIVERY_THRESHOLD || cartSubtotal === 0 ? 0 : DELIVERY_FEE;
        const cartTotal = cartSubtotal + cartDelivery;

        // ==========================================
        // LOGIKA RENDEROWANIA SKLEPU
        // ==========================================
        const processedProducts = useMemo(() => {
            let result = [...products];
            if (activeCategory !== 'Wszystkie') result = result.filter(p => p.category === activeCategory);
            if (search.trim()) {
                const s = search.toLowerCase();
                result = result.filter(p => p.name.toLowerCase().includes(s) || (p.description?.toLowerCase().includes(s)));
            }
            switch (sortBy) {
                case 'price_asc': result.sort((a, b) => parseFloat(a.price) - parseFloat(b.price)); break;
                case 'price_desc': result.sort((a, b) => parseFloat(b.price) - parseFloat(a.price)); break;
                default: result.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)); break;
            }
            return result;
        }, [products, activeCategory, search, sortBy]);

        // ==========================================
        // EKRAN ŁADOWANIA
        // ==========================================
        if (loading) {
            return (
                <div className={`min-h-screen ${Theme.bg} flex flex-col items-center justify-center p-6 overflow-hidden`}>
                    {/* Warstwa tła - subtelny gradient w tle, żeby nie było płasko */}
                    <div className="absolute inset-0 bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-purple-500/5 via-transparent to-transparent"></div>

                    <div className="relative flex flex-col items-center">
                        {/* Nowoczesny Loader: Ring z efektem poświaty */}
                        <div className="relative w-24 h-24 mb-12">
                            {/* Zewnętrzny pierścień (statyczny/wolny) */}
                            <div className="absolute inset-0 border-[3px] border-purple-100/10 rounded-full"></div>
                            {/* Wewnętrzny pierścień (szybki spinner) */}
                            <div className="absolute inset-0 border-[3px] border-t-purple-600 border-r-transparent border-b-transparent border-l-transparent rounded-full animate-[spin_0.8s_linear_infinite]"></div>
                            {/* Środkowy punkt (pulsujący) */}
                            <div className="absolute inset-[35%] bg-purple-600 rounded-full animate-pulse shadow-[0_0_20px_rgba(147,51,234,0.5)]"></div>
                        </div>

                        {/* Tekst ładowania w Twoim stylu */}
                        <div className="text-center relative">
                            <h2 className="text-4xl md:text-5xl font-black uppercase italic tracking-tighter mb-4 text-slate-900 leading-none">
                                Ładowanie<span className="text-purple-600">.</span>
                            </h2>

                            <div className="flex items-center justify-center gap-3">
                                <div className="h-[2px] w-8 bg-purple-600/20"></div>
                                <p className="text-[10px] md:text-xs font-black uppercase tracking-[0.4em] text-gray-400 flex items-center gap-2">
                                    MAKE<span className="text-purple-600">3D</span> Shop
                                    <span className="inline-block animate-bounce"><Icons.Package size={14} /></span>
                                </p>
                                <div className="h-[2px] w-8 bg-purple-600/20"></div>
                            </div>
                        </div>
                    </div>

                    {/* Pasek postępu na dole (opcjonalny detal dla klimatu) */}
                    <div className="fixed bottom-12 w-48 h-1 bg-gray-100 rounded-full overflow-hidden">
                        <div className="h-full bg-purple-600 w-full animate-[loading-bar_2s_ease-in-out_infinite] origin-left"></div>
                    </div>

                    <style jsx>{`
                        @keyframes loading-bar {
                            0% { transform: scaleX(0); opacity: 0; }
                            50% { transform: scaleX(0.5); opacity: 1; }
                            100% { transform: scaleX(1); opacity: 0; }
                        }
                    `}</style>
                </div>
            );
        }

        const isAdmin = user?.email === ADMIN_EMAIL;

        // ============================================================================
        // GŁÓWNY RENDER APLIKACJI
        // ============================================================================
        return (
            <div className={`min-h-screen ${Theme.bg} ${Theme.text} font-sans selection:bg-purple-200 selection:text-purple-900 overflow-x-hidden`}>

                {/* Modal Globalny */}
                <CustomModal {...modalConfig} />

                {/* Powiadomienia (Toast) */}
                <div className={`fixed top-4 md:top-8 left-1/2 -translate-x-1/2 z-[9999] transition-all duration-500 ease-out w-[90%] md:w-auto max-w-sm ${toast.show ? 'translate-y-0 opacity-100 scale-100' : '-translate-y-10 opacity-0 scale-95 pointer-events-none'}`}>
                    <div className={`${toast.type === 'error' ? 'bg-rose-500' : 'bg-slate-900'} text-white px-6 md:px-8 py-4 rounded-2xl md:rounded-full font-black text-[9px] md:text-[10px] uppercase tracking-[0.2em] shadow-2xl flex items-center justify-center gap-3 border border-white/10 text-center`}>
                        <span className="shrink-0">{toast.type === 'error' ? <Icons.X /> : <Icons.Check />}</span>
                        <span className="truncate">{toast.msg}</span>
                    </div>
                </div>

                {/* ========================================== */}
                {/* NAWIGACJA (DESKTOP + MOBILE) */}
                {/* ========================================== */}
                <nav className="sticky top-0 z-[500] bg-white/90 backdrop-blur-xl border-b border-gray-100/50">
                    <div className="max-w-[1400px] mx-auto px-4 md:px-12 h-16 md:h-24 flex items-center justify-between">

                        {/* Hamburger Menu (Tylko Mobile) */}
                        <button onClick={() => setIsMobileMenuOpen(true)} className="lg:hidden p-2 text-slate-900 hover:bg-gray-100 rounded-xl transition-colors">
                            <Icons.Menu />
                        </button>

                        {/* Logo */}
                        <div onClick={() => { navigateTo('home'); setSearch(''); }} className="cursor-pointer group flex items-center gap-2 absolute left-1/2 -translate-x-1/2 lg:static lg:translate-x-0">
                            <span className="hidden sm:block"><Icons.Package /></span>
                            <h1 className="text-xl md:text-3xl font-black italic tracking-tighter group-hover:scale-105 transition-transform origin-left">
                                MAKE<span className="text-purple-600">3D</span>
                            </h1>
                        </div>

                        {/* Linki Desktop */}
                        <div className="hidden lg:flex items-center gap-10 text-[10px] font-black uppercase tracking-[0.2em] text-gray-400">
                            <button onClick={() => navigateTo('home')} className={`hover:text-slate-900 transition-colors ${view === 'home' && 'text-slate-900'}`}>Katalog</button>
                            {user && <button onClick={() => navigateTo('orders')} className={`hover:text-slate-900 transition-colors ${view === 'orders' && 'text-slate-900'}`}>Moje Zamówienia</button>}
                        </div>

                        {/* Akcje (Koszyk / Profil) */}
                        <div className="flex items-center gap-2 md:gap-4">
                            {isAdmin && (
                                <button onClick={() => navigateTo('admin')} className="hidden xl:flex items-center gap-2 bg-purple-50 text-purple-600 hover:bg-purple-600 hover:text-white px-5 py-2.5 rounded-xl font-black text-[9px] uppercase tracking-widest transition-all">
                                    <Icons.Settings /> Panel Admina
                                </button>
                            )}

                            <button onClick={() => navigateTo('cart')} className="bg-slate-900 text-white px-4 md:px-5 py-2 md:py-2.5 rounded-xl flex items-center gap-2 hover:bg-purple-600 transition-all shadow-lg shadow-slate-900/10 active:scale-95">
                                <Icons.Cart />
                                <span className="bg-white/20 px-2 py-0.5 rounded text-[9px] md:text-[10px] font-black">{cart.length}</span>
                            </button>

                            <div className="hidden md:block">
                                {user ? (
                                    <div className="relative group">
                                        <button onClick={() => navigateTo('orders')} className="w-10 h-10 rounded-xl overflow-hidden border-2 border-transparent hover:border-purple-300 transition-all shadow-sm">
                                            <img src={user.user_metadata?.avatar_url || `https://ui-avatars.com/api/?name=${user.email}`} className="w-full h-full object-cover" alt="User" />
                                        </button>
                                        <div className="absolute right-0 top-full mt-2 w-56 bg-white border border-gray-100 rounded-2xl shadow-xl opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all flex flex-col overflow-hidden">
                                            <div className="px-5 py-4 bg-gray-50 border-b border-gray-100">
                                                <p className="text-xs font-black truncate">{user.user_metadata?.full_name || 'Klient'}</p>
                                                <p className="text-[9px] font-bold text-gray-400 truncate">{user.email}</p>
                                            </div>
                                            <button onClick={() => navigateTo('orders')} className="text-left px-5 py-4 text-[10px] font-black uppercase tracking-widest hover:bg-purple-50 hover:text-purple-600 flex items-center gap-2"><Icons.Package/> Historia</button>
                                            <button onClick={async () => { await sb.auth.signOut(); setCart([]); navigateTo('home'); }} className="text-left px-5 py-4 text-[10px] font-black uppercase tracking-widest text-rose-500 hover:bg-rose-50 flex items-center gap-2"><Icons.LogOut/> Wyloguj</button>
                                        </div>
                                    </div>
                                ) : (
                                    <button onClick={() => sb.auth.signInWithOAuth({ provider: 'google' })} className="w-10 h-10 flex items-center justify-center bg-white border border-gray-200 rounded-xl text-gray-500 hover:text-purple-600 hover:border-purple-300 transition-all shadow-sm">
                                        <Icons.User />
                                    </button>
                                )}
                            </div>
                        </div>
                    </div>
                </nav>

                {/* --- MENU MOBILNE (DRAWER) --- */}
                <div className={`fixed inset-0 z-[1000] lg:hidden transition-opacity duration-300 ${isMobileMenuOpen ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'}`}>
                    <div className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm" onClick={() => setIsMobileMenuOpen(false)}></div>
                    <div className={`absolute top-0 left-0 bottom-0 w-[85%] max-w-sm bg-white shadow-2xl transition-transform duration-500 ease-out flex flex-col ${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'}`}>
                        <div className="p-6 border-b border-gray-100 flex justify-between items-center">
                            <h2 className="text-2xl font-black italic tracking-tighter">MAKE<span className="text-purple-600">3D</span></h2>
                            <button onClick={() => setIsMobileMenuOpen(false)} className="p-2 text-gray-400 hover:text-rose-500 bg-gray-50 rounded-xl"><Icons.X /></button>
                        </div>

                        <div className="flex-1 overflow-y-auto py-6 px-4 space-y-2">
                            <button onClick={() => navigateTo('home')} className={`w-full text-left px-6 py-4 rounded-2xl text-xs font-black uppercase tracking-widest flex items-center gap-3 ${view === 'home' ? 'bg-slate-900 text-white' : 'text-gray-500 hover:bg-gray-50'}`}>
                                <Icons.Search /> Katalog Produktów
                            </button>
                            {user && (
                                <button onClick={() => navigateTo('orders')} className={`w-full text-left px-6 py-4 rounded-2xl text-xs font-black uppercase tracking-widest flex items-center gap-3 ${view === 'orders' ? 'bg-slate-900 text-white' : 'text-gray-500 hover:bg-gray-50'}`}>
                                    <Icons.Package /> Moje Zamówienia
                                </button>
                            )}
                            {isAdmin && (
                                <button onClick={() => navigateTo('admin')} className={`w-full text-left px-6 py-4 rounded-2xl text-xs font-black uppercase tracking-widest flex items-center gap-3 ${view === 'admin' ? 'bg-purple-600 text-white' : 'text-purple-600 hover:bg-purple-50'}`}>
                                    <Icons.Settings /> Panel Admina
                                </button>
                            )}
                        </div>

                        <div className="p-6 border-t border-gray-100 bg-gray-50">
                            {user ? (
                                <div className="space-y-4">
                                    <div className="flex items-center gap-4">
                                        <img src={user.user_metadata?.avatar_url || `https://ui-avatars.com/api/?name=${user.email}`} className="w-12 h-12 rounded-xl object-cover shadow-sm" />
                                        <div className="overflow-hidden">
                                            <p className="text-sm font-black truncate">{user.user_metadata?.full_name || 'Klient'}</p>
                                            <p className="text-[10px] font-bold text-gray-500 truncate">{user.email}</p>
                                        </div>
                                    </div>
                                    <button onClick={async () => { await sb.auth.signOut(); setCart([]); setIsMobileMenuOpen(false); navigateTo('home'); }} className={`${Theme.btnDanger} w-full flex justify-center gap-2`}><Icons.LogOut/> Wyloguj</button>
                                </div>
                            ) : (
                                <div className="space-y-4 text-center">
                                    <p className="text-xs font-bold text-gray-500">Zaloguj się, aby śledzić zamówienia.</p>
                                    <button onClick={() => sb.auth.signInWithOAuth({ provider: 'google' })} className={`${Theme.btnPrimary} w-full flex justify-center gap-2`}><Icons.User/> Zaloguj przez Google</button>
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                {/* ========================================== */}
                {/* GŁÓWNY KONTENER TREŚCI */}
                {/* ========================================== */}
                <main className="max-w-[1400px] mx-auto px-4 md:px-12 py-6 md:py-12">

                    {/* ------------------------------------------ */}
                    {/* WIDOK 1: STRONA GŁÓWNA / KATALOG */}
                    {/* ------------------------------------------ */}
                    {view === 'home' && (
                        <div className="space-y-8 md:space-y-12 animate-in fade-in duration-700">
                            {/* Wyszukiwarka i Filtry - Mobile Optimized */}
                            <div className={`${Theme.card} p-4 md:p-6 sticky top-[72px] md:top-28 z-[400] flex flex-col xl:flex-row gap-4 justify-between items-center bg-white/90 backdrop-blur-md`}>
                                {/* Kategorie (Scrollable on mobile) */}
                                <div className="flex gap-2 overflow-x-auto no-scrollbar w-full xl:w-auto pb-2 xl:pb-0 snap-x">
                                    <button onClick={() => setActiveCategory('Wszystkie')} className={`snap-start shrink-0 px-5 md:px-6 py-3 rounded-xl text-[9px] md:text-[10px] font-black uppercase tracking-widest transition-all ${activeCategory === 'Wszystkie' ? 'bg-slate-900 text-white' : 'bg-gray-50 text-gray-500 hover:bg-gray-100'}`}>
                                        Wszystkie
                                    </button>
                                    {categories.map(c => (
                                        <button key={c.id} onClick={() => setActiveCategory(c.name)} className={`snap-start shrink-0 px-5 md:px-6 py-3 rounded-xl text-[9px] md:text-[10px] font-black uppercase tracking-widest transition-all ${activeCategory === c.name ? 'bg-slate-900 text-white' : 'bg-gray-50 text-gray-500 hover:bg-gray-100'}`}>
                                            {c.name}
                                        </button>
                                    ))}
                                </div>

                                {/* Szukaj i Sortuj */}
                                <div className="flex flex-col sm:flex-row w-full xl:w-auto gap-3 md:gap-4 items-stretch sm:items-center">

                                    {/* Kontener wyszukiwarki */}
                                    <div className="relative flex-grow sm:w-72 lg:w-96 group">
                                        {/* Ikona - przesunięta nieco bardziej w lewo dla balansu */}
                                        <span className="absolute left-5 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-purple-500 transition-colors pointer-events-none z-20">
                                            <Icons.Search />
                                        </span>

                                        {/* Input - dodany style={{ paddingLeft: '3.5rem' }} który wymusi odstęp */}
                                        <input 
                                            type="text" 
                                            placeholder="Szukaj modelu..." 
                                            style={{ paddingLeft: '3.75rem' }} 
                                            className={`${Theme.input} w-full transition-all focus:ring-2 focus:ring-purple-500/10`} 
                                            value={search} 
                                            onChange={e => setSearch(e.target.value)} 
                                        />
                                    </div>

                                    {/* Selektor sortowania */}
                                    <div className="sm:w-56">
                                        <select 
                                            className={`${Theme.select} w-full h-full cursor-pointer hover:border-gray-300 transition-colors`} 
                                            value={sortBy} 
                                            onChange={e => setSortBy(e.target.value)}
                                        >
                                            <option value="newest">Najnowsze</option>
                                            <option value="price_asc">Od najtańszych</option>
                                            <option value="price_desc">Od najdroższych</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            {/* Siatka Produktów */}
                            {processedProducts.length > 0 ? (
                                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 md:gap-8">
                                    {processedProducts.map(p => (
                                        <div key={p.id} 
                                             onClick={() => { setSelectedProduct(p); setSelectedVariant(null); setQuantity(1); navigateTo('details'); }} 
                                             className="group cursor-pointer">

                                            <div className={`${Theme.card} h-full min-h-[420px] p-5 md:p-6 flex flex-col group-hover:border-purple-300 group-hover:shadow-2xl md:group-hover:-translate-y-2 transition-all duration-300 relative overflow-hidden`}>

                                                {/* Plakietki (Badge) - Górna sekcja */}
                                                <div className="flex justify-between items-start gap-2 mb-4 relative z-20">
                                                    <span className={`${Theme.badge('outline')} backdrop-blur-md bg-white/50`}>{p.category}</span>
                                                    <div className="flex flex-col gap-1 items-end">
                                                        {!p.is_available && <span className={Theme.badge('rose')}>Brak</span>}
                                                        {p.is_available && p.is_featured && <span className={Theme.badge('purple')}>HIT</span>}
                                                    </div>
                                                </div>

                                                {/* Kontener Obrazka - Centrowanie i elastyczność */}
                                                <div className="flex-grow flex items-center justify-center min-h-[200px] max-h-[260px] mb-6 relative z-10">
                                                    <img 
                                                        src={p.image_url} 
                                                        alt={p.name} 
                                                        className={`max-h-full w-auto object-contain transition-transform duration-700 md:group-hover:scale-110 ${!p.is_available ? 'grayscale opacity-40' : ''}`} 
                                                        loading="lazy" 
                                                    />
                                                </div>

                                                {/* Dolna sekcja: Nazwa i Cena */}
                                                <div className="mt-auto pt-4 border-t border-gray-50 relative z-20">
                                                    <h3 className={`text-base md:text-lg font-black uppercase italic leading-tight mb-2 line-clamp-2 min-h-[3rem] ${!p.is_available ? 'text-gray-400' : 'text-slate-800'}`}>
                                                        {p.name}
                                                    </h3>

                                                    <div className="flex justify-between items-end gap-2">
                                                        <div>
                                                            <p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-0.5">Cena</p>
                                                            <p className={`text-xl md:text-2xl font-black tracking-tighter leading-none ${!p.is_available ? 'text-gray-400' : 'text-purple-600'}`}>
                                                                {parseFloat(p.price).toFixed(2)} <span className="text-sm ml-0.5">zł</span>
                                                            </p>
                                                        </div>

                                                        <div className="w-12 h-12 rounded-2xl bg-gray-50 flex items-center justify-center text-slate-400 group-hover:bg-slate-900 group-hover:text-white transition-all duration-300 transform group-hover:rotate-6">
                                                            <Icons.Cart />
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            ) : (
                                <EmptyState icon={<Icons.Search />} title="Brak Wyników" desc="Spróbuj zmienić filtry lub wyszukiwaną frazę." />
                            )}
                        </div>
                    )}

                    {/* ------------------------------------------ */}
                    {/* WIDOK 2: SZCZEGÓŁY PRODUKTU */}
                    {/* ------------------------------------------ */}
                    {view === 'details' && selectedProduct && (
                        <div className="animate-in slide-in-from-bottom-8 duration-500">
                            <button onClick={() => navigateTo('home')} className="mb-6 flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.2em] text-gray-500 hover:text-slate-900 transition-colors bg-white px-4 py-2 rounded-xl border border-gray-100 shadow-sm md:bg-transparent md:border-none md:shadow-none md:p-0">
                                ← Powrót
                            </button>

                            <div className="flex flex-col lg:flex-row gap-8 lg:gap-16 xl:gap-24">
                                {/* Zdjęcie Główne (Mobile Responsive) */}
                                <div className="flex-1 w-full">
                                    <div className={`${Theme.card} p-8 lg:p-16 flex items-center justify-center min-h-[300px] sm:min-h-[400px] lg:min-h-[600px] lg:sticky lg:top-32 bg-white relative`}>
                                        {!selectedProduct.is_available && (
                                            <div className="absolute top-6 left-6 z-20"><span className={Theme.badge('rose')}>Niedostępny</span></div>
                                        )}
                                        <img 
                                            src={selectedVariant?.image_url || selectedProduct.image_url} 
                                            alt={selectedProduct.name}
                                            className={`max-h-[250px] sm:max-h-[350px] lg:max-h-[450px] object-contain drop-shadow-2xl transition-all duration-500 ${!selectedProduct.is_available ? 'grayscale opacity-60' : 'lg:hover:scale-105 lg:hover:-rotate-2'}`}
                                        />
                                    </div>
                                </div>

                                {/* Formularz i Opis */}
                                <div className="flex-1 space-y-8 lg:space-y-10 lg:py-4">
                                    <div>
                                        <div className="flex flex-wrap items-center gap-3 mb-4 lg:mb-6">
                                            <span className={Theme.badge('dark')}>{selectedProduct.category}</span>
                                            <div className="flex text-yellow-400 gap-1">
                                                {[1,2,3,4,5].map(i => <Icons.Star key={i} filled={true} />)}
                                            </div>
                                            <span className="text-[10px] font-bold text-gray-400">({reviews.filter(r=>r.product_id===selectedProduct.id).length} opinii)</span>
                                        </div>
                                        <h1 className={`text-4xl sm:text-5xl lg:text-7xl font-black uppercase italic tracking-tighter leading-[0.9] mb-4 lg:mb-6 ${!selectedProduct.is_available ? 'text-gray-400' : ''}`}>
                                            {selectedProduct.name}
                                        </h1>
                                        <p className={`text-3xl sm:text-4xl lg:text-5xl font-black tracking-tighter ${!selectedProduct.is_available ? 'text-gray-400' : 'text-purple-600'}`}>
                                            {selectedVariant ? parseFloat(selectedVariant.price).toFixed(2) : parseFloat(selectedProduct.price).toFixed(2)} zł
                                        </p>
                                    </div>

                                    <p className="text-sm font-bold text-gray-500 leading-relaxed max-w-lg">
                                        {selectedProduct.description || "Wysokiej jakości wydruk 3D wykonany w technologii FDM/SLA. Używamy wyłącznie sprawdzonych materiałów, gwarantując precyzję i trwałość."}
                                    </p>

                                    {/* Warianty / Kolory */}
                                    {selectedProduct.product_variants?.length > 0 && (
                                        <div className="space-y-4 pt-6 border-t border-gray-100">
                                            <p className="text-[10px] font-black uppercase tracking-[0.2em] text-gray-400">Wybierz Kolor:</p>
                                            <div className="flex flex-wrap gap-2 md:gap-3">
                                                {selectedProduct.product_variants.map(v => {
                                                    const isSel = selectedVariant?.id === v.id;
                                                    const isAvail = v.is_available;
                                                    return (
                                                        <button 
                                                            key={v.id} 
                                                            onClick={() => isAvail && setSelectedVariant(v)}
                                                            disabled={!isAvail}
                                                            className={`px-4 md:px-6 py-3 md:py-4 rounded-xl md:rounded-2xl font-black text-[9px] md:text-[10px] uppercase tracking-widest transition-all border-2 ${isSel ? 'bg-slate-900 text-white border-slate-900 shadow-xl' : (!isAvail ? 'bg-gray-50 border-gray-100 text-gray-400 cursor-not-allowed opacity-60' : 'bg-white border-gray-200 text-gray-600 hover:border-purple-400')}`}
                                                        >
                                                            {v.color_name} {!isAvail && '(Brak)'}
                                                        </button>
                                                    );
                                                })}
                                            </div>
                                        </div>
                                    )}

                                    {/* Akcje (Ilość + Koszyk) */}
                                    <div className="flex flex-col sm:flex-row gap-3 md:gap-4 pt-4 lg:pt-6">
                                        <div className="flex items-center bg-gray-50 border-2 border-gray-100 rounded-2xl p-2 h-14 md:h-16 w-full sm:w-40 justify-between">
                                            <button onClick={() => setQuantity(Math.max(1, quantity-1))} disabled={!selectedProduct.is_available} className="w-12 h-full font-black text-xl text-gray-500 hover:text-slate-900 disabled:opacity-30">-</button>
                                            <span className={`font-black text-lg md:text-xl ${!selectedProduct.is_available ? 'text-gray-400' : ''}`}>{quantity}</span>
                                            <button onClick={() => setQuantity(quantity+1)} disabled={!selectedProduct.is_available} className="w-12 h-full font-black text-xl text-gray-500 hover:text-slate-900 disabled:opacity-30">+</button>
                                        </div>
                                        <button onClick={handleAddToCart} disabled={!selectedProduct.is_available} className={`${Theme.btnPrimary} flex-grow h-14 md:h-16 text-xs md:text-sm w-full`}>
                                            {!selectedProduct.is_available ? 'Chwilowo Niedostępny' : 'Dodaj do koszyka'}
                                        </button>
                                    </div>

                                    {/* Opinie - Skrócona wersja */}
                                    <div className="pt-12 border-t border-gray-100 mt-12">
                                        <h3 className="text-xl md:text-2xl font-black uppercase italic tracking-tighter mb-6">Opinie Klientów</h3>
                                        <div className="space-y-4">
                                            {reviews.filter(r => r.product_id === selectedProduct.id).slice(0,3).map(review => (
                                                <div key={review.id} className="bg-gray-50 p-5 md:p-6 rounded-2xl md:rounded-3xl border border-gray-100">
                                                    <div className="flex justify-between items-start mb-3">
                                                        <div>
                                                            <p className="font-black text-[10px] md:text-xs uppercase tracking-widest text-slate-900">{review.user_name}</p>
                                                            <p className="text-[8px] md:text-[9px] font-bold text-gray-400 mt-1">{new Date(review.created_at).toLocaleDateString('pl-PL')}</p>
                                                        </div>
                                                        <div className="flex text-yellow-400 gap-0.5 scale-75 md:scale-100 origin-right">
                                                            {[...Array(review.rating)].map((_, i) => <Icons.Star key={i} filled={true} />)}
                                                        </div>
                                                    </div>
                                                    <p className="text-xs md:text-sm font-bold text-gray-600 italic leading-relaxed">"{review.comment}"</p>
                                                </div>
                                            ))}
                                            {reviews.filter(r => r.product_id === selectedProduct.id).length === 0 && (
                                                <p className="text-center text-xs font-bold text-gray-400 py-6">Jeszcze nikt nie ocenił tego produktu.</p>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* ------------------------------------------ */}
                    {/* WIDOK 3: KOSZYK I CHECKOUT (Z PAYPAL)     */}
                    {/* ------------------------------------------ */}
                    {view === 'cart' && (
                        <div className="max-w-7xl mx-auto px-4 py-6 md:py-12 animate-in fade-in duration-500">
                            <div className="flex items-center gap-4 md:gap-6 mb-8 md:mb-16">
                                <h2 className="text-4xl md:text-8xl font-black uppercase italic tracking-tighter text-slate-900">Koszyk</h2>
                                <div className="h-10 w-10 md:h-16 md:w-16 rounded-xl bg-purple-600 text-white flex items-center justify-center text-xl md:text-3xl font-black italic">
                                    {cart.length}
                                </div>
                            </div>

                            {cart.length === 0 ? (
                                <div className="py-20 text-center border-2 border-dashed border-slate-200 rounded-3xl">
                                    <p className="text-slate-400 font-black uppercase italic">Koszyk jest pusty</p>
                                    <button onClick={() => setView('catalog')} className="mt-6 px-8 py-3 bg-slate-900 text-white rounded-xl font-bold uppercase italic text-sm">Wróć do sklepu</button>
                                </div>
                            ) : (
                                <div className="flex flex-col lg:flex-row gap-8 lg:items-start">
                                    <div className="flex-1 space-y-3">
                                        {cart.map((item) => (
                                            <div key={item.cartId} className="bg-white p-4 rounded-2xl border border-slate-100 flex items-center gap-4 shadow-sm">
                                                <div className="w-16 h-16 md:w-20 bg-slate-50 rounded-xl overflow-hidden flex items-center justify-center">
                                                    <img src={item.img} className="max-h-full object-contain" />
                                                </div>
                                                <div className="flex-1">
                                                    <h4 className="font-black uppercase italic text-slate-900 text-xs md:text-sm">{item.name}</h4>
                                                    <p className="text-[9px] font-bold opacity-30 uppercase">{item.variantName}</p>
                                                    <p className="text-purple-600 font-black text-sm mt-1">{item.qty} × {item.price.toFixed(2)} zł</p>
                                                </div>
                                                <button onClick={() => removeFromCart(item.cartId)} className="p-2 text-rose-400"><Icons.Trash size={18} /></button>
                                            </div>
                                        ))}
                                    </div>

                                    <div className="w-full lg:w-[440px] sticky top-4">
                                        {user ? (
                                            <div className="bg-white p-6 md:p-8 rounded-[2.5rem] border border-slate-100 shadow-2xl">
                                                <h3 className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400 mb-6 pb-4 border-b">Adres Dostawy</h3>
                                                <div className="space-y-3 mb-8">
                                                    <div className="grid grid-cols-2 gap-3">
                                                        <input className={`${Theme.input} bg-slate-50 border-none text-slate-900`} value={user?.user_metadata?.full_name?.split(' ')[0]} readOnly />
                                                        <input className={`${Theme.input} bg-slate-50 border-none text-slate-900`} value={user?.user_metadata?.full_name?.split(' ').slice(1).join(' ')} readOnly />
                                                    </div>
                                                    <input className={`${Theme.input} bg-slate-50 border-none text-slate-900`} value={user.email} readOnly />
                                                    <div className="grid grid-cols-3 gap-2">
                                                        <input placeholder="Ulica i nr" className={`${Theme.input} border-slate-200 text-slate-900 col-span-2`} value={checkoutData.street} onChange={e => setCheckoutData({...checkoutData, street: e.target.value})} />
                                                        <input placeholder="Kod" className={`${Theme.input} border-slate-200 text-slate-900`} value={checkoutData.zip} onChange={e => setCheckoutData({...checkoutData, zip: e.target.value})} />
                                                    </div>
                                                    <input placeholder="Miasto" className={`${Theme.input} border-slate-200 text-slate-900`} value={checkoutData.city} onChange={e => setCheckoutData({...checkoutData, city: e.target.value})} />
                                                    <div className="relative">
                                                        <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-300 font-bold text-sm">+48</span>
                                                        <input placeholder="Numer telefonu" className={`${Theme.input} border-slate-200 text-slate-900 pl-12`} value={checkoutData.phone} onChange={e => setCheckoutData({...checkoutData, phone: e.target.value.replace(/\D/g, '').slice(0, 9)})} />
                                                    </div>
                                                </div>

                                                <div className="pt-6 border-t border-slate-50 space-y-2">
                                                    <div className="flex justify-between text-[11px] font-bold uppercase text-slate-400">
                                                        <span>Produkty</span>
                                                        <span>{cartSubtotal.toFixed(2)} zł</span>
                                                    </div>
                                                    <div className="flex justify-between items-end pt-4 mb-8">
                                                        <div>
                                                            <p className="text-[10px] font-black uppercase text-slate-300 leading-none mb-1">Razem do zapłaty</p>
                                                            <p className="text-4xl font-black italic text-slate-900 tracking-tighter leading-none">{cartTotal.toFixed(2)} zł</p>
                                                        </div>
                                                    </div>
                                                    <div id="paypal-button-container" className="min-h-[150px]"></div>
                                                </div>
                                            </div>
                                        ) : (
                                            <div className="bg-purple-50 p-8 rounded-[2.5rem] border-2 border-dashed border-purple-200 text-center">
                                                <h3 className="text-2xl font-black uppercase italic text-slate-900">Zaloguj się</h3>
                                                <button onClick={() => sb.auth.signInWithOAuth({ provider: 'google' })} className="mt-8 w-full py-4 bg-slate-900 text-white rounded-2xl font-black uppercase italic">Zaloguj przez Google</button>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )}
                        </div>
                    )}
                    
                    {view === 'orders' && user && (
                        <div className="max-w-4xl mx-auto p-4 animate-in fade-in">
                            <h2 className="text-5xl md:text-7xl font-black uppercase italic mb-12">Twoja Historia</h2>
                            <div className="space-y-8">
                                {orders.filter(o => o.customer_email === user.email).map((order) => {
                                    const s = order.status.toLowerCase();
                                    const isUnpaid = s.includes('pending') || s.includes('oczekiwanie') || s.includes('czeka na opłatę');

                                    return (
                                        <div key={order.id} className={`bg-white rounded-3xl p-8 border-2 ${isUnpaid ? 'border-amber-400 shadow-lg' : 'border-gray-100'}`}>
                                            <div className="flex justify-between mb-6">
                                                <span className={`px-4 py-1 rounded-full text-[10px] font-black uppercase ${isUnpaid ? 'bg-amber-100 text-amber-600' : 'bg-gray-100'}`}>
                                                    {order.status}
                                                </span>
                                                <span className="opacity-20 font-mono text-[10px]">#{order.id.slice(-8)}</span>
                                            </div>

                                            <div className="grid md:grid-cols-2 gap-6 mb-6">
                                                <div className="bg-gray-50 p-4 rounded-xl">
                                                    <p className="text-[9px] font-black text-gray-400 uppercase mb-2">Produkty:</p>
                                                    <p className="text-sm font-bold">{order.items}</p>
                                                </div>
                                                <div>
                                                    <p className="text-[9px] font-black text-gray-400 uppercase mb-2">Adres:</p>
                                                    <p className="text-sm italic">{order.address}</p>
                                                </div>
                                            </div>

                                            <div className="flex flex-col md:flex-row justify-between items-center pt-6 border-t gap-4">
                                                <p className="text-3xl font-black">{parseFloat(order.total_price).toFixed(2)} zł</p>

                                                {isUnpaid && (
                                                    <div className="w-full md:w-64">
                                                        {activeOrderId === order.id ? (
                                                            <div className="space-y-2">
                                                                <div id={`paypal-button-${order.id}`}></div>
                                                                <button onClick={() => setActiveOrderId(null)} className="w-full text-[10px] font-bold uppercase opacity-40">Anuluj</button>
                                                            </div>
                                                        ) : (
                                                            <button 
                                                                onClick={() => setActiveOrderId(order.id)}
                                                                className="w-full bg-[#0070ba] text-white py-4 rounded-xl font-black uppercase italic hover:scale-105 transition-transform"
                                                            >
                                                                Dokończ płatność
                                                            </button>
                                                        )}
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    )}
                    {/* ------------------------------------------ */}
                    {/* WIDOK 5: PANEL ADMINISTRATORA (POTĘŻNY) */}
                    {/* ------------------------------------------ */}
                    {view === 'admin' && isAdmin && (
                        <AdminDashboard 
                            products={products} 
                            categories={categories} 
                            orders={orders} 
                            reviews={reviews} 
                            refresh={refreshAllData} 
                            showToast={showToast} 
                            confirmAction={confirmAction}
                        />
                    )}
                </main>

                {/* ========================================== */}
                {/* STOPKA (FOOTER) */}
                {/* ========================================== */}
                <footer className="bg-white border-t border-gray-100 mt-12 md:mt-24 pt-16 md:pt-24 pb-8 md:pb-12">
                    <div className="max-w-[1400px] mx-auto px-6 md:px-12 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-12 mb-16">
                        <div className="lg:col-span-2">
                            <div className="flex items-center gap-2 mb-6 text-slate-900">
                                <Icons.Package />
                                <h2 className="text-2xl md:text-3xl font-black italic tracking-tighter">MAKE<span className="text-purple-600">3D</span></h2>
                            </div>
                            <p className="text-[10px] md:text-xs font-bold text-gray-400 uppercase tracking-widest leading-loose max-w-sm">
                                Zaawansowane studio druku 3D. Przekształcamy cyfrowe modele w fizyczną rzeczywistość przy użyciu najnowszych technologii FDM 
                            </p>
                        </div>
                        <div>
                            <ul className="space-y-4 text-[10px] md:text-xs font-bold text-gray-500">
                                <li className="flex items-center gap-2"><Icons.User/> {ADMIN_EMAIL}</li>
                                <li className="flex items-center gap-2"><Icons.Clock/> Pn-Pt: 9:00 - 17:00</li>
                            </ul>
                        </div>
                    </div>
                    <div className="border-t border-gray-100 pt-8 flex flex-col md:flex-row items-center justify-between px-6 md:px-12 text-[8px] md:text-[9px] font-black text-gray-400 uppercase tracking-[0.3em] text-center md:text-left gap-4">
                        <p>&copy; 2026 MAKE3D. Wszelkie Prawa Zastrzeżone.</p>
                    </div>
                </footer>
            </div>
        );
    }

    // ============================================================================
    // 6. PANEL ADMINISTRATORA (ZAAWANSOWANY KOMPONENT)
    // ============================================================================
    function AdminDashboard({ products, categories, orders, reviews, refresh, showToast, confirmAction }) {
        const [activeTab, setActiveTab] = useState('orders'); // orders, products, categories, reviews

        const stats = {
            totalRevenue: orders.filter(o => o.status === 'opłacone' || o.status === 'wysłane').reduce((sum, o) => sum + parseFloat(o.total_price), 0),
            pendingOrders: orders.filter(o => o.status === 'czeka na potwierdzenie').length,
            totalProducts: products.length,
            avgRating: reviews.length ? (reviews.reduce((s, r) => s + r.rating, 0) / reviews.length).toFixed(1) : 0
        };

        return (
            <div className="space-y-8 md:space-y-12 animate-in slide-in-from-bottom-8">
                <h2 className="text-3xl md:text-5xl font-black uppercase italic tracking-tighter">Panel Administracyjny</h2>

                {/* Kafelki Statystyk (Mobile Grid) */}
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6">
                    <div className="bg-slate-900 text-white p-6 md:p-8 rounded-2xl md:rounded-[2rem] shadow-xl relative overflow-hidden group">
                        <div className="absolute right-[-10%] top-[-10%] opacity-10 scale-150 transition-transform group-hover:scale-125"><Icons.Search /></div>
                        <p className="text-[9px] md:text-[10px] font-black uppercase opacity-60 tracking-widest mb-2 relative z-10">Przychód Netto</p>
                        <p className="text-3xl md:text-4xl font-black tracking-tighter relative z-10">{stats.totalRevenue.toFixed(2)} <span className="text-lg">zł</span></p>
                    </div>
                    <div className="bg-purple-600 text-white p-6 md:p-8 rounded-2xl md:rounded-[2rem] shadow-xl shadow-purple-200 relative overflow-hidden group">
                        <div className="absolute right-[-10%] top-[-10%] opacity-20 scale-150 transition-transform group-hover:scale-125"><Icons.Package /></div>
                        <p className="text-[9px] md:text-[10px] font-black uppercase opacity-80 tracking-widest mb-2 relative z-10">Aktywne Zamówienia</p>
                        <p className="text-3xl md:text-4xl font-black tracking-tighter relative z-10">{stats.pendingOrders}</p>
                    </div>
                    <div className="bg-white border border-gray-100 p-6 md:p-8 rounded-2xl md:rounded-[2rem] shadow-sm text-slate-900">
                        <p className="text-[9px] md:text-[10px] font-black uppercase text-gray-400 tracking-widest mb-2">Asortyment</p>
                        <p className="text-3xl md:text-4xl font-black tracking-tighter">{stats.totalProducts}</p>
                    </div>
                    <div className="bg-white border border-gray-100 p-6 md:p-8 rounded-2xl md:rounded-[2rem] shadow-sm text-slate-900">
                        <p className="text-[9px] md:text-[10px] font-black uppercase text-gray-400 tracking-widest mb-2">Satysfakcja (Średnia)</p>
                        <p className="text-3xl md:text-4xl font-black tracking-tighter flex items-center gap-2">
                            {stats.avgRating} <span className="text-yellow-400 text-2xl"><Icons.Star filled={true}/></span>
                        </p>
                    </div>
                </div>

                {/* Nawigacja Zakładek Admina (Scrollable on Mobile) */}
                <div className="flex gap-2 md:gap-4 overflow-x-auto no-scrollbar border-b border-gray-200 pb-4 snap-x">
                    {[
                        { id: 'orders', label: 'Zamówienia', icon: <Icons.Package/> },
                        { id: 'products', label: 'Baza Produktów', icon: <Icons.Search/> },
                        { id: 'categories', label: 'Kategorie', icon: <Icons.Menu/> },
                        { id: 'reviews', label: 'Opinie Klientów', icon: <Icons.Star/> }
                    ].map(tab => (
                        <button 
                            key={tab.id} onClick={() => setActiveTab(tab.id)}
                            className={`snap-start shrink-0 px-5 md:px-8 py-3 md:py-4 rounded-xl md:rounded-2xl text-[9px] md:text-[10px] font-black uppercase tracking-widest transition-all flex items-center gap-2 ${activeTab === tab.id ? 'bg-slate-900 text-white shadow-lg' : 'bg-white text-gray-500 hover:bg-gray-50 border border-gray-100'}`}
                        >
                            <span className="scale-75 md:scale-100">{tab.icon}</span> {tab.label}
                        </button>
                    ))}
                </div>
                {/* ========================================== */}
                {/* ZAKŁADKA 1: ZARZĄDZANIE ZAMÓWIENIAMI */}
                {/* ========================================== */}
                {activeTab === 'orders' && (
                    <div className="space-y-6">
                        {orders.length === 0 && <EmptyState icon={<Icons.Package />} title="Pusto" desc="Brak zamówień w systemie." />}
                        {orders.map(order => (
                            <div key={order.id} className={`${Theme.card} p-6 md:p-10 flex flex-col xl:flex-row gap-6 md:gap-10`}>
                                {/* Lewa strona: Dane zamówienia */}
                                <div className="flex-1 space-y-4 md:space-y-6">
                                    <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-3 border-b border-gray-100 pb-4">
                                        <span className={Theme.badge(order.status === 'opłacone' ? 'purple' : order.status === 'wysłane' ? 'green' : order.status === 'anulowane' ? 'outline' : 'rose')}>
                                            STATUS: {order.status}
                                        </span>
                                        <span className="text-[9px] md:text-[10px] font-black text-gray-400 uppercase tracking-widest">
                                            Data: {new Date(order.created_at).toLocaleString('pl-PL')} | ID: #{order.id.slice(0,6)}
                                        </span>
                                    </div>

                                    <div className="bg-gray-50 p-5 md:p-6 rounded-2xl border border-gray-100">
                                        <p className="text-[9px] font-black uppercase tracking-widest text-gray-400 mb-3">Produkty</p>
                                        <pre className="font-sans font-bold text-xs md:text-sm text-slate-700 whitespace-pre-wrap">{order.items}</pre>
                                    </div>

                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                        <div className="p-4 border border-gray-100 rounded-2xl">
                                            <p className="text-[9px] font-black uppercase text-gray-400 tracking-widest mb-2">Dane Klienta (Email)</p>
                                            <p className="text-xs font-bold text-slate-700 break-all">{order.customer_email}</p>
                                        </div>
                                        <div className="p-4 border border-gray-100 rounded-2xl">
                                            <p className="text-[9px] font-black uppercase text-gray-400 tracking-widest mb-2">Adres Dostawy</p>
                                            <p className="text-xs font-bold text-slate-700 whitespace-pre-wrap">{order.address}</p>
                                        </div>
                                    </div>
                                </div>

                                {/* Prawa strona: Akcje i Status */}
                                <div className="xl:w-80 flex flex-col bg-slate-900 text-white rounded-2xl md:rounded-[2rem] p-6 md:p-8 shadow-xl">
                                    <p className="text-[10px] font-black uppercase tracking-widest text-gray-400 mb-1">Kwota Zamówienia</p>
                                    <p className="text-3xl md:text-4xl font-black tracking-tighter mb-8">{parseFloat(order.total_price).toFixed(2)} <span className="text-xl">zł</span></p>

                                    <div className="space-y-6 mt-auto">
                                        {/* Zmiana Statusu */}
                                        <div>
                                            <p className="text-[9px] font-black uppercase text-gray-400 tracking-widest mb-2">Akcja operacyjna</p>
                                            <select 
                                                className="w-full bg-white/10 border-2 border-white/20 text-white p-4 rounded-xl font-bold text-xs outline-none"
                                                value={order.status}
                                                onChange={async (e) => {
                                                    await sb.from('orders').update({status: e.target.value}).eq('id', order.id);
                                                    refresh(); 
                                                    showToast("Status: " + e.target.value);
                                                }}
                                            >
                                                <option value="Oczekiwanie na płatność" className="text-black">⏳ Oczekiwanie na płatność</option>
                                                <option value="Opłacone - do druku" className="text-black">🖨️ Opłacone - DO DRUKU</option>
                                                <option value="W realizacji" className="text-black">🛠️ W trakcie produkcji</option>
                                                <option value="Oczekuje na kuriera" className="text-black">📦 GOTOWE - Czeka na kuriera</option> {/* NOWY STATUS */}
                                                <option value="Wysłane" className="text-black">🚚 Wysłane do klienta</option>
                                                <option value="Anulowane" className="text-black">❌ Anulowane</option>
                                            </select>
                                        </div>

                                        {/* Numer Przesyłki */}
                                        {(order.status === 'opłacone' || order.status === 'wysłane') && (
                                            <div className="pt-4 border-t border-white/10">
                                                <p className="text-[9px] font-black uppercase text-gray-400 tracking-widest mb-2">Numer InPost/DPD</p>
                                                <div className="flex gap-2">
                                                    <input 
                                                        id={`trk-${order.id}`} defaultValue={order.tracking_id || ''} placeholder="Wklej nr paczki..." 
                                                        className="w-full bg-white/10 border-2 border-white/20 text-white p-3 rounded-xl font-bold text-xs outline-none focus:border-purple-400 placeholder:text-gray-500" 
                                                    />
                                                    <button 
                                                        onClick={async () => {
                                                            const val = document.getElementById(`trk-${order.id}`).value;
                                                            await sb.from('orders').update({tracking_id: val}).eq('id', order.id);
                                                            refresh(); showToast("Zapisano list przewozowy");
                                                        }}
                                                        className="bg-purple-600 text-white px-4 rounded-xl flex items-center justify-center hover:bg-purple-500 transition-colors"
                                                    >
                                                        <Icons.Check />
                                                    </button>
                                                </div>
                                            </div>
                                        )}

                                        {/* PRZYCISK USUWANIA ZAMÓWIENIA */}
                                        <div className="pt-4 border-t border-white/5">
                                            <button 
                                                onClick={() => confirmAction(
                                                    "Usuń zamówienie", 
                                                    "Czy na pewno chcesz trwale usunąć to zamówienie z bazy danych?", 
                                                    async () => {
                                                        const { error } = await sb.from('orders').delete().eq('id', order.id);
                                                        if (error) {
                                                            showToast("Błąd usuwania: " + error.message, "error");
                                                        } else {
                                                            refresh();
                                                            showToast("Zamówienie zostało usunięte");
                                                        }
                                                    }, 
                                                    true
                                                )}
                                                className="w-full group flex items-center justify-center gap-2 py-3 text-[10px] font-black uppercase tracking-tighter text-red-400 hover:text-red-300 transition-colors"
                                            >
                                                <Icons.Trash size={14} className="group-hover:scale-110 transition-transform" />
                                                Usuń rekord zamówienia
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}

                {/* ========================================== */}
                {/* ZAKŁADKA 2: ASORTYMENT (PRODUKTY) */}
                {/* ========================================== */}
                {activeTab === 'products' && (
                    <div className="space-y-8 md:space-y-12">
                        {/* Formularz Dodawania Nowego Produktu */}
                        <div className={`${Theme.card} p-6 md:p-12 bg-purple-50/50 border-purple-100`}>
                            <h3 className="text-xl md:text-2xl font-black uppercase italic tracking-tighter mb-6 text-purple-900 flex items-center gap-2">
                                <Icons.Search /> Kreator Nowego Modelu
                            </h3>
                            <div className="grid grid-cols-1 lg:grid-cols-5 gap-6 md:gap-10">
                               {/* Upload Zdjęcia */}
                                <div 
                                    id="preview-container"
                                    className="lg:col-span-2 relative h-48 sm:h-64 lg:h-full bg-white border-2 border-dashed border-purple-200 rounded-3xl flex flex-col items-center justify-center overflow-hidden hover:bg-purple-50 transition-colors"
                                >
                                    <div id="upload-placeholder" className="flex flex-col items-center justify-center">
                                        <div className="text-purple-300 scale-150 mb-4"><Icons.Search/></div>
                                        <span className="text-[10px] font-black uppercase tracking-widest text-purple-500 text-center px-4">Wgraj miniaturę (JPG/PNG)</span>
                                    </div>

                                    {/* Ukryty obrazek podglądu, który pokażemy skryptem */}
                                    <img id="new-p-preview" className="absolute inset-0 w-full h-full object-cover hidden" />

                                    <input 
                                        type="file" 
                                        id="new-p-file" 
                                        accept="image/*"
                                        className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10" 
                                        onChange={(e) => {
                                            const file = e.target.files[0];
                                            if (file) {
                                                const reader = new FileReader();
                                                reader.onload = (event) => {
                                                    document.getElementById('new-p-preview').src = event.target.result;
                                                    document.getElementById('new-p-preview').classList.remove('hidden');
                                                    document.getElementById('upload-placeholder').classList.add('hidden');
                                                };
                                                reader.readAsDataURL(file);
                                            }
                                        }}
                                    />
                                </div>

                                {/* Dane Tekstowe */}
                                <div className="lg:col-span-3 space-y-4">
                                    <div>
                                        <label className="text-[9px] font-black uppercase tracking-widest text-gray-500 ml-2">Nazwa Produktu</label>
                                        <input id="new-p-name" placeholder="np. Figurka Smoka" className={`${Theme.input} mt-1`} />
                                    </div>
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                        <div>
                                            <label className="text-[9px] font-black uppercase tracking-widest text-gray-500 ml-2">Cena Bazowa (PLN)</label>
                                            <input id="new-p-price" type="number" placeholder="0.00" className={`${Theme.input} mt-1`} />
                                        </div>
                                        <div>
                                            <label className="text-[9px] font-black uppercase tracking-widest text-gray-500 ml-2">Kategoria</label>
                                            <select id="new-p-cat" className={`${Theme.select} mt-1`}>
                                                <option value="">Wybierz...</option>
                                                {categories.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
                                            </select>
                                        </div>
                                    </div>
                                    <div>
                                        <label className="text-[9px] font-black uppercase tracking-widest text-gray-500 ml-2">Szczegółowy Opis</label>
                                        <textarea id="new-p-desc" placeholder="Opisz materiał, wymiary..." className={`${Theme.input} mt-1 resize-y min-h-[100px]`} rows="3"></textarea>
                                    </div>
                                    <button 
                                        onClick={async () => {
                                            const file = document.getElementById('new-p-file').files[0];
                                            const name = document.getElementById('new-p-name').value;
                                            const price = document.getElementById('new-p-price').value;
                                            const cat = document.getElementById('new-p-cat').value;
                                            const desc = document.getElementById('new-p-desc').value;

                                            if(!file || !name || !price || !cat) return showToast("Błąd! Wypełnij nazwę, cenę, kategorię i dodaj plik.", "error");

                                            showToast("Upload pliku...");
                                            const fName = `prod_${Date.now()}_${file.name}`;
                                            await sb.storage.from('products').upload(fName, file);
                                            const { data: { publicUrl } } = sb.storage.from('products').getPublicUrl(fName);

                                            await sb.from('products').insert([{
                                                name, price: parseFloat(price), category: cat, description: desc, image_url: publicUrl, is_available: true, is_featured: false
                                            }]);

                                            document.getElementById('new-p-name').value = '';
                                            document.getElementById('new-p-price').value = '';
                                            document.getElementById('new-p-preview').classList.add('hidden');
                                            document.getElementById('upload-placeholder').classList.remove('hidden');
                                            document.getElementById('new-p-preview').src = '';
                                            refresh(); showToast("Dodano produkt do bazy!");
                                        }}
                                        className={`${Theme.btnPrimary} w-full`}
                                    >
                                        Stwórz Produkt
                                    </button>
                                </div>
                            </div>
                        </div>

                        {/* Lista Istniejących Produktów */}
                        <div className="space-y-4">
                            <h3 className="text-lg md:text-xl font-black uppercase italic tracking-tighter mb-4">Baza Produktów ({products.length})</h3>
                            {products.map(p => (
                                <AdminProductRow key={p.id} product={p} categories={categories} refresh={refresh} showToast={showToast} confirmAction={confirmAction} sb={sb} Theme={Theme} ToggleSwitch={ToggleSwitch} Icons={Icons} />
                            ))}
                        </div>
                    </div>
                )}

                {/* ========================================== */}
                {/* ZAKŁADKA 3: KATEGORIE */}
                {/* ========================================== */}
                {activeTab === 'categories' && (
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 md:gap-8">
                        <div className={`${Theme.card} p-6 md:p-10`}>
                            <h3 className="text-xl font-black uppercase italic tracking-tighter mb-6">Dodaj Kategorię</h3>
                            <div className="flex flex-col sm:flex-row gap-4">
                                <input id="new-cat-input" placeholder="np. Żywica SLA" className={Theme.input} />
                                <button 
                                    onClick={async () => {
                                        const val = document.getElementById('new-cat-input').value.trim();
                                        if(!val) return;
                                        const { error } = await sb.from('categories').insert([{ name: val }]);
                                        if(error) showToast("Błąd lub kategoria istnieje.", "error");
                                        else { document.getElementById('new-cat-input').value = ''; refresh(); showToast("Dodano Kategorię"); }
                                    }}
                                    className={`${Theme.btnPrimary} sm:w-auto w-full`}
                                >
                                    Zapisz
                                </button>
                            </div>
                        </div>

                        <div className={`${Theme.card} p-6 md:p-10`}>
                            <h3 className="text-xl font-black uppercase italic tracking-tighter mb-6">Lista Kategorii</h3>
                            <div className="space-y-3">
                                {categories.map(c => (
                                    <div key={c.id} className="flex justify-between items-center p-4 bg-gray-50 border border-gray-100 rounded-2xl">
                                        <span className="font-bold text-sm text-slate-800">{c.name}</span>
                                        <button 
                                            onClick={() => confirmAction("Usunąć kategorię?", "Produkty przypisane do tej kategorii mogą zniknąć z katalogu sklepu.", async () => {
                                                await sb.from('categories').delete().eq('id', c.id); refresh(); showToast("Usunięto");
                                            }, true)}
                                            className="text-rose-500 hover:bg-rose-100 p-2 rounded-xl transition-colors"
                                        >
                                            <Icons.Trash />
                                        </button>
                                    </div>
                                ))}
                                {categories.length === 0 && <p className="text-xs font-bold text-gray-400">Brak kategorii w bazie.</p>}
                            </div>
                        </div>
                    </div>
                )}

                {/* ========================================== */}
                {/* ZAKŁADKA 4: MODERACJA OPINII */}
                {/* ========================================== */}
                {activeTab === 'reviews' && (
                    <div className="space-y-4">
                        {/* Stan pusty - gdy nie ma żadnych opinii */}
                        {reviews.length === 0 ? (
                            <EmptyState icon={<Icons.Star />} title="Brak Opinii" />
                        ) : (
                            reviews.map(r => {
                                // Znalezienie produktu powiązanego z opinią
                                const prod = products.find(p => p.id === r.product_id);

                                // Funkcja usuwania z pełną obsługą błędów
                                const handleDeleteReview = () => {
                                    confirmAction(
                                        "Usuń opinię", 
                                        "Czy na pewno chcesz trwale usunąć ten komentarz? Tej operacji nie można cofnąć.", 
                                        async () => {
                                            try {
                                                // Wykonanie usunięcia w bazie Supabase
                                                const { error } = await sb
                                                    .from('reviews')
                                                    .delete()
                                                    .eq('id', r.id);

                                                if (error) throw error;

                                                // Jeśli sukces: powiadomienie i odświeżenie listy
                                                showToast("Opinia została usunięta");
                                                if (typeof refresh === 'function') refresh();

                                            } catch (err) {
                                                console.error("Błąd podczas usuwania opinii:", err.message);
                                                showToast("Błąd: Nie udało się usunąć opinii", "error");
                                            }
                                        }, 
                                        true // tryb Danger (czerwony przycisk w modalu)
                                    );
                                };

                                return (
                                    <div 
                                        key={r.id} 
                                        className={`${Theme.card} p-6 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-l-4 border-transparent hover:border-purple-400 transition-all`}
                                    >
                                        <div className="flex-1 w-full">
                                            {/* Nagłówek opinii: Autor i Model */}
                                            <div className="flex flex-wrap items-center gap-2 mb-2">
                                                <p className="text-[10px] font-black uppercase text-gray-400 tracking-widest">
                                                    Od: <span className="text-slate-900">{r.user_name || 'Anonim'}</span>
                                                </p>
                                                <span className="text-gray-300">|</span>
                                                <p className="text-[10px] font-black uppercase text-gray-400 tracking-widest">
                                                    Model: <span className="text-purple-600">{prod?.name || 'Usunięty Model'}</span>
                                                </p>
                                            </div>

                                            {/* System Gwiazdek (zawsze 5 ikon, kolorowane wg oceny) */}
                                            <div className="flex text-yellow-400 mb-3 scale-90 origin-left">
                                                {[...Array(5)].map((_, i) => (
                                                    <Icons.Star 
                                                        key={`star-${r.id}-${i}`} 
                                                        filled={i < r.rating} 
                                                    />
                                                ))}
                                            </div>

                                            {/* Treść opinii */}
                                            <div className="relative">
                                                <p className="text-sm font-medium text-slate-700 italic border-l-2 border-purple-200 pl-4 py-1 bg-slate-50/50 rounded-r-lg">
                                                    "{r.comment}"
                                                </p>
                                            </div>
                                        </div>

                                        {/* Akcje */}
                                        <button 
                                            onClick={handleDeleteReview}
                                            className={`${Theme.btnDanger} w-full sm:w-auto px-6 py-2 shrink-0 flex items-center justify-center gap-2 shadow-sm hover:shadow-md transition-shadow`}
                                        >
                                            <Icons.Trash size={16} />
                                            Usuń Wpis
                                        </button>
                                    </div>
                                );
                            })
                        )}
                    </div>
                )}
            </div>
        );
    }

    // ============================================================================
    // 7. KOMPONENT EDYCJI PRODUKTU (Wewnątrz Admina)
    // ============================================================================
    function AdminProductRow({ product, categories, refresh, showToast, confirmAction, sb, Theme, ToggleSwitch, Icons }) {
        const [isEditing, setIsEditing] = useState(false);
        const [editData, setEditData] = useState({
            name: product.name, price: product.price, category: product.category,
            is_available: product.is_available, is_featured: product.is_featured
        });
        const [variants, setVariants] = useState(product.product_variants || []);

        const saveChanges = async () => {
            await sb.from('products').update({
                name: editData.name, price: parseFloat(editData.price), category: editData.category,
                is_available: editData.is_available, is_featured: editData.is_featured
            }).eq('id', product.id);

            for (const v of variants) {
                let finalImgUrl = v.image_url;
                if (v.newFile) {
                    const fName = `var_${Date.now()}_${v.newFile.name}`;
                    await sb.storage.from('products').upload(fName, v.newFile);
                    finalImgUrl = sb.storage.from('products').getPublicUrl(fName).data.publicUrl;
                }
                const payload = {
                    product_id: product.id, color_name: v.color_name,
                    price: v.price ? parseFloat(v.price) : parseFloat(editData.price),
                    image_url: finalImgUrl, is_available: v.is_available
                };
                if (v.isNew) await sb.from('product_variants').insert([payload]);
                else await sb.from('product_variants').update(payload).eq('id', v.id);
            }

            setIsEditing(false); refresh(); showToast("Pomyślnie zaktualizowano produkt.");
        };

        if (!isEditing) {
            return (
                <div className={`${Theme.card} p-5 md:p-6 flex flex-col sm:flex-row items-center justify-between gap-4 md:gap-6 hover:border-purple-200 transition-colors`}>
                    <div className="flex items-center gap-4 w-full sm:w-auto">
                        <div className="w-16 h-16 md:w-20 md:h-20 bg-gray-50 rounded-2xl p-2 relative shrink-0">
                            <img src={product.image_url} className={`w-full h-full object-contain ${!product.is_available ? 'grayscale opacity-50' : ''}`} />
                            {!product.is_available && <div className="absolute -top-1 -right-1 w-4 h-4 bg-rose-500 rounded-full border-2 border-white"></div>}
                        </div>
                        <div className="overflow-hidden">
                            <h4 className={`text-lg md:text-xl font-black uppercase italic tracking-tighter truncate ${!product.is_available ? 'text-gray-400 line-through' : ''}`}>{product.name}</h4>
                            <p className="text-[9px] md:text-[10px] font-black uppercase tracking-widest text-gray-500 truncate">{product.price} zł • {product.category} • Wariantów: {product.product_variants?.length || 0}</p>
                        </div>
                    </div>
                    <div className="flex gap-2 md:gap-3 w-full sm:w-auto">
                        <button onClick={() => setIsEditing(true)} className={`${Theme.btnGhost} flex-1 sm:flex-none flex justify-center items-center gap-2 py-3 md:py-4`}>
                            <Icons.Edit /> <span className="sm:hidden">Edytuj</span>
                        </button>
                        <button onClick={() => confirmAction("Usunąć produkt?", "Całkowicie usuniesz produkt i jego opinie.", async () => {
                            await sb.from('products').delete().eq('id', product.id); refresh(); showToast("Usunięto model");
                        }, true)} className="w-14 h-[44px] md:h-[52px] flex items-center justify-center bg-rose-50 text-rose-500 rounded-2xl hover:bg-rose-500 hover:text-white transition-all shrink-0">
                            <Icons.Trash />
                        </button>
                    </div>
                </div>
            );
        }
        return (
            <div className={`${Theme.card} p-6 md:p-8 border-purple-300 shadow-2xl border-2 space-y-8 relative mt-8`}>
                <div className="absolute top-0 right-6 px-4 md:px-6 py-1 bg-purple-600 text-white rounded-b-2xl text-[8px] md:text-[9px] font-black uppercase tracking-widest">Edycja: {product.name}</div>
                {/* Główne dane */}
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 md:gap-8 pt-4">
                    <div className="space-y-4">
                        <p className="text-[10px] font-black uppercase text-gray-400 tracking-widest border-b border-gray-100 pb-2">Informacje Główne</p>
                        <input className={Theme.input} value={editData.name} onChange={e => setEditData({...editData, name: e.target.value})} />
                        <div className="flex gap-4">
                            <input type="number" className={Theme.input} value={editData.price} onChange={e => setEditData({...editData, price: e.target.value})} />
                            <select className={Theme.select} value={editData.category} onChange={e => setEditData({...editData, category: e.target.value})}>
                                {categories.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
                            </select>
                        </div>
                    </div>
                    <div className="space-y-4">
                        <p className="text-[10px] font-black uppercase text-gray-400 tracking-widest border-b border-gray-100 pb-2">Dostępność i Promocja</p>
                        <ToggleSwitch label="Produkt dostępny w sklepie" checked={editData.is_available} onChange={v => setEditData({...editData, is_available: v})} />
                        <ToggleSwitch label="Oznacz jako HIT (Odznaka)" checked={editData.is_featured} onChange={v => setEditData({...editData, is_featured: v})} />
                    </div>
                </div>
                {/* Warianty */}
                <div className="bg-gray-50 p-4 md:p-8 rounded-3xl border border-gray-200 space-y-6">
                    <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4">
                        <h5 className="font-black text-[10px] md:text-xs uppercase tracking-widest text-slate-900">Kolory i Warianty ({variants.length})</h5>
                        <button onClick={() => setVariants([...variants, { id: Date.now(), isNew: true, color_name: 'Nowy...', price: editData.price, is_available: true }])}
                            className="bg-slate-900 text-white px-4 py-2.5 rounded-xl text-[9px] font-black uppercase tracking-widest hover:bg-purple-600 transition-colors">
                            + Nowy Wariant
                        </button>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-6">
                        {variants.map((v, idx) => (
                            <div key={v.id} className="bg-white p-4 md:p-6 rounded-2xl border border-gray-200 shadow-sm relative group">
                                <button onClick={() => {
                                    if(!v.isNew) confirmAction("Usuń wariant", "Zniknie z bazy", async () => { await sb.from('product_variants').delete().eq('id', v.id); setVariants(variants.filter(x => x.id !== v.id)); }, true);
                                    else setVariants(variants.filter(x => x.id !== v.id));
                                }} className="absolute top-3 right-3 text-gray-300 hover:text-rose-500 z-10"><Icons.X /></button>
                                <div className="flex flex-col sm:flex-row items-center sm:items-start gap-4 mb-4">
                                    <div className="w-16 h-16 bg-gray-50 rounded-xl flex items-center justify-center border-2 border-dashed border-gray-200 relative overflow-hidden shrink-0">
                                        {v.newFile ? <img src={URL.createObjectURL(v.newFile)} className="object-cover" /> : (v.image_url ? <img src={v.image_url} className="object-cover" /> : <span className="text-[8px] font-bold text-gray-400">FOTO</span>)}
                                        <input type="file" className="absolute inset-0 opacity-0 cursor-pointer" onChange={e => { const nv = [...variants]; nv[idx].newFile = e.target.files[0]; setVariants(nv); }} />
                                    </div>
                                    <div className="w-full space-y-2">
                                        <input className={`${Theme.input} py-2 px-3 text-xs w-full`} placeholder="Nazwa koloru" value={v.color_name} onChange={e => { const nv = [...variants]; nv[idx].color_name = e.target.value; setVariants(nv); }} />
                                        <input className={`${Theme.input} py-2 px-3 text-xs w-full`} placeholder="Cena (opcja)" type="number" value={v.price} onChange={e => { const nv = [...variants]; nv[idx].price = e.target.value; setVariants(nv); }} />
                                    </div>
                                </div>
                                <div className="pt-2 border-t border-gray-100">
                                    <ToggleSwitch label="Aktywny kolor" checked={v.is_available} onChange={val => { const nv = [...variants]; nv[idx].is_available = val; setVariants(nv); }} />
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
                <div className="flex flex-col sm:flex-row gap-3 md:gap-4 pt-4 border-t border-gray-100">
                    <button onClick={saveChanges} className={`${Theme.btnPrimary} flex-1 py-4 bg-purple-600 hover:bg-purple-700`}>Zapisz Zmiany</button>
                    <button onClick={() => { setIsEditing(false); setVariants(product.product_variants || []); }} className={`${Theme.btnGhost} px-8`}>Anuluj Edycję</button>
                </div>
            </div>
        );
    }

    // Inicjalizacja React
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<App />);    
