"use client";

import { useState, useEffect, useMemo, Suspense } from "react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import Image from "next/image";
import { motion } from "framer-motion";
import PaymentButton from "@/components/stripe/PaymentButton";
import MiniMaxVoiceWidgetV2 from "@/components/MiniMaxVoiceWidgetV2";
// import SiteMenteVoiceWidget from "@/components/SiteMenteVoiceWidget";

type Language = "es" | "en";
type Vertical = "real-estate" | "restaurant" | "clinic" | "home-services";

const contentByLang = {
  es: {
    nav: { features: "Características", pricing: "Precios", contact: "Contacto", cta: "Pedir demo" },
    selectIndustry: "Selecciona tu industria:",
    ctaPrimary: "Ver demo en vivo",
    ctaSecondary: "Ver características",
    featuresTitle: (v: string) => `Características para ${v}`,
    pricingTitle: (v: string) => `Planes para ${v}`,
    pricingSubtitle: "Cada nivel incluye todo del anterior. Elige el que se adapte a tu negocio.",
    popular: "Más popular",
    ctaTitle: "¿Listo para empezar?",
    ctaText: "Cuéntanos sobre tu negocio y te mostraremos una demo personalizada.",
    ctaButton: "Solicitar demo gratuita",
    form: { 
      title: "Cuéntanos sobre tu negocio", 
      businessName: "Nombre del negocio",
      contactName: "Tu nombre",
      email: "Email",
      phone: "Teléfono",
      message: "Mensaje", 
      submit: "Pedir mi demo gratis", 
      close: "Cerrar",
      success: "¡Gracias! Tu solicitud de demo ha sido recibida. Te contactaremos en breve.",
      // Vertical-specific labels
      restaurant: { tables: "¿Cuántas mesas tiene tu restaurante?", hasWebsite: "¿Ya tienes web?", websiteYes: "Sí", websiteNo: "No" },
      realEstate: { properties: "¿Cuántas propiedades gestionas?", location: "¿En qué zona operas?" },
      clinic: { practitioners: "¿Cuántos profesionales trabajan en la clínica?", clinicType: "¿Qué tipo de clínica es?" },
      carRental: { vehicles: "¿Cuántos vehículos tienes?", services: "¿Ofreces servicio de recogida en aeropuerto?" },
    },
    footer: "© 2026 SiteMente. Parte de la familia HolaCompi.",
  },
  en: {
    nav: { features: "Features", pricing: "Pricing", contact: "Contact", cta: "Get demo" },
    selectIndustry: "Select your industry:",
    ctaPrimary: "See live demo",
    ctaSecondary: "See features",
    featuresTitle: (v: string) => `Features for ${v}`,
    pricingTitle: (v: string) => `Plans for ${v}`,
    pricingSubtitle: "Each plan includes everything from the previous level. Choose what fits your needs.",
    popular: "Most popular",
    ctaTitle: "Ready to get started?",
    ctaText: "Tell us about your business and we'll show you a personalized demo.",
    ctaButton: "Request free demo",
    form: { 
      title: "Tell us about your business", 
      businessName: "Business name",
      contactName: "Your name",
      email: "Email",
      phone: "Phone",
      message: "Message", 
      submit: "Get my free demo", 
      close: "Close",
      success: "Thanks! Your demo request has been received. We'll contact you soon.",
      // Vertical-specific labels
      restaurant: { tables: "How many tables does your restaurant have?", hasWebsite: "Do you already have a website?", websiteYes: "Yes", websiteNo: "No" },
      realEstate: { properties: "How many properties do you manage?", location: "What area do you operate in?" },
      clinic: { practitioners: "How many practitioners work at your clinic?", clinicType: "What type of clinic is it?" },
      carRental: { vehicles: "How many vehicles do you have?", services: "Do you offer airport pickup service?" },
    },
    footer: "© 2026 SiteMente. Part of the HolaCompi family.",
  },
};

const verticals = {
  "real-estate": {
    es: {
      name: "Inmobiliaria",
      hero: { badge: "✓ Agentes inmobiliarios en España", title: "Tu web inmobiliario con IA que vende 24/7", subtitle: "La IA responde preguntas sobre propiedades, agenda visitas y cualifica leads mientras tú cierras ventas. Especialistas en agencias inmobiliarias en la Costa del Sol." },
      features: [
        { title: "Búsqueda inteligente", desc: "Los clientes encuentran propiedades con preguntas naturales" },
        { title: "Visitas automáticas", desc: "Agenda visitas sin intervención humana" },
        { title: "Cualificación de leads", desc: "La IA filtra compradores serios de mirones" },
        { title: "Multidioma", desc: "Responde en español, inglés, francés, alemán" },
      ],
      pricing: [
        { name: "Chat IA", price: "€299", period: "/mes", setup: "+€900", features: ["🤖 Empleado IA 24/7", "🌍 Hasta 3 idiomas", "📅 Reservas automáticas", "📊 Dashboard de clientes"] },
        { name: "Chat + Voz", price: "€599", period: "/mes", setup: "+€2.500", popular: true, features: ["✅ Todo de Chat IA", "📞 Contesta llamadas", "🌍 Hasta 5 idiomas", "📅 Sincroniza calendario"] },
        { name: "Empresa IA", price: "€1.499", period: "/mes", setup: "+€5.000", features: ["✅ Todo de Chat + Voz", "🏢 Múltiples ubicaciones", "🔗 CRM completo", "📈 Analytics avanzado"] },
      ],
    },
    en: {
      name: "Real Estate",
      hero: { badge: "✓ Real estate agents in Spain", title: "Your AI real estate website that sells 24/7", subtitle: "AI answers property questions, schedules viewings, and qualifies leads while you close sales. Specialists in Costa del Sol agencies." },
      features: [
        { title: "Smart search", desc: "Clients find properties with natural questions" },
        { title: "Auto viewings", desc: "Schedule visits without human intervention" },
        { title: "Lead qualification", desc: "AI filters serious buyers from browsers" },
        { title: "Multilingual", desc: "Responds in Spanish, English, French, German" },
      ],
      pricing: [
        { name: "AI Chat", price: "€299", period: "/month", setup: "+€900", features: ["🤖 AI Employee 24/7", "🌍 2 languages (ES+EN)", "📅 Automated bookings", "📊 Customer dashboard"] },
        { name: "Chat + Voice", price: "€599", period: "/month", setup: "+€2.500", popular: true, features: ["✅ Everything in AI Chat", "📞 Answers calls", "🌍 Up to 5 languages", "📅 Calendar sync"] },
        { name: "AI Company", price: "€1,499", period: "/month", setup: "+€5,000", features: ["✅ Everything in Chat + Voice", "🏢 Multiple locations", "🔗 Full CRM", "📈 Advanced analytics"] },
      ],
    },
  },
  "restaurant": {
    es: {
      name: "Restaurante",
      hero: { badge: "✓ Restaurantes en España", title: "Tu restaurante abierto 24 horas", subtitle: "Toma reservas a las 3 AM, responde sobre alérgenos y sugiere platos. La IA maneja toda la atención al cliente mientras tú disfrutas de tu negocio." },
      features: [
        { title: "Reservas 24/7", desc: "Reservas automáticas sin llamar" },
        { title: "Menú interactivo", desc: "Clientes preguntan sobre platos y alérgenos" },
        { title: "Pedidos online", desc: "Carrito de pedidos integrado" },
        { title: "Promociones automáticas", desc: "La IA propone ofertas en momentos bajos" },
      ],
      pricing: [
        { name: "Chat IA", price: "€299", period: "/mes", setup: "+€900", features: ["🤖 Empleado IA 24/7", "🌍 Hasta 3 idiomas", "📅 Reservas automáticas", "📊 Dashboard de clientes"] },
        { name: "Chat + Voz", price: "€599", period: "/mes", setup: "+€2.500", popular: true, features: ["✅ Todo de Chat IA", "📞 Contesta llamadas", "🌍 Hasta 5 idiomas", "📅 Sincroniza calendario"] },
        { name: "Empresa IA", price: "€1.499", period: "/mes", setup: "+€5.000", features: ["✅ Todo de Chat + Voz", "🏢 Múltiples ubicaciones", "🔗 CRM completo", "📈 Analytics avanzado"] },
      ],
    },
    en: {
      name: "Restaurant",
      hero: { badge: "✓ Restaurants in Spain", title: "Your restaurant open 24 hours", subtitle: "Take reservations at 3 AM, answer about allergens and suggest dishes. AI handles all customer service while you enjoy your business." },
      features: [
        { title: "24/7 Reservations", desc: "Automated bookings without calling" },
        { title: "Interactive menu", desc: "Clients ask about dishes and allergens" },
        { title: "Online orders", desc: "Integrated ordering cart" },
        { title: "Auto promotions", desc: "AI offers deals during slow periods" },
      ],
      pricing: [
        { name: "AI Chat", price: "€299", period: "/month", setup: "+€900", features: ["🤖 AI Employee 24/7", "🌍 2 languages (ES+EN)", "📅 Automated bookings", "📊 Customer dashboard"] },
        { name: "Chat + Voice", price: "€599", period: "/month", setup: "+€2.500", popular: true, features: ["✅ Everything in AI Chat", "📞 Answers calls", "🌍 Up to 5 languages", "📅 Calendar sync"] },
        { name: "AI Company", price: "€1,499", period: "/month", setup: "+€5,000", features: ["✅ Everything in Chat + Voice", "🏢 Multiple locations", "🔗 Full CRM", "📈 Advanced analytics"] },
      ],
    },
  },
  "clinic": {
    es: {
      name: "Clínica",
      hero: { badge: "✓ Clínicas estéticas y médicas", title: "Tu clínica siempre disponible", subtitle: "La IA agenda citas, responde sobre tratamientos y recuerda citas. Libera a tu equipo para lo que importa: cuidar pacientes." },
      features: [
        { title: "Citas automáticas", desc: "Agenda 24/7 sin receptionist" },
        { title: "Info de tratamientos", desc: "Responde sobre procedimientos y precios" },
        { title: "Recordatorios", desc: "La IA recuerda citas y seguimiento" },
        { title: "Cualificación", desc: "Filtra pacientes adecuados para cada tratamiento" },
      ],
      pricing: [
        { name: "Chat IA", price: "€299", period: "/mes", setup: "+€900", features: ["🤖 Empleado IA 24/7", "🌍 Hasta 3 idiomas", "📅 Reservas automáticas", "📊 Dashboard de clientes"] },
        { name: "Chat + Voz", price: "€599", period: "/mes", setup: "+€2.500", popular: true, features: ["✅ Todo de Chat IA", "📞 Contesta llamadas", "🌍 Hasta 5 idiomas", "📅 Sincroniza calendario"] },
        { name: "Empresa IA", price: "€1.499", period: "/mes", setup: "+€5.000", features: ["✅ Todo de Chat + Voz", "🏢 Múltiples ubicaciones", "🔗 CRM completo", "📈 Analytics avanzado"] },
      ],
    },
    en: {
      name: "Clinic",
      hero: { badge: "✓ Aesthetic and medical clinics", title: "Your clinic always available", subtitle: "AI schedules appointments, answers about treatments and remembers appointments. Free your team for what matters: patient care." },
      features: [
        { title: "Auto appointments", desc: "Schedule 24/7 without receptionist" },
        { title: "Treatment info", desc: "Answers about procedures and prices" },
        { title: "Reminders", desc: "AI remembers appointments and follow-ups" },
        { title: "Qualification", desc: "Filters suitable patients for each treatment" },
      ],
      pricing: [
        { name: "AI Chat", price: "€299", period: "/month", setup: "+€900", features: ["🤖 AI Employee 24/7", "🌍 2 languages (ES+EN)", "📅 Automated bookings", "📊 Customer dashboard"] },
        { name: "Chat + Voice", price: "€599", period: "/month", setup: "+€2.500", popular: true, features: ["✅ Everything in AI Chat", "📞 Answers calls", "🌍 Up to 5 languages", "📅 Calendar sync"] },
        { name: "AI Company", price: "€1,499", period: "/month", setup: "+€5,000", features: ["✅ Everything in Chat + Voice", "🏢 Multiple locations", "🔗 Full CRM", "📈 Advanced analytics"] },
      ],
    },
  },
  "home-services": {
    es: {
      name: "Servicios del Hogar",
      hero: { badge: "✓ Fontaneros, electricistas, piscinas", title: "Tu empresa de servicios siempre operativa", subtitle: "La IA responde emergencias, agenda servicios y quotea presupuestos. Nunca pierdas un cliente por no estar disponible." },
      features: [
        { title: "Emergencias 24/7", desc: "Responde siempre, incluso a las 2 AM" },
        { title: "Presupuestos rápidos", desc: "La IA genera presupuestos preliminares" },
        { title: "Agenda inteligente", desc: "Coordina citas con disponibilidad real" },
        { title: "Seguimiento", desc: "Recordatorios y seguimiento automático" },
      ],
      pricing: [
        { name: "Chat IA", price: "€299", period: "/mes", setup: "+€900", features: ["🤖 Empleado IA 24/7", "🌍 Hasta 3 idiomas", "📅 Reservas automáticas", "📊 Dashboard de clientes"] },
        { name: "Chat + Voz", price: "€599", period: "/mes", setup: "+€2.500", popular: true, features: ["✅ Todo de Chat IA", "📞 Contesta llamadas", "🌍 Hasta 5 idiomas", "📅 Sincroniza calendario"] },
        { name: "Empresa IA", price: "€1.499", period: "/mes", setup: "+€5.000", features: ["✅ Todo de Chat + Voz", "🏢 Múltiples ubicaciones", "🔗 CRM completo", "📈 Analytics avanzado"] },
      ],
    },
    en: {
      name: "Home Services",
      hero: { badge: "✓ Plumbers, electricians, pools", title: "Your service company always operational", subtitle: "AI answers emergencies, schedules services and quotes jobs. Never lose a customer due to unavailability." },
      features: [
        { title: "24/7 Emergencies", desc: "Always responds, even at 2 AM" },
        { title: "Fast quotes", desc: "AI generates preliminary quotes" },
        { title: "Smart scheduling", desc: "Coordinates appointments with real availability" },
        { title: "Follow-up", desc: "Automatic reminders and follow-up" },
      ],
      pricing: [
        { name: "AI Chat", price: "€299", period: "/month", setup: "+€900", features: ["🤖 AI Employee 24/7", "🌍 2 languages (ES+EN)", "📅 Automated bookings", "📊 Customer dashboard"] },
        { name: "Chat + Voice", price: "€599", period: "/month", setup: "+€2.500", popular: true, features: ["✅ Everything in AI Chat", "📞 Answers calls", "🌍 Up to 5 languages", "📅 Calendar sync"] },
        { name: "AI Company", price: "€1,499", period: "/month", setup: "+€5,000", features: ["✅ Everything in Chat + Voice", "🏢 Multiple locations", "🔗 Full CRM", "📈 Advanced analytics"] },
      ],
    },
  },
};

const verticalNames = {
  es: { "real-estate": "Inmobiliaria", restaurant: "Restaurante", clinic: "Clínica", "home-services": "Servicios del Hogar" },
  en: { "real-estate": "Real Estate", restaurant: "Restaurant", clinic: "Clinic", "home-services": "Home Services" },
};

const verticalIcons = {
  "real-estate": "🏠", restaurant: "🍽️", clinic: "⚕️", "home-services": "🔧"
};

const fadeUp = { hidden: { opacity: 0, y: 20 }, visible: { opacity: 1, y: 0 } };

function DemosContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const [lang, setLang] = useState<Language>("es");
  const [selected, setSelected] = useState<Vertical>("real-estate");
  const [contactOpen, setContactOpen] = useState(false);
  const [initialized, setInitialized] = useState(false);
  const [formData, setFormData] = useState({ 
    businessName: "", 
    contactName: "", 
    email: "", 
    phone: "", 
    message: "",
    // Vertical-specific fields
    tables: "",
    hasWebsite: "",
    properties: "",
    location: "",
    practitioners: "",
    clinicType: "",
    vehicles: "",
    services: "",
  });
  const [businessName, setBusinessName] = useState("");
  const [formSubmitted, setFormSubmitted] = useState(false);

  useEffect(() => {
    if (!searchParams) return;
    
    // Get vertical from URL
    const urlVertical = searchParams.get("vertical");
    const urlType = searchParams.get("type");
    
    if (urlVertical && ["real-estate", "restaurant", "clinic", "home-services"].includes(urlVertical)) {
      setSelected(urlVertical as Vertical);
    } else if (urlType && ["real-estate", "restaurant", "clinic", "home-services"].includes(urlType)) {
      setSelected(urlType as Vertical);
    }
    
    // Get name from URL
    const urlName = searchParams.get("name");
    if (urlName) {
      setBusinessName(decodeURIComponent(urlName));
    }
  }, [searchParams]);

  const t = contentByLang[lang];
  const v = verticals[selected]?.[lang] || verticals["real-estate"][lang];
  const vName = verticalNames[lang][selected];

  useEffect(() => {
    if (typeof window === "undefined") return;
    // Check URL param first
    const params = new URLSearchParams(window.location.search);
    const urlLang = params.get("lang");
    if (urlLang === "es" || urlLang === "en") {
      setLang(urlLang);
      localStorage.setItem("sitemente:lang", urlLang);
      return;
    }
    // Then check localStorage
    const saved = localStorage.getItem("sitemente:lang");
    if (saved === "es" || saved === "en") {
      setLang(saved);
      return;
    }
    // Finally check browser language
    const browserLang = navigator.language.toLowerCase();
    setLang(browserLang.startsWith("en") ? "en" : "es");
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    localStorage.setItem("sitemente:lang", lang);
    // Update URL without reload
    const url = new URL(window.location.href);
    url.searchParams.set("lang", lang);
    window.history.replaceState({}, "", url.toString());
  }, [lang]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // Create lead object matching the CRM schema from /leads page
    const newLead = {
      id: `demo-${Date.now()}`,
      name: formData.businessName || formData.contactName,
      category: selected as "restaurant" | "real-estate" | "clinic" | "car-rental",
      phone: formData.phone,
      email: formData.email,
      website: "",
      address: "",
      rating: 0,
      score: 10, // High score - demo requests are hot leads
      notes: buildLeadNotes(formData, selected, t),
      status: "new" as const,
      lastContact: "",
      nextAction: lang === "es" ? "Llamar para demo" : "Call for demo",
      createdAt: new Date().toISOString().split("T")[0],
    };

    // Save to localStorage (same as /leads page)
    const existingLeads = JSON.parse(localStorage.getItem("sitemente:leads") || "[]");
    const updatedLeads = [newLead, ...existingLeads];
    localStorage.setItem("sitemente:leads", JSON.stringify(updatedLeads));

    setFormSubmitted(true);
    setTimeout(() => {
      setContactOpen(false);
      setFormData({ 
        businessName: "", contactName: "", email: "", phone: "", message: "",
        tables: "", hasWebsite: "", properties: "", location: "",
        practitioners: "", clinicType: "", vehicles: "", services: "" 
      });
      setFormSubmitted(false);
    }, 3000);
  };

  // Build notes string based on vertical-specific fields
  const buildLeadNotes = (data: typeof formData, vertical: Vertical, t: typeof contentByLang.es): string => {
    const notes: string[] = [];
    if (data.message) notes.push(data.message);
    
    switch (vertical) {
      case "restaurant":
        if (data.tables) notes.push(`Mesas: ${data.tables}`);
        if (data.hasWebsite) notes.push(`Web: ${data.hasWebsite === "yes" ? "Sí" : "No"}`);
        break;
      case "real-estate":
        if (data.properties) notes.push(`Propiedades: ${data.properties}`);
        if (data.location) notes.push(`Zona: ${data.location}`);
        break;
      case "clinic":
        if (data.practitioners) notes.push(`Profesionales: ${data.practitioners}`);
        if (data.clinicType) notes.push(`Tipo: ${data.clinicType}`);
        break;
      case "car-rental":
        if (data.vehicles) notes.push(`Vehículos: ${data.vehicles}`);
        if (data.services) notes.push(`Aeropuerto: ${data.services}`);
        break;
    }
    notes.push("DEMO REQUEST - Alta prioridad");
    return notes.join(" | ");
  };

  return (
    <div className="min-h-screen bg-[#1a1625] text-white">
      {/* Header */}
      <header className="border-b border-white/10 bg-[#1a1625]/90 backdrop-blur sticky top-0 z-50">
        <div className="mx-auto flex w-full max-w-6xl items-center justify-between px-6 py-4">
          <a href="/" className="flex items-center gap-3">
            <Image src="/sitemente-logo-light.png" alt="SiteMente" width={40} height={40} className="h-10 w-auto" />
            <span className="font-bold text-xl">SiteMente</span>
          </a>
          <div className="flex items-center gap-4">
            <nav className="hidden md:flex items-center gap-6 text-sm font-medium">
              <a href="#features" className="hover:text-brand-pink transition">{t.nav.features}</a>
              <a href="#pricing" className="hover:text-brand-pink transition">{t.nav.pricing}</a>
              <a href="#contact" className="hover:text-brand-pink transition">{t.nav.contact}</a>
            </nav>
            <div className="flex rounded-full border border-white/40 bg-white/10 p-1 text-xs font-semibold">
              <button onClick={() => setLang("es")} className={`rounded-full px-3 py-1 transition ${lang === "es" ? "bg-white text-brand-purple-dark" : "text-white/80 hover:text-white"}`}>ES</button>
              <button onClick={() => setLang("en")} className={`rounded-full px-3 py-1 transition ${lang === "en" ? "bg-white text-brand-purple-dark" : "text-white/80 hover:text-white"}`}>EN</button>
            </div>
            <a href="#contact" onClick={() => setContactOpen(true)} className="px-4 py-2 bg-brand-pink rounded-lg text-sm font-medium hover:bg-[#ff7bc0] transition">{t.nav.cta}</a>
          </div>
        </div>
      </header>

      {/* Vertical Selector */}
      <section className="py-10 border-b border-white/10 bg-gradient-to-b from-[#1a1625] to-[#2a2235]">
        <div className="mx-auto max-w-6xl px-6">
          <p className="text-center text-white/50 text-sm mb-4">{t.selectIndustry}</p>
          <div className="flex flex-wrap justify-center gap-3">
            {(["real-estate", "restaurant", "clinic", "home-services"] as Vertical[]).map((key) => (
              <button
                key={key}
                onClick={() => setSelected(key)}
                className={`flex items-center gap-2 px-4 py-2 rounded-full border transition ${selected === key ? "bg-brand-pink/20 border-brand-pink text-white" : "border-white/20 text-white/70 hover:border-white/40"}`}
              >
                <span>{verticalIcons[key]}</span>
                <span className="font-medium">{verticalNames[lang][key]}</span>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* Personalized Demo Banner */}
      {businessName && (
        <section className="py-6 bg-gradient-to-r from-brand-pink/20 to-purple-500/20 border-b border-brand-pink/30">
          <div className="mx-auto max-w-4xl px-6 text-center">
            <p className="text-white/80">
              🎯 <span className="font-bold text-white">{businessName}</span> - Demo personalizada lista
            </p>
            <p className="text-sm text-white/60 mt-1">
              Habla con nuestra IA como si fuera un cliente preguntando sobre tu negocio
            </p>
          </div>
        </section>
      )}

      {/* Hero */}
      <section className="py-20 md:py-32 bg-gradient-to-b from-[#2a2235] to-[#1a1625]">
        <div className="mx-auto max-w-4xl px-6 text-center">
          <motion.div variants={fadeUp} initial="hidden" animate="visible" transition={{ duration: 0.6 }}>
            <span className="inline-flex items-center gap-2 rounded-full bg-white/10 px-4 py-1 text-sm mb-6">
              <span className="w-2 h-2 rounded-full bg-brand-pink" />
              {v.hero.badge}
            </span>
            <h1 className="text-4xl md:text-5xl font-bold mb-4">{v.hero.title}</h1>
            <p className="text-lg text-white/70 mb-8">{v.hero.subtitle}</p>
            <div className="flex flex-wrap justify-center gap-4">
              <button onClick={() => setContactOpen(true)} className="px-6 py-3 bg-brand-pink rounded-lg font-semibold hover:bg-[#ff7bc0] transition">{t.ctaPrimary}</button>
              <a href="#features" className="px-6 py-3 border border-white/20 rounded-lg font-semibold hover:bg-white/10 transition">{t.ctaSecondary}</a>
            </div>
          </motion.div>
        </div>
      </section>

      {/* Features */}
      <section id="features" className="py-16 border-t border-white/10">
        <div className="mx-auto max-w-6xl px-6">
          <h2 className="text-3xl font-bold text-center mb-12">{t.featuresTitle(vName)}</h2>
          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
            {v.features.map((feature, i) => (
              <motion.div key={feature.title} variants={fadeUp} initial="hidden" animate="visible" transition={{ duration: 0.5, delay: i * 0.1 }} className="p-6 rounded-xl border border-white/10 bg-white/5 hover:border-white/20 transition">
                <div className="w-12 h-12 rounded-lg bg-brand-pink/20 flex items-center justify-center text-2xl mb-4">✨</div>
                <h3 className="font-semibold mb-2">{feature.title}</h3>
                <p className="text-sm text-white/60">{feature.desc}</p>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* Pricing */}
      <section id="pricing" className="py-16 border-t border-white/10 bg-white/5">
        <div className="mx-auto max-w-6xl px-6">
          <h2 className="text-3xl font-bold text-center mb-4">{t.pricingTitle(vName)}</h2>
          <p className="text-center text-white/60 mb-12">{t.pricingSubtitle}</p>
          <div className="grid md:grid-cols-3 gap-6 max-w-5xl mx-auto">
            {v.pricing.map((plan, i) => (
              <motion.div key={plan.name} variants={fadeUp} initial="hidden" animate="visible" transition={{ duration: 0.5, delay: i * 0.1 }} className={`p-6 rounded-2xl border ${plan.popular ? "border-brand-pink bg-brand-pink/10" : "border-white/10 bg-white/5"}`}>
                {plan.popular && <span className="text-xs font-medium text-brand-pink">{t.popular}</span>}
                <h3 className="text-xl font-bold mt-2">{plan.name}</h3>
                <p className="text-3xl font-bold mt-4">{plan.price}<span className="text-sm font-normal text-white/60">{plan.period || "/mes"}</span></p>
                {plan.setup && <p className="text-xs text-white/50 mt-1">{plan.setup}</p>}
                <ul className="mt-6 space-y-3">
                  {plan.features.map((f) => (
                    <li key={f} className="flex items-center gap-2 text-sm text-white/70">
                      {f}
                    </li>
                  ))}
                </ul>
                <PaymentButton 
                  planId={`demo-${selected}-${plan.name.toLowerCase().replace("starter", "starter").replace("site", "site").replace("growth", "growth")}`} 
                  planType="monthly" 
                  label={lang === "es" ? "Elegir plan" : "Choose plan"}
                  variant={plan.popular ? "primary" : "secondary"}
                />
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section id="contact" className="py-16 border-t border-white/10">
        <div className="mx-auto max-w-2xl px-6 text-center">
          <h2 className="text-3xl font-bold mb-4">{t.ctaTitle}</h2>
          <p className="text-white/60 mb-8">{t.ctaText}</p>
          <button onClick={() => setContactOpen(true)} className="px-8 py-3 bg-brand-pink rounded-lg font-semibold hover:bg-[#ff7bc0] transition">{t.ctaButton}</button>
        </div>
      </section>

      {/* Contact Modal */}
      {contactOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center px-4">
          <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setContactOpen(false)} />
          <motion.div initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} className="relative z-10 w-full max-w-lg rounded-2xl border border-white/20 bg-[#1a1625] p-8">
            <div className="flex items-start justify-between mb-6">
              <div>
                <p className="text-sm uppercase tracking-widest text-white/50">{lang === "es" ? "Contacto" : "Contact"}</p>
                <h3 className="text-xl font-bold mt-1">{t.form.title}</h3>
              </div>
              <button onClick={() => setContactOpen(false)} className="text-white/50 hover:text-white">✕</button>
            </div>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="text-sm text-white/70">{t.form.name}</label>
                <input required value={formData.name} onChange={(e) => setFormData({...formData, name: e.target.value})} className="w-full mt-1 px-4 py-2 rounded-lg bg-white/10 border border-white/20 text-white placeholder-white/40 focus:outline-none focus:border-brand-pink" placeholder={lang === "es" ? "Tu nombre" : "Your name"} />
              </div>
              <div>
                <label className="text-sm text-white/70">{t.form.email}</label>
                <input required type="email" value={formData.email} onChange={(e) => setFormData({...formData, email: e.target.value})} className="w-full mt-1 px-4 py-2 rounded-lg bg-white/10 border border-white/20 text-white placeholder-white/40 focus:outline-none focus:border-brand-pink" placeholder="tu@email.com" />
              </div>
              <div>
                <label className="text-sm text-white/70">{t.form.phone}</label>
                <input required value={formData.phone} onChange={(e) => setFormData({...formData, phone: e.target.value})} className="w-full mt-1 px-4 py-2 rounded-lg bg-white/10 border border-white/20 text-white placeholder-white/40 focus:outline-none focus:border-brand-pink" placeholder="+34 600 000 000" />
              </div>
              <div>
                <label className="text-sm text-white/70">{t.form.message}</label>
                <textarea required value={formData.message} onChange={(e) => setFormData({...formData, message: e.target.value})} rows={3} className="w-full mt-1 px-4 py-2 rounded-lg bg-white/10 border border-white/20 text-white placeholder-white/40 focus:outline-none focus:border-brand-pink" placeholder={lang === "es" ? "¿Qué necesitas automatizar?" : "What do you need to automate?"} />
              </div>
              <button type="submit" className="w-full py-3 bg-brand-pink rounded-lg font-medium hover:bg-[#ff7bc0] transition">{t.form.submit}</button>
            </form>
          </motion.div>
        </div>
      )}

      {/* Footer */}
      <footer className="py-8 border-t border-white/10 text-center text-white/40 text-sm">
        <p>{t.footer}</p>
      </footer>

      {/* Voice AI Widget - Disabled for V2 */}
      {/* <SiteMenteVoiceWidget 
        businessName={businessName || "SiteMente Demo"} 
        businessType={selected}
      /> */}
      
      <MiniMaxVoiceWidgetV2 
        businessName={businessName || "SiteMente"} 
        businessType={selected}
        enabled={false}
      />
    </div>
  );
}


export default function DemosPage() {
  return (
    <Suspense fallback={<div className='min-h-screen bg-brand-purple flex items-center justify-center'><div className='text-white text-xl'>Loading...</div></div>}>
      <DemosContent />
    </Suspense>
  );
}

