
import React, { useState, useEffect, useMemo, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { createClient } from '@supabase/supabase-js';
import { 
  Search, MapPin, Phone, Instagram, Facebook, Car, Fuel, Gauge, Calendar, 
  Plus, Trash2, Edit3, LogOut, User, ChevronRight, ShieldCheck, X, Menu, 
  Lock, Mail, CheckCircle, AlertCircle, Loader2, Upload, Camera, Images, Trash,
  Settings, Save, Palette, Globe, ImagePlus, MessageCircle
} from 'lucide-react';

/**
 * INSTRUÇÕES PARA O PATRÃO (SUPABASE):
 * 1. Acesse o SQL Editor no painel do seu Supabase.
 * 2. Copie, cole e execute o código abaixo para criar/atualizar as tabelas do site:
 * 
 * CREATE TABLE IF NOT EXISTS public.vehicles (
 *   id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
 *   make text NOT NULL,
 *   model text NOT NULL,
 *   year_model integer NOT NULL,
 *   year_fab integer NOT NULL,
 *   price numeric NOT NULL,
 *   mileage integer NOT NULL,
 *   fuel_type text NOT NULL,
 *   description text,
 *   images text[] DEFAULT '{}',
 *   status text DEFAULT 'available',
 *   created_at timestamp with time zone DEFAULT timezone('utc'::text, now()) NOT NULL
 * );
 * 
 * CREATE TABLE IF NOT EXISTS public.site_settings (
 *   id text PRIMARY KEY,
 *   site_name text DEFAULT 'Lameira Multimarcas',
 *   address text DEFAULT 'Estrada da posse 1200, Rio de Janeiro - RJ, 23088-000',
 *   phone text DEFAULT '21 96449-2682',
 *   whatsapp text DEFAULT '5521964492682',
 *   instagram_url text DEFAULT 'https://www.instagram.com/lameiras.multimarcas',
 *   facebook_url text DEFAULT 'https://www.facebook.com/lameirasmultimarcas',
 *   logo_url text,
 *   primary_color text DEFAULT '#fcc201',
 *   hero_title text DEFAULT 'LAMEIRAS MULTIMARCAS',
 *   hero_subtitle text DEFAULT 'Qualidade, procedência e as melhores condições da Estrada da Posse.',
 *   footer_description text DEFAULT 'A melhor experiência na compra e venda de seminovos no Rio de Janeiro.'
 * );
 * 
 * -- Criar a configuração inicial do site com os links corretos
 * INSERT INTO public.site_settings (id, instagram_url, facebook_url, whatsapp) 
 * VALUES ('global', 'https://www.instagram.com/lameiras.multimarcas', 'https://www.facebook.com/lameirasmultimarcas', '5521964492682') 
 * ON CONFLICT (id) DO UPDATE SET 
 * instagram_url = EXCLUDED.instagram_url, 
 * facebook_url = EXCLUDED.facebook_url,
 * whatsapp = EXCLUDED.whatsapp;
 * 
 * 3. Vá em 'Storage' no menu lateral, crie um novo bucket chamado 'vehicles' e mude o acesso para 'Public'.
 */

const supabaseUrl = 'https://lehlswirraoqiioazdkg.supabase.co';
const supabaseKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImxlaGxzd2lycmFvcWlpb2F6ZGtnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Njk4OTE4NTUsImV4cCI6MjA4NTQ2Nzg1NX0.0CbI9nfut-mW9NtcmNwXFmpfTABPVG9unfVzAmAAm-4';
const supabase = createClient(supabaseUrl, supabaseKey);

type FuelType = 'Gasolina' | 'Etanol' | 'Flex' | 'Diesel' | 'GNV' | 'Híbrido' | 'Elétrico';

interface Vehicle {
  id: string;
  make: string;
  model: string;
  year_model: number;
  year_fab: number;
  price: number;
  mileage: number;
  fuel_type: FuelType;
  description: string;
  images: string[];
  status: 'available' | 'sold';
  created_at?: string;
}

interface SiteSettings {
  id: string;
  site_name: string;
  address: string;
  phone: string;
  whatsapp: string;
  instagram_url: string;
  facebook_url: string;
  logo_url: string | null;
  primary_color: string;
  hero_title: string;
  hero_subtitle: string;
  footer_description: string;
}

const Logo = ({ className = "h-10", settings }: { className?: string, settings?: SiteSettings }) => {
  if (settings?.logo_url) {
    return <img src={settings.logo_url} alt={settings.site_name} className={`${className} object-contain`} />;
  }
  return (
    <svg viewBox="0 0 450 140" className={className} xmlns="http://www.w3.org/2000/svg">
      <defs>
        <clipPath id="logoClip">
          <rect x="5" y="5" width="440" height="130" rx="20" />
        </clipPath>
      </defs>
      <rect x="5" y="5" width="440" height="130" rx="20" fill={settings?.primary_color || "#fcc201"} stroke="#1a1a1a" strokeWidth="10" />
      <g clipPath="url(#logoClip)">
        <path d="M 360 -10 C 330 40, 420 90, 390 150 L 460 150 L 460 -10 Z" fill="#1a1a1a" />
        <path d="M 360 -10 C 330 40, 420 90, 390 150" stroke="white" strokeWidth="4" strokeDasharray="10,12" fill="none" />
      </g>
      <text x="35" y="102" fontFamily="'Arial Black', 'Inter', sans-serif" fontWeight="900" fontSize="88" fill="#1a1a1a" letterSpacing="-5">
        {settings?.site_name.split(' ')[0] || 'Lameira'}
      </text>
    </svg>
  );
};

const VehicleCard: React.FC<{ vehicle: Vehicle, settings?: SiteSettings }> = ({ vehicle, settings }) => {
  const adLink = `${window.location.origin}/?veiculo=${vehicle.id}`;
  const messageText = `Olá! Vi o anúncio no site e tenho interesse neste veículo:
  
📌 *${vehicle.make} ${vehicle.model}*
📅 Ano: ${vehicle.year_fab}/${vehicle.year_model}
⛽ Combustível: ${vehicle.fuel_type}
🛣️ KM: ${vehicle.mileage.toLocaleString('pt-BR')}
💰 Valor: *R$ ${vehicle.price.toLocaleString('pt-BR')}*

🔗 Link do anúncio: ${adLink}`;

  const message = encodeURIComponent(messageText);
  const waNumber = settings?.whatsapp || '5521964492682';
  const url = `https://wa.me/${waNumber}?text=${message}`;

  return (
    <div className="bg-white rounded-xl overflow-hidden shadow-md hover:shadow-xl transition-all border border-gray-100 group relative">
      <div className="relative h-56 overflow-hidden bg-gray-200">
        <img 
          src={vehicle.images?.[0] || 'https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?auto=format&fit=crop&q=80&w=800'} 
          alt={vehicle.model} 
          className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" 
        />
        <div 
          className="absolute top-4 right-4 text-black font-bold px-3 py-1 rounded-full text-sm shadow-sm"
          style={{ backgroundColor: settings?.primary_color || '#fcc201' }}
        >
          {vehicle.year_model}
        </div>
        
        {vehicle.images && vehicle.images.length > 1 && (
          <div className="absolute bottom-4 right-4 bg-black/60 text-white text-[10px] font-black px-2 py-1 rounded-md flex items-center gap-1 backdrop-blur-md">
            <Images size={12} /> {vehicle.images.length}
          </div>
        )}

        {vehicle.status === 'sold' && (
          <div className="absolute inset-0 bg-black/60 flex items-center justify-center">
             <span className="border-4 border-white text-white font-black text-2xl uppercase p-2 -rotate-12">Vendido</span>
          </div>
        )}
      </div>
      <div className="p-5">
        <h3 className="font-black text-lg uppercase italic">{vehicle.make} {vehicle.model}</h3>
        <p className="text-gray-500 text-xs font-bold uppercase mb-4">{vehicle.fuel_type}</p>
        <div className="flex justify-between items-center mb-6">
           <p className="text-2xl font-black text-gray-900">R$ {vehicle.price.toLocaleString('pt-BR')}</p>
           <div className="flex items-center gap-2 text-xs text-gray-500 font-bold"><Gauge size={14} /> {vehicle.mileage.toLocaleString('pt-BR')} km</div>
        </div>
        <a href={url} target="_blank" rel="noreferrer" className="flex items-center justify-center gap-2 bg-green-600 hover:bg-green-700 text-white font-black py-3 rounded-lg transition-all uppercase italic tracking-tighter shadow-lg">
          <Phone size={18} /> Tenho Interesse
        </a>
      </div>
    </div>
  );
};

const App = () => {
  const [activeTab, setActiveTab] = useState<'home' | 'estoque' | 'admin' | 'contato' | 'politicas'>('home');
  const [adminSubTab, setAdminSubTab] = useState<'vehicles' | 'settings'>('vehicles');
  const [settings, setSettings] = useState<SiteSettings | null>(null);
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState<any>(null);
  const [showLGPD, setShowLGPD] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  
  const [loginEmail, setLoginEmail] = useState('');
  const [loginPassword, setLoginPassword] = useState('');
  const [loginError, setLoginError] = useState('');

  const [showModal, setShowModal] = useState(false);
  const [saving, setSaving] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const logoInputRef = useRef<HTMLInputElement>(null);
  const directLogoInputRef = useRef<HTMLInputElement>(null);

  const [formData, setFormData] = useState<Partial<Vehicle>>({
    make: '', model: '', year_model: 2024, year_fab: 2024, price: 0, mileage: 0, fuel_type: 'Flex', status: 'available', images: []
  });

  const [settingsForm, setSettingsForm] = useState<Partial<SiteSettings>>({});

  useEffect(() => {
    fetchInitialData();
    supabase.auth.getSession().then(({ data: { session } }) => setUser(session?.user ?? null));
    const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => setUser(session?.user ?? null));
    return () => subscription.unsubscribe();
  }, []);

  const fetchInitialData = async () => {
    setLoading(true);
    const [vehiclesRes, settingsRes] = await Promise.all([
      supabase.from('vehicles').select('*').order('created_at', { ascending: false }),
      supabase.from('site_settings').select('*').eq('id', 'global').single()
    ]);
    
    if (vehiclesRes.data) setVehicles(vehiclesRes.data);
    if (settingsRes.data) {
      setSettings(settingsRes.data);
      setSettingsForm(settingsRes.data);
    }
    setLoading(false);
  };

  const isDiego = user?.email === 'diegocarreiroonline@gmail.com';

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoginError('');
    const { data, error } = await supabase.auth.signInWithPassword({ email: loginEmail, password: loginPassword });
    if (error) setLoginError('Erro de acesso. Verifique seu email e senha.');
    else setUser(data.user);
  };

  const handleLogout = async () => {
    await supabase.auth.signOut();
    setUser(null);
    toggleTab('home');
  };

  const handleSaveSettings = async (e?: React.FormEvent, newSettings?: Partial<SiteSettings>) => {
    if (e) e.preventDefault();
    setSaving(true);
    const updatedData = newSettings || settingsForm;
    const { error } = await supabase.from('site_settings').update(updatedData).eq('id', 'global');
    if (!error) {
      setSettings(prev => ({ ...prev, ...updatedData } as SiteSettings));
      setSettingsForm(prev => ({ ...prev, ...updatedData }));
      if (!newSettings) alert('Configurações atualizadas com sucesso!');
    } else {
      alert('Erro ao salvar: ' + error.message);
    }
    setSaving(false);
  };

  const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files?.[0]) return;
    const file = e.target.files[0];
    const fileExt = file.name.split('.').pop();
    const filePath = `site-assets/logo-${Math.random()}.${fileExt}`;

    setSaving(true);
    const { error: uploadError } = await supabase.storage.from('vehicles').upload(filePath, file);
    if (uploadError) {
      setSaving(false);
      return alert('Erro upload logo');
    }

    const { data } = supabase.storage.from('vehicles').getPublicUrl(filePath);
    await handleSaveSettings(undefined, { logo_url: data.publicUrl });
    setSaving(false);
  };

  const handleRemoveLogo = async () => {
    if (confirm('Deseja remover a imagem da logo e voltar para o padrão?')) {
      await handleSaveSettings(undefined, { logo_url: null });
    }
  };

  const uploadImages = async (files: File[]): Promise<string[]> => {
    const uploadPromises = files.map(async (file) => {
      const fileExt = file.name.split('.').pop();
      const fileName = `${Math.random()}.${fileExt}`;
      const filePath = `vehicle-photos/${fileName}`;
      const { error } = await supabase.storage.from('vehicles').upload(filePath, file);
      if (error) return null;
      const { data } = supabase.storage.from('vehicles').getPublicUrl(filePath);
      return data.publicUrl;
    });
    const results = await Promise.all(uploadPromises);
    return results.filter((url): url is string => url !== null);
  };

  const closeModal = () => {
    setShowModal(false);
    setEditingId(null);
    setFormData({
      make: '', model: '', year_model: 2024, year_fab: 2024, price: 0, mileage: 0, fuel_type: 'Flex', status: 'available', images: []
    });
    setSelectedFiles([]);
  };

  const handleSaveVehicle = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      let currentImages = formData.images || [];
      if (selectedFiles.length > 0) {
        const newUrls = await uploadImages(selectedFiles);
        currentImages = [...currentImages, ...newUrls];
      }
      if (currentImages.length === 0) throw new Error('Mínimo de 1 foto.');
      
      const vehicleData = { ...formData, images: currentImages };
      const { error } = editingId 
        ? await supabase.from('vehicles').update(vehicleData).eq('id', editingId)
        : await supabase.from('vehicles').insert([vehicleData]);
      
      if (error) throw error;
      fetchInitialData();
      closeModal();
    } catch (err: any) {
      alert(err.message);
    } finally { setSaving(false); }
  };

  const toggleTab = (tab: any) => {
    setActiveTab(tab);
    window.scrollTo(0, 0);
    setIsMenuOpen(false);
  };

  const primaryColor = settings?.primary_color || '#fcc201';

  return (
    <div className="min-h-screen flex flex-col font-['Inter']" style={{ '--primary': primaryColor } as any}>
      {/* HEADER TOP BAR */}
      <div className="bg-black-900 text-white text-[10px] sm:text-xs py-2 px-4 flex justify-between items-center border-b border-white/10">
        <div className="flex items-center gap-4"><span className="flex items-center gap-1"><MapPin size={12} style={{ color: primaryColor }} /> {settings?.address}</span></div>
        <div className="flex items-center gap-4"><a href={`tel:${settings?.phone}`} className="flex items-center gap-1 hover:text-primary transition-colors"><Phone size={12} style={{ color: primaryColor }} /> {settings?.phone}</a></div>
      </div>

      {/* NAVIGATION */}
      <nav className="sticky top-0 z-40 bg-white shadow-sm border-b border-gray-200 px-4 sm:px-8 py-4">
        <div className="max-w-7xl mx-auto flex justify-between items-center">
          <div className="flex items-center gap-3 cursor-pointer group relative">
             <div onClick={() => toggleTab('home')}>
                <Logo className="h-10 sm:h-12 md:h-14 group-hover:scale-105 transition-transform" settings={settings || undefined} />
             </div>
             
             {/* CONTROLES DE LOGO PARA O DIEGO */}
             {isDiego && (
               <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/40 rounded-xl gap-2 backdrop-blur-[2px]">
                 <button 
                   onClick={() => directLogoInputRef.current?.click()} 
                   className="p-2 bg-primary text-black rounded-full hover:scale-110 transition-transform shadow-lg"
                   title="Mudar Imagem"
                 >
                   <ImagePlus size={18} />
                 </button>
                 {settings?.logo_url && (
                   <button 
                     onClick={handleRemoveLogo} 
                     className="p-2 bg-red-500 text-white rounded-full hover:scale-110 transition-transform shadow-lg"
                     title="Remover e Voltar Padrão"
                   >
                     <Trash size={18} />
                   </button>
                 )}
                 <input ref={directLogoInputRef} type="file" className="hidden" accept="image/*" onChange={handleLogoUpload} />
               </div>
             )}
          </div>
          
          <div className="hidden md:flex items-center gap-8 font-semibold text-sm">
            <button onClick={() => toggleTab('home')} className={`${activeTab === 'home' ? 'text-primary' : 'text-gray-600'} hover:text-primary transition-colors uppercase tracking-widest`}>Início</button>
            <button onClick={() => toggleTab('estoque')} className={`${activeTab === 'estoque' ? 'text-primary' : 'text-gray-600'} hover:text-primary transition-colors uppercase tracking-widest`}>Estoque</button>
            <button onClick={() => toggleTab('contato')} className={`${activeTab === 'contato' ? 'text-primary' : 'text-gray-600'} hover:text-primary transition-colors uppercase tracking-widest`}>Contato</button>
            <button onClick={() => toggleTab('admin')} className="flex items-center gap-2 bg-gray-100 px-4 py-2 rounded-full hover:bg-gray-200 transition-colors">
              <User size={18} /> {user ? 'Painel Lameiras' : 'Entrar'}
            </button>
          </div>
          <button className="md:hidden p-2" onClick={() => setIsMenuOpen(!isMenuOpen)}>{isMenuOpen ? <X /> : <Menu />}</button>
        </div>
      </nav>

      <main className="flex-grow">
        {activeTab === 'home' && (
          <div>
            <section className="relative h-[600px] flex items-center justify-center text-white overflow-hidden">
              <img src="https://images.unsplash.com/photo-1492144534655-ae79c964c9d7?auto=format&fit=crop&q=80&w=1920" className="absolute inset-0 w-full h-full object-cover brightness-[0.4]" />
              <div className="relative z-10 text-center px-4 max-w-4xl">
                <h1 className="text-4xl md:text-7xl font-black mb-6 uppercase italic tracking-tighter leading-none">{settings?.hero_title}</h1>
                <p className="text-lg md:text-2xl mb-10 font-medium text-gray-200">{settings?.hero_subtitle}</p>
                <button onClick={() => toggleTab('estoque')} className="text-black font-black px-12 py-5 rounded-full text-xl hover:scale-105 transition-transform shadow-2xl uppercase italic" style={{ backgroundColor: primaryColor }}>Ver Ofertas</button>
              </div>
            </section>
            
            <section className="max-w-7xl mx-auto py-20 px-4">
               <div className="flex justify-between items-end mb-12">
                  <div><h2 className="text-4xl font-black italic tracking-tighter uppercase leading-none">Últimos <span className="text-primary">Anúncios</span></h2><div className="h-2 w-32 mt-3" style={{ backgroundColor: primaryColor }}></div></div>
               </div>
               {loading ? (
                 <div className="flex justify-center py-20"><Loader2 className="animate-spin text-primary" size={48} /></div>
               ) : (
                 <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-10">
                    {vehicles.slice(0, 6).map(v => (
                      <VehicleCard key={v.id} vehicle={v} settings={settings || undefined} />
                    ))}
                 </div>
               )}
            </section>
          </div>
        )}

        {activeTab === 'estoque' && (
          <section className="max-w-7xl mx-auto py-16 px-4">
             <div className="flex flex-col md:flex-row justify-between items-center gap-8 mb-16">
               <h1 className="text-5xl font-black italic tracking-tighter uppercase">Estoque <span className="text-primary">Completo</span></h1>
               <div className="relative w-full md:w-[450px]">
                  <Search className="absolute left-5 top-1/2 -translate-y-1/2 text-gray-400" size={24} />
                  <input type="text" placeholder="Busque por marca ou modelo..." className="w-full bg-white border-2 border-gray-100 rounded-full py-5 pl-14 pr-6 focus:ring-4 outline-none shadow-xl text-lg font-medium" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
               </div>
             </div>
             <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-10">
                {vehicles.filter(v => v.model.toLowerCase().includes(searchTerm.toLowerCase())).map(v => <VehicleCard key={v.id} vehicle={v} settings={settings || undefined} />)}
             </div>
          </section>
        )}

        {activeTab === 'admin' && (
          <section className="max-w-7xl mx-auto py-16 px-4">
             {!user ? (
               <div className="max-w-md mx-auto bg-white rounded-3xl shadow-2xl p-10 border border-gray-100">
                  <h2 className="text-3xl font-black italic uppercase tracking-tighter mb-8 text-center">Acesso Painel</h2>
                  <form onSubmit={handleLogin} className="space-y-4">
                     <input type="email" value={loginEmail} onChange={e => setLoginEmail(e.target.value)} className="w-full p-4 bg-gray-50 rounded-2xl border" placeholder="Email" required />
                     <input type="password" value={loginPassword} onChange={e => setLoginPassword(e.target.value)} className="w-full p-4 bg-gray-50 rounded-2xl border" placeholder="Senha" required />
                     <button className="w-full bg-black text-white font-black py-5 rounded-2xl hover:bg-primary hover:text-black uppercase italic transition-all">Entrar</button>
                  </form>
               </div>
             ) : (
               <div className="space-y-8">
                  <div className="flex flex-wrap items-center justify-between gap-4 bg-white p-6 rounded-3xl shadow-xl border border-gray-100">
                    <div className="flex gap-4">
                       <button onClick={() => setAdminSubTab('vehicles')} className={`px-6 py-3 rounded-2xl font-black uppercase italic transition-all flex items-center gap-2 ${adminSubTab === 'vehicles' ? 'bg-black text-white' : 'bg-gray-100 text-gray-500'}`}>
                          <Car size={20}/> Veículos
                       </button>
                       {isDiego && (
                        <button onClick={() => setAdminSubTab('settings')} className={`px-6 py-3 rounded-2xl font-black uppercase italic transition-all flex items-center gap-2 ${adminSubTab === 'settings' ? 'bg-black text-white' : 'bg-gray-100 text-gray-500'}`}>
                           <Settings size={20}/> Configurar Site
                        </button>
                       )}
                    </div>
                    <button onClick={handleLogout} className="px-6 py-3 bg-red-50 text-red-600 rounded-2xl font-bold flex items-center gap-2 hover:bg-red-100"><LogOut size={20}/> Sair</button>
                  </div>

                  {adminSubTab === 'vehicles' ? (
                    <div className="bg-white rounded-3xl p-10 shadow-2xl border border-gray-100">
                       <div className="flex justify-between items-center mb-8">
                          <h3 className="text-2xl font-black uppercase italic">Meus Anúncios</h3>
                          <button onClick={() => { setEditingId(null); setFormData({ make: '', model: '', year_model: 2024, year_fab: 2024, price: 0, mileage: 0, fuel_type: 'Flex', status: 'available', images: [] }); setSelectedFiles([]); setShowModal(true); }} className="bg-primary text-black font-black px-8 py-4 rounded-2xl flex items-center gap-2 uppercase italic shadow-lg hover:scale-105 transition-transform"><Plus size={24} /> Novo Anúncio</button>
                       </div>
                       <div className="overflow-x-auto">
                          <table className="w-full">
                             <thead><tr className="text-left text-xs font-black uppercase text-gray-400 border-b border-gray-50"><th className="pb-4">Foto</th><th className="pb-4">Veículo</th><th className="pb-4">Preço</th><th className="pb-4">Ações</th></tr></thead>
                             <tbody className="divide-y divide-gray-100">
                                {vehicles.map(v => (
                                   <tr key={v.id} className="hover:bg-gray-50/50">
                                      <td className="py-4"><img src={v.images[0]} className="w-16 h-12 object-cover rounded-lg" /></td>
                                      <td className="py-4 font-bold">{v.make} {v.model}</td>
                                      <td className="py-4 font-black text-primary">R$ {v.price.toLocaleString('pt-BR')}</td>
                                      <td className="py-4">
                                         <div className="flex gap-2">
                                            <button onClick={() => { setFormData(v); setEditingId(v.id); setShowModal(true); }} className="p-2 bg-blue-50 text-blue-600 rounded-lg"><Edit3 size={18}/></button>
                                            <button onClick={async () => { if(confirm('Excluir?')) { await supabase.from('vehicles').delete().eq('id', v.id); fetchInitialData(); }}} className="p-2 bg-red-50 text-red-600 rounded-lg"><Trash2 size={18}/></button>
                                         </div>
                                      </td>
                                   </tr>
                                ))}
                             </tbody>
                          </table>
                       </div>
                    </div>
                  ) : (
                    <div className="bg-white rounded-3xl p-10 shadow-2xl border border-gray-100">
                       <h3 className="text-3xl font-black uppercase italic mb-10 flex items-center gap-4">
                          <Globe className="text-primary" size={32} /> Customizar o Site (CMS)
                       </h3>
                       <form onSubmit={handleSaveSettings} className="space-y-12">
                          <section className="grid grid-cols-1 md:grid-cols-2 gap-10">
                             <div className="space-y-6">
                                <h4 className="font-black uppercase text-sm border-l-4 border-primary pl-3">Identidade Visual</h4>
                                <div>
                                   <label className="block text-[10px] font-black uppercase mb-2">Logo Personalizada (Opcional)</label>
                                   <div className="flex items-center gap-4">
                                      <div className="w-20 h-20 bg-gray-100 rounded-2xl flex items-center justify-center border overflow-hidden">
                                         {settingsForm.logo_url ? <img src={settingsForm.logo_url} className="w-full h-full object-contain" /> : <Camera className="text-gray-300" />}
                                      </div>
                                      <button type="button" onClick={() => logoInputRef.current?.click()} className="text-xs bg-black text-white px-4 py-2 rounded-xl font-bold hover:bg-primary transition-colors uppercase">Mudar Logo</button>
                                      <input ref={logoInputRef} type="file" className="hidden" onChange={handleLogoUpload} />
                                   </div>
                                </div>
                                <div>
                                   <label className="block text-[10px] font-black uppercase mb-2">Cor Principal do Site</label>
                                   <div className="flex items-center gap-3">
                                      <input type="color" value={settingsForm.primary_color} onChange={e => setSettingsForm({...settingsForm, primary_color: e.target.value})} className="w-12 h-12 rounded-xl border-none cursor-pointer" />
                                      <span className="text-xs font-mono uppercase font-bold">{settingsForm.primary_color}</span>
                                   </div>
                                </div>
                             </div>
                             
                             <div className="space-y-6">
                                <h4 className="font-black uppercase text-sm border-l-4 border-primary pl-3">Informações de Contato</h4>
                                <div><label className="block text-[10px] font-black uppercase mb-2">Nome da Empresa</label><input type="text" value={settingsForm.site_name} onChange={e => setSettingsForm({...settingsForm, site_name: e.target.value})} className="w-full p-4 bg-gray-50 rounded-xl border font-bold" /></div>
                                <div><label className="block text-[10px] font-black uppercase mb-2">Endereço Completo</label><input type="text" value={settingsForm.address} onChange={e => setSettingsForm({...settingsForm, address: e.target.value})} className="w-full p-4 bg-gray-50 rounded-xl border font-bold" /></div>
                                <div className="grid grid-cols-2 gap-4">
                                   <div><label className="block text-[10px] font-black uppercase mb-2">Telefone</label><input type="text" value={settingsForm.phone} onChange={e => setSettingsForm({...settingsForm, phone: e.target.value})} className="w-full p-4 bg-gray-50 rounded-xl border font-bold" /></div>
                                   <div><label className="block text-[10px] font-black uppercase mb-2">WhatsApp (só números)</label><input type="text" value={settingsForm.whatsapp} onChange={e => setSettingsForm({...settingsForm, whatsapp: e.target.value})} className="w-full p-4 bg-gray-50 rounded-xl border font-bold" /></div>
                                </div>
                             </div>
                          </section>

                          <section className="space-y-6">
                             <h4 className="font-black uppercase text-sm border-l-4 border-primary pl-3">Conteúdo do Site (Hero & Footer)</h4>
                             <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div><label className="block text-[10px] font-black uppercase mb-2">Título Principal (Banner)</label><input type="text" value={settingsForm.hero_title} onChange={e => setSettingsForm({...settingsForm, hero_title: e.target.value})} className="w-full p-4 bg-gray-50 rounded-xl border font-bold" /></div>
                                <div><label className="block text-[10px] font-black uppercase mb-2">Subtítulo (Banner)</label><input type="text" value={settingsForm.hero_subtitle} onChange={e => setSettingsForm({...settingsForm, hero_subtitle: e.target.value})} className="w-full p-4 bg-gray-50 rounded-xl border font-bold" /></div>
                                <div className="col-span-full"><label className="block text-[10px] font-black uppercase mb-2">Descrição do Rodapé</label><textarea value={settingsForm.footer_description} onChange={e => setSettingsForm({...settingsForm, footer_description: e.target.value})} className="w-full p-4 bg-gray-50 rounded-xl border font-bold h-24" /></div>
                             </div>
                          </section>

                          <button disabled={saving} className="bg-black text-white font-black px-12 py-5 rounded-2xl flex items-center gap-3 uppercase italic text-lg shadow-xl hover:bg-primary hover:text-black transition-all">
                             {saving ? <Loader2 className="animate-spin" /> : <Save />} Salvar Todas as Alterações
                          </button>
                       </form>
                    </div>
                  )}
               </div>
             )}
          </section>
        )}
      </main>

      <footer className="bg-black-900 text-white pt-24 pb-10 px-4">
        <div className="max-w-7xl mx-auto text-center md:text-left">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-20 mb-20 border-b border-white/5 pb-20">
             <div className="flex flex-col items-center md:items-start gap-6">
               <Logo className="h-14" settings={settings || undefined} />
               <p className="text-gray-400 text-sm font-medium leading-relaxed max-w-xs">{settings?.footer_description}</p>
             </div>
             <div>
                <h4 className="text-primary font-black uppercase italic mb-6">Localização</h4>
                <p className="text-gray-400 font-bold">{settings?.address}</p>
             </div>
             <div>
                <h4 className="text-primary font-black uppercase italic mb-6">Siga-nos nas Redes Sociais</h4>
                <div className="flex justify-center md:justify-start gap-4">
                   <a href={settings?.instagram_url} target="_blank" rel="noreferrer" className="p-3 bg-white/5 rounded-xl hover:text-primary transition-colors border border-white/10 flex items-center justify-center w-12 h-12" title="Instagram">
                     <Instagram size={24} />
                   </a>
                   <a href={settings?.facebook_url} target="_blank" rel="noreferrer" className="p-3 bg-white/5 rounded-xl hover:text-primary transition-colors border border-white/10 flex items-center justify-center w-12 h-12" title="Facebook">
                     <Facebook size={24} />
                   </a>
                   <a href={`https://wa.me/${settings?.whatsapp || '5521964492682'}`} target="_blank" rel="noreferrer" className="p-3 bg-white/5 rounded-xl hover:text-primary transition-colors border border-white/10 flex items-center justify-center w-12 h-12" title="WhatsApp">
                     <MessageCircle size={24} />
                   </a>
                </div>
             </div>
          </div>
          <div className="flex flex-col md:flex-row justify-between items-center text-[10px] text-gray-600 uppercase font-black italic tracking-widest gap-4">
            <p>© {new Date().getFullYear()} {settings?.site_name} - Todos os direitos reservados.</p>
            <p className="flex items-center gap-2">Proteção de Dados <ShieldCheck size={14} className="text-primary" /> LGPD Ativa</p>
          </div>
        </div>
      </footer>

      {showModal && (
        <div className="fixed inset-0 z-[100] bg-black/80 backdrop-blur-sm flex items-center justify-center p-4">
           <div className="bg-white w-full max-w-2xl rounded-[2.5rem] shadow-2xl overflow-hidden max-h-[90vh] overflow-y-auto">
              <div className="bg-primary p-8 flex justify-between items-center">
                 <h2 className="text-2xl font-black italic uppercase tracking-tighter">Gerenciar Anúncio</h2>
                 <button onClick={closeModal} className="p-2 bg-black/10 rounded-full"><X/></button>
              </div>
              <form onSubmit={handleSaveVehicle} className="p-8 space-y-6">
                 <div className="grid grid-cols-2 gap-4">
                    <input type="text" placeholder="Marca" value={formData.make} onChange={e => setFormData({...formData, make: e.target.value})} className="p-4 bg-gray-50 border rounded-xl" required />
                    <input type="text" placeholder="Modelo" value={formData.model} onChange={e => setFormData({...formData, model: e.target.value})} className="p-4 bg-gray-50 border rounded-xl" required />
                 </div>
                 <div className="grid grid-cols-2 gap-4">
                    <input type="number" placeholder="Ano Fab." value={formData.year_fab} onChange={e => setFormData({...formData, year_fab: parseInt(e.target.value)})} className="p-4 bg-gray-50 border rounded-xl" required />
                    <input type="number" placeholder="Ano Mod." value={formData.year_model} onChange={e => setFormData({...formData, year_model: parseInt(e.target.value)})} className="p-4 bg-gray-50 border rounded-xl" required />
                 </div>
                 <div className="grid grid-cols-2 gap-4">
                    <input type="number" placeholder="Preço" value={formData.price} onChange={e => setFormData({...formData, price: parseFloat(e.target.value)})} className="p-4 bg-gray-50 border rounded-xl" required />
                    <input type="number" placeholder="Quilometragem" value={formData.mileage} onChange={e => setFormData({...formData, mileage: parseInt(e.target.value)})} className="p-4 bg-gray-50 border rounded-xl" required />
                 </div>
                 <select value={formData.fuel_type} onChange={e => setFormData({...formData, fuel_type: e.target.value as FuelType})} className="w-full p-4 bg-gray-50 border rounded-xl">
                    <option value="Gasolina">Gasolina</option>
                    <option value="Etanol">Etanol</option>
                    <option value="Flex">Flex</option>
                    <option value="Diesel">Diesel</option>
                    <option value="GNV">GNV</option>
                    <option value="Híbrido">Híbrido</option>
                    <option value="Elétrico">Elétrico</option>
                 </select>
                 
                 <div className="bg-gray-50 border-2 border-dashed rounded-xl p-6 text-center">
                    <button type="button" onClick={() => fileInputRef.current?.click()} className="bg-black text-white px-6 py-2 rounded-lg text-xs uppercase font-black">Selecionar Fotos</button>
                    <input ref={fileInputRef} type="file" multiple className="hidden" onChange={e => e.target.files && setSelectedFiles(Array.from(e.target.files))} />
                    <div className="grid grid-cols-4 gap-2 mt-4">
                       {selectedFiles.map((f, i) => <div key={i} className="aspect-square bg-gray-200 rounded-lg overflow-hidden"><img src={URL.createObjectURL(f)} className="w-full h-full object-cover"/></div>)}
                       {editingId && formData.images?.map((url, i) => <div key={`old-${i}`} className="aspect-square bg-gray-200 rounded-lg overflow-hidden relative group">
                          <img src={url} className="w-full h-full object-cover"/>
                          <button type="button" onClick={() => setFormData({...formData, images: formData.images?.filter((_, idx) => idx !== i)})} className="absolute top-1 right-1 bg-red-500 text-white p-1 rounded-md opacity-0 group-hover:opacity-100 transition-opacity"><Trash size={12}/></button>
                       </div>)}
                    </div>
                 </div>

                 <button disabled={saving} className="w-full bg-black text-white font-black py-5 rounded-2xl hover:bg-primary hover:text-black uppercase italic transition-all">
                    {saving ? 'Salvando...' : 'Publicar Anúncio'}
                 </button>
              </form>
           </div>
        </div>
      )}
      
      {showLGPD && (
        <div className="fixed bottom-6 left-6 right-6 z-50 animate-bounce-in">
           <div className="bg-white shadow-2xl rounded-3xl p-6 border border-gray-200 flex flex-col md:flex-row items-center gap-6 max-w-6xl mx-auto">
              <div className="flex-grow text-center md:text-left">
                <h4 className="font-black text-sm mb-1 uppercase italic tracking-tighter">Privacidade e Cookies</h4>
                <p className="text-gray-500 font-semibold uppercase text-[10px] tracking-widest leading-tight">Nosso site utiliza tecnologias para melhorar sua experiência em conformidade com a LGPD.</p>
              </div>
              <button onClick={() => setShowLGPD(false)} className="bg-black text-white font-black px-10 py-3 rounded-xl hover:bg-primary hover:text-black transition-all uppercase italic text-xs shadow-lg">Entendido</button>
           </div>
        </div>
      )}
    </div>
  );
};

const root = createRoot(document.getElementById('root')!);
root.render(<App />);
