const { useState, useEffect } = React;

window.Admin = () => {
    const [products, setProducts] = useState([]);
    const [categories, setCategories] = useState([]);
    const [variants, setVariants] = useState([]);
    const [editMode, setEditMode] = useState(null);
    const [uploading, setUploading] = useState(false);
    const [preview, setPreview] = useState(null);
    
    // Nowe pola wariantów
    const [vValue, setVValue] = useState('');
    const [vPrice, setVPrice] = useState(''); // <--- Cena wariantu

    const sb = window.supabaseClient;

    const loadData = async () => {
        const { data: p } = await sb.from('products').select('*').order('created_at', {ascending: false});
        const { data: c } = await sb.from('categories').select('*').order('name');
        setProducts(p || []);
        setCategories(c || []);
    };

    useEffect(() => { loadData(); }, []);

    const loadVariants = async (id) => {
        const { data } = await sb.from('product_variants').select('*').eq('product_id', id);
        setVariants(data || []);
    };

    const addVariant = async () => {
        if(!vValue || !editMode) return;
        await sb.from('product_variants').insert([{ 
            product_id: editMode, 
            color_name: `Kolor: ${vValue}`,
            price: vPrice ? parseFloat(vPrice) : null // Jeśli puste, będzie brać cenę główną
        }]);
        setVValue('');
        setVPrice('');
        loadVariants(editMode);
    };

    // ... (reszta funkcji jak uploadVariantImg i onSubmitForm pozostaje bez zmian) ...
    const uploadVariantImg = async (vId, file) => {
        setUploading(true);
        const fileName = `v-${Date.now()}`;
        await sb.storage.from('Product-Images').upload(fileName, file);
        const { data: { publicUrl } } = sb.storage.from('Product-Images').getPublicUrl(fileName);
        await sb.from('product_variants').update({ image_url: publicUrl }).eq('id', vId);
        loadVariants(editMode);
        setUploading(false);
    };

    const onSubmitForm = async (e) => {
        e.preventDefault();
        setUploading(true);
        const fd = new FormData(e.target);
        const imageFile = fd.get('image_file');
        let finalImageUrl = fd.get('existing_url');
        if (imageFile && imageFile.name) {
            const fileName = `${Date.now()}`;
            await sb.storage.from('Product-Images').upload(fileName, imageFile);
            const { data: { publicUrl } } = sb.storage.from('Product-Images').getPublicUrl(fileName);
            finalImageUrl = publicUrl;
        }
        const pData = { name: fd.get('name'), price: parseFloat(fd.get('price')), image_url: finalImageUrl, category: fd.get('category'), is_available: true };
        if (editMode) await sb.from('products').update(pData).eq('id', editMode);
        else await sb.from('products').insert([pData]);
        setEditMode(null); setPreview(null); e.target.reset(); loadData(); setUploading(false);
    };

    return (
        <div className="grid lg:grid-cols-3 gap-10 py-10">
            <div className="space-y-8">
                <form onSubmit={onSubmitForm} className="bg-white p-8 rounded-[3rem] border shadow-sm">
                    <h2 className="text-xl font-black mb-6 uppercase italic">{editMode ? 'Edytuj' : 'Nowy'} Produkt</h2>
                    <div className="space-y-4">
                        <div className="aspect-square bg-gray-50 rounded-[2.5rem] border-2 border-dashed flex items-center justify-center relative overflow-hidden">
                            {preview ? <img src={preview} className="w-full h-full object-cover" /> : <span className="text-[10px] font-black opacity-20">FOTO</span>}
                            <input type="file" name="image_file" onChange={(e) => setPreview(URL.createObjectURL(e.target.files[0]))} className="absolute inset-0 opacity-0 cursor-pointer" />
                        </div>
                        <input type="hidden" name="existing_url" />
                        <input name="name" placeholder="Nazwa" className="w-full p-4 bg-gray-50 rounded-2xl font-bold" required />
                        <input name="price" step="0.01" type="number" placeholder="Cena Główna" className="w-full p-4 bg-gray-50 rounded-2xl font-bold" required />
                        <select name="category" className="w-full p-4 bg-gray-50 rounded-2xl font-bold">
                            {categories.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
                        </select>
                        <button type="submit" disabled={uploading} className="w-full bg-black text-white py-5 rounded-2xl font-black uppercase">{uploading ? '...' : 'Zapisz'}</button>
                    </div>

                    {editMode && (
                        <div className="mt-8 pt-8 border-t">
                            <h3 className="text-[10px] font-black uppercase text-purple-600 mb-4">Dodaj Wariant</h3>
                            <div className="space-y-2 mb-4">
                                <input value={vValue} onChange={e => setVValue(e.target.value)} placeholder="Kolor (np. Złoty)" className="w-full p-3 bg-gray-100 rounded-xl text-xs font-bold" />
                                <input value={vPrice} onChange={e => setVPrice(e.target.value)} type="number" placeholder="Cena tego wariantu (opcjonalnie)" className="w-full p-3 bg-gray-100 rounded-xl text-xs font-bold" />
                                <button type="button" onClick={addVariant} className="w-full bg-black text-white py-3 rounded-xl font-black">DODAJ WARIANT</button>
                            </div>
                            <div className="space-y-2">
                                {variants.map(v => (
                                    <div key={v.id} className="flex items-center justify-between bg-gray-50 p-2 rounded-xl border">
                                        <div className="flex items-center gap-2">
                                            <div className="w-8 h-8 rounded bg-gray-200 relative overflow-hidden">
                                                {v.image_url && <img src={v.image_url} className="w-full h-full object-cover" />}
                                                <input type="file" onChange={(e) => uploadVariantImg(v.id, e.target.files[0])} className="absolute inset-0 opacity-0 cursor-pointer" />
                                            </div>
                                            <div>
                                                <div className="text-[10px] font-black uppercase">{v.color_name}</div>
                                                <div className="text-[9px] font-bold text-purple-600">{v.price ? `${v.price} zł` : 'Cena główna'}</div>
                                            </div>
                                        </div>
                                        <button type="button" onClick={async () => { await sb.from('product_variants').delete().eq('id', v.id); loadVariants(editMode); }} className="text-red-500 font-bold px-2">✕</button>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </form>
            </div>

            <div className="lg:col-span-2 space-y-4">
                {products.map(p => (
                    <div key={p.id} className="flex items-center gap-4 bg-white p-4 rounded-[2.5rem] border border-gray-100">
                        <img src={p.image_url} className="w-16 h-16 rounded-2xl object-cover" />
                        <div className="flex-1">
                            <h4 className="font-bold">{p.name}</h4>
                            <p className="text-[10px] font-black text-purple-600 uppercase">{p.price} zł</p>
                        </div>
                        <div className="flex gap-2">
                            <button onClick={() => { setEditMode(p.id); setPreview(p.image_url); loadVariants(p.id); setTimeout(() => { const f = document.querySelector('form'); f.name.value = p.name; f.price.value = p.price; f.category.value = p.category; f.existing_url.value = p.image_url; }, 50); }} className="bg-gray-100 px-4 py-2 rounded-xl font-bold text-[10px]">EDYTUJ</button>
                            <button onClick={async () => { if(confirm("Usunąć?")) { await sb.from('products').delete().eq('id', p.id); loadData(); } }} className="bg-red-50 text-red-500 px-4 py-2 rounded-xl font-bold text-[10px]">USUŃ</button>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};
