"use client";

import { useEffect, useMemo, useState } from "react";
import { motion } from "framer-motion";
import HeroSlider, {
  type HeroSlide,
} from "../components/site-mente/HeroSlider";
import JsonLdSchemas from "../components/site-mente/JsonLdSchemas";
import ServicesAndPricing from "../components/site-mente/ServicesAndPricing";
import SeoMeta from "../components/site-mente/SeoMeta";
// Old widget disabled - using V2 only
// import SiteMenteVoiceWidget from "../components/SiteMenteVoiceWidget";

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

type Language = "es" | "en";

type LeadFormData = {
  name: string;
  phone: string;
  business: string;
  type: string;
};

const contentByLang = {
  es: {
    nav: {
      servicesPricing: "Servicios y Precios",
      method: "Método",
      cta: "Agenda una demo",
    },
    hero: {
      badge: "✓ Agencia de IA para negocios locales en Málaga, Marbella y Costa del Sol",
      title:
        "Implementación de IA para Negocios Locales en España | Convierte tu Web en un Vendedor Inteligente 24/7",
      subtitle:
        "En 2026, tu sitio web o es inteligente, o es invisible. Instalamos agentes de IA que responden, reservan y venden mientras duermes. Especialistas en restaurantes, inmobiliarias y alquiler de coches en la Costa del Sol y toda España.",
      ctaPrimary: "Quiero automatizar mi negocio",
      ctaSecondary: "Ver casos reales",
      highlights: [
        "Setup en 48 horas",
        "ROI medible desde el primer mes",
        "Equipo bilingüe ES / EN",
      ],
    },
    whyAi: {
      title: "Por Qué tu Negocio Necesita IA en 2026",
      intro:
        "En 2026, la IA ya no es opcional. Los clientes esperan respuestas instantáneas y reservas sin fricción, o se van a la competencia.",
      stats: [
        {
          value: "+67% en ventas",
          description: "Aumento medio tras añadir chatbots de IA",
        },
        {
          value: "26% de las transacciones",
          description: "Ya están influidas directamente por asistentes de IA",
        },
        {
          value: "290.000 M$",
          description: "Compras a través de comercio conversacional en 2025",
        },
        {
          value: "95% de las interacciones",
          description: "Se esperan con IA en algún momento del proceso",
        },
        {
          value: "14.200 M$ en un día",
          description: "Ventas del Black Friday 2025 tocadas por IA",
        },
      ],
      footer: "Tu competencia ya está usando IA. ¿Y tú?",
    },
    services: {
      eyebrow: "Servicios",
      title: "IA lista para trabajar en tu negocio.",
      items: [
        {
          title: "Agentes de voz con IA",
          description:
            "Atiende llamadas 24/7, confirma reservas y responde preguntas sin perder oportunidades.",
        },
        {
          title: "Chatbots inteligentes",
          description:
            "Convierte visitas web en clientes con soporte inmediato y respuestas personalizadas.",
        },
        {
          title: "Webs inteligentes",
          description:
            "Sitios modernos y rápidos con IA integrada para captar, convencer y vender.",
        },
        {
          title: "Automatización de negocio",
          description:
            "Emails, recordatorios y CRM conectados para que tu equipo se enfoque en lo importante.",
        },
      ],
    },
    testimonials: {
      title: "Lo Que Dicen Nuestros Clientes",
      items: [
        {
          icon: "🍽️",
          quote:
            "Desde que instalamos el chatbot de SiteMente, nuestras reservas nocturnas aumentaron un 43%. Ya no perdemos clientes que buscan mesa después de las 22h.",
          author: "Propietario de Restaurante",
          location: "Marbella",
        },
        {
          icon: "🏠",
          quote:
            "La IA responde el 70% de las consultas sobre propiedades automáticamente. Mi equipo ahora se enfoca solo en visitas cualificadas. ROI positivo en el primer mes.",
          author: "Director de Agencia Inmobiliaria",
          location: "Málaga",
        },
        {
          icon: "🚗",
          quote:
            "El sistema procesa reservas en 3 idiomas sin intervención humana. Recuperamos la inversión en menos de 6 semanas.",
          author: "Gerente de Rent a Car",
          location: "Benalmádena",
        },
      ],
    },
    method: {
      eyebrow: "Cómo funciona",
      title: "Tu IA en marcha en tres pasos.",
      steps: [
        {
          title: "Diagnóstico inteligente",
          text: "Analizamos tus procesos y detectamos dónde la IA aporta más valor.",
        },
        {
          title: "Implementación exprés",
          text: "Configuramos agentes y flujos en días, no en meses.",
        },
        {
          title: "Crecimiento continuo",
          text: "Optimización semanal basada en datos reales de tu negocio.",
        },
      ],
    },
    pricing: {
      eyebrow: "Precios",
      title: "Planes claros para resultados medibles.",
      plans: [
        {
          name: "Impulso",
          price: "390€",
          desc: "Ideal para empezar con IA en un área clave.",
          features: [
            "1 solución IA",
            "Integración web básica",
            "Soporte por email",
          ],
        },
        {
          name: "Pro",
          price: "790€",
          desc: "El plan favorito para negocios en crecimiento.",
          features: [
            "2 soluciones IA",
            "Automatizaciones avanzadas",
            "Soporte prioritario",
          ],
          popular: true,
        },
        {
          name: "Elite",
          price: "1390€",
          desc: "Para operaciones que quieren IA en todo su embudo.",
          features: [
            "Soluciones IA ilimitadas",
            "Integraciones a medida",
            "Acompañamiento estratégico",
          ],
        },
      ],
      popularBadge: "Más popular",
      cta: "Empezar ahora",
    },
    faq: {
      title: "Preguntas Frecuentes sobre IA para Negocios Locales",
      items: [
        {
          question: "¿Qué es la implementación de IA para negocios?",
          answer:
            "La implementación de IA para negocios significa instalar agentes inteligentes (chatbots, asistentes de voz, automatizaciones) en tu sitio web y canales de comunicación para que respondan preguntas, tomen reservas y vendan 24/7 sin intervención humana. En SiteMente nos especializamos en implementar estas soluciones para restaurantes, inmobiliarias y alquiler de coches en España.",
        },
        {
          question: "¿Cuánto cuesta implementar IA en mi negocio en España?",
          answer:
            "Los precios de implementación de IA en España varían según la complejidad. En SiteMente, nuestros planes comienzan desde 900€ de instalación + 299€/mes para chat IA básico con reservas, hasta planes completos desde 3.500€ + 749€/mes que incluyen sitio web nuevo con IA integrada. Todos los planes incluyen soporte en español e inglés.",
        },
        {
          question: "¿Por qué necesito IA en mi sitio web en 2026?",
          answer:
            "En 2026, el 95% de las interacciones con clientes involucran IA de alguna forma. Los estudios muestran que los negocios con chatbots de IA aumentan sus ventas en un 67% de media y reducen costes de soporte en un 30%. Si tu sitio no puede responder al instante, pierdes clientes frente a la competencia que sí tiene IA.",
        },
        {
          question: "¿La IA funciona para restaurantes pequeños en España?",
          answer:
            "Sí, especialmente bien. Los restaurantes con IA chat ven hasta un 47% más de reservas completadas porque pueden tomar pedidos y reservas 24/7, responder preguntas sobre alérgenos y menús, y sugerir platos personalizados. Muchos de nuestros clientes en la Costa del Sol son restaurantes locales que ahora captan reservas incluso a las 2-3 AM.",
        },
        {
          question: "¿Cuánto tiempo tarda en implementarse la IA?",
          answer:
            "En SiteMente implementamos la mayoría de proyectos en 48 horas para instalaciones básicas (chat IA + reservas en web existente), y entre 2-4 semanas para sitios web completos nuevos con IA integrada. Mucho más rápido que contratar personal adicional.",
        },
        {
          question: "¿La IA puede hablar en español e inglés?",
          answer:
            "Sí. Todos nuestros agentes de IA funcionan en español e inglés nativamente, perfecto para negocios en zonas turísticas como la Costa del Sol. Podemos añadir idiomas adicionales según necesidad.",
        },
        {
          question: "¿Qué negocios se benefician más de la IA?",
          answer:
            "Los negocios con alto volumen de consultas repetitivas: restaurantes (reservas, menú, alergias), inmobiliarias (propiedades disponibles, visitas), alquiler de coches (disponibilidad, precios, seguros), clínicas (citas, tratamientos), hoteles y servicios turísticos. Cualquier negocio que pierda clientes fuera de horario de atención.",
        },
        {
          question: "¿Puedo probar antes de contratar?",
          answer:
            "Sí. Reserva una demo gratuita y te mostramos cómo funcionaría la IA en tu caso específico, con ejemplos reales de tu sector. Sin compromiso.",
        },
        {
          question: "¿Qué pasa si mis clientes usan demasiado la IA y me cobran de más?",
          answer:
            "Todos nuestros planes incluyen uso generoso ('fair use') calculado para un negocio típico de tu tamaño. Si tu uso crece mucho (por ejemplo, abres nuevas ubicaciones o crece tu negocio), te avisamos primero y te proponemos opciones antes de cualquier cargo extra. Nunca sorpresas en la factura.",
        },
        {
          question: "¿SiteMente trabaja solo en la Costa del Sol?",
          answer:
            "No. Aunque tenemos muchos clientes en Málaga, Marbella, Benalmádena y Costa del Sol, trabajamos con negocios en toda España de forma remota. Nuestro equipo es bilingüe ES/EN y podemos implementar IA en cualquier ubicación.",
        },
      ],
    },
    stats: [
      { value: "24/7", label: "Atención automática" },
      { value: "3x", label: "Más reservas" },
      { value: "48h", label: "Tiempo medio de implementación" },
      { value: "+120", label: "Negocios locales servidos" },
    ],
    cta: {
      title: "Haz que tu negocio responda solo.",
      text:
        "Agenda una demo y descubre cómo SiteMente implementa IA real en tu operación diaria.",
      button: "Hablar con SiteMente",
    },
    footer: {
      tagline: "Parte de la familia HolaCompi.",
    },
  },
  en: {
    nav: {
      servicesPricing: "Services & Pricing",
      method: "Method",
      cta: "Book a demo",
    },
    hero: {
      badge: "✓ AI agency for local businesses in Málaga, Marbella & Costa del Sol",
      title:
        "AI Implementation for Local Businesses in Spain | Turn Your Website Into a 24/7 Smart Salesperson",
      subtitle:
        "In 2026, your website is either smart or invisible. We install AI agents that answer, book and sell while you sleep. Specialists in restaurants, real estate and car rentals across Costa del Sol and Spain.",
      ctaPrimary: "Automate my business",
      ctaSecondary: "See real results",
      highlights: [
        "Setup in 48 hours",
        "Measurable ROI in month one",
        "Bilingual team ES / EN",
      ],
    },
    whyAi: {
      title: "Why Your Business Needs AI in 2026",
      intro:
        "In 2026, AI isn't optional anymore. Customers expect instant answers and frictionless bookings, or they go to your competitors.",
      stats: [
        {
          value: "+67% sales",
          description: "Average increase after adding AI chatbots",
        },
        {
          value: "26% of transactions",
          description: "Already influenced directly by AI assistants",
        },
        {
          value: "$290B",
          description: "Purchases via conversational commerce in 2025",
        },
        {
          value: "95% of interactions",
          description: "Expected to involve AI at some point",
        },
        {
          value: "$14.2B in one day",
          description: "Black Friday 2025 sales touched by AI",
        },
      ],
      footer: "Your competition is already using AI. Are you?",
    },
    services: {
      eyebrow: "Services",
      title: "AI ready to work for your business.",
      items: [
        {
          title: "AI Voice Agents",
          description:
            "Answer calls 24/7, confirm bookings, and resolve questions without lost opportunities.",
        },
        {
          title: "AI Chat Widgets",
          description:
            "Turn website visits into customers with instant, personalized support.",
        },
        {
          title: "Smart Websites",
          description:
            "Modern, fast sites with built-in AI to capture, convince, and sell.",
        },
        {
          title: "Business Automation",
          description:
            "Emails, reminders, and CRM flows connected so your team stays focused.",
        },
      ],
    },
    testimonials: {
      title: "What Our Clients Say",
      items: [
        {
          icon: "🍽️",
          quote:
            "Since we installed SiteMente's chatbot, our late-night bookings increased by 43%. We no longer lose customers looking for tables after 10 PM.",
          author: "Restaurant Owner",
          location: "Marbella",
        },
        {
          icon: "🏠",
          quote:
            "The AI answers 70% of property inquiries automatically. My team now focuses only on qualified viewings. Positive ROI in the first month.",
          author: "Real Estate Agency Director",
          location: "Málaga",
        },
        {
          icon: "🚗",
          quote:
            "The system processes bookings in 3 languages without human intervention. We recovered our investment in less than 6 weeks.",
          author: "Car Rental Manager",
          location: "Benalmádena",
        },
      ],
    },
    method: {
      eyebrow: "How it works",
      title: "Your AI live in three steps.",
      steps: [
        {
          title: "Smart audit",
          text: "We map your workflows and pinpoint where AI adds the most value.",
        },
        {
          title: "Rapid implementation",
          text: "Agents and automations go live in days, not months.",
        },
        {
          title: "Continuous growth",
          text: "Weekly optimization based on real business data.",
        },
      ],
    },
    pricing: {
      eyebrow: "Pricing",
      title: "Clear plans for measurable results.",
      plans: [
        {
          name: "Starter",
          price: "€390",
          desc: "Ideal to launch AI in one key area.",
          features: ["1 AI solution", "Basic web integration", "Email support"],
        },
        {
          name: "Pro",
          price: "€790",
          desc: "The go-to plan for growing businesses.",
          features: [
            "2 AI solutions",
            "Advanced automations",
            "Priority support",
          ],
          popular: true,
        },
        {
          name: "Elite",
          price: "€1,390",
          desc: "For operations that want AI across the full funnel.",
          features: [
            "Unlimited AI solutions",
            "Custom integrations",
            "Strategic guidance",
          ],
        },
      ],
      popularBadge: "Most popular",
      cta: "Get started",
    },
    faq: {
      title: "Frequently Asked Questions About AI for Local Businesses",
      items: [
        {
          question: "What is AI implementation for businesses?",
          answer:
            "AI implementation for businesses means installing intelligent agents (chatbots, voice assistants, automations) on your website and communication channels so they answer questions, take bookings, and sell 24/7 without human intervention. At SiteMente we specialize in implementing these solutions for restaurants, real estate and car rentals in Spain.",
        },
        {
          question: "How much does it cost to implement AI in my business in Spain?",
          answer:
            "AI implementation prices in Spain vary by complexity. At SiteMente, our plans start from €900 setup + €299/month for basic AI chat with bookings, up to complete packages from €3,500 + €749/month including a new website with integrated AI. All plans include support in Spanish and English.",
        },
        {
          question: "Why do I need AI on my website in 2026?",
          answer:
            "In 2026, 95% of customer interactions involve AI in some form. Studies show businesses with AI chatbots increase sales by an average of 67% and reduce support costs by 30%. If your site can't answer instantly, you lose customers to competitors that can.",
        },
        {
          question: "Does AI work for small restaurants in Spain?",
          answer:
            "Yes, especially well. Restaurants with AI chat see up to 47% more completed bookings because they can take orders and reservations 24/7, answer allergen and menu questions, and suggest personalized dishes. Many of our clients on the Costa del Sol are local restaurants now capturing bookings even at 2-3 AM.",
        },
        {
          question: "How long does AI implementation take?",
          answer:
            "At SiteMente we implement most projects in 48 hours for basic setups (AI chat + bookings on an existing site), and between 2-4 weeks for complete new websites with integrated AI. Much faster than hiring additional staff.",
        },
        {
          question: "Can the AI speak Spanish and English?",
          answer:
            "Yes. All our AI agents run natively in Spanish and English, perfect for businesses in tourist areas like the Costa del Sol. We can add additional languages as needed.",
        },
        {
          question: "What businesses benefit most from AI?",
          answer:
            "Businesses with high volumes of repetitive inquiries: restaurants (bookings, menu, allergens), real estate (available properties, viewings), car rentals (availability, prices, insurance), clinics (appointments, treatments), hotels, and tourism services. Any business that loses customers outside business hours.",
        },
        {
          question: "Can I try it before committing?",
          answer:
            "Yes. Book a free demo and we'll show how AI would work for your specific case, with real examples from your sector. No commitment.",
        },
        {
          question: "What if my customers use the AI too much and I get charged extra?",
          answer:
            "All our plans include generous fair use sized for a typical business of your size. If your usage grows significantly (for example, you open new locations or your business grows), we let you know first and propose options before any extra charges. No billing surprises.",
        },
        {
          question: "Does SiteMente work only on the Costa del Sol?",
          answer:
            "No. Although we have many clients in Málaga, Marbella, Benalmádena and the Costa del Sol, we work with businesses all across Spain remotely. Our team is bilingual ES/EN and we can implement AI in any location.",
        },
      ],
    },
    stats: [
      { value: "24/7", label: "Automated support" },
      { value: "3x", label: "More bookings" },
      { value: "48h", label: "Average rollout time" },
      { value: "+120", label: "Local businesses served" },
    ],
    cta: {
      title: "Make your business respond on its own.",
      text:
        "Book a demo and see how SiteMente implements real AI in your daily operations.",
      button: "Talk to SiteMente",
    },
    footer: {
      tagline: "Part of the HolaCompi family.",
    },
  },
} as const satisfies Record<Language, object>;

const servicesByLang = {
  es: {
    headline:
      "Convertimos tu web en un vendedor inteligente que trabaja 24/7",
    subheadline:
      "En 2026, los clientes esperan respuestas instantáneas, reservas sin fricción y experiencias personalizadas. Si tu web no puede hacerlo, están yendo a tu competencia.",
    cards: [
      {
        title: "AI Chat + Reservas Automatizadas",
        icon: "💬",
        for: "Para: Restaurantes, clínicas, negocios locales con web existente",
        description: [
          "¿Tu web pierde clientes fuera de horario? En 2026, el 49% de los consumidores consultan chatbots de IA antes de comprar. Si tu sitio no responde al instante, pierdes esa venta.",
          "Tu sitio web responde preguntas, toma reservas y captura leads mientras duermes. Sin aplicaciones complejas, sin clientes perdidos después de las 22h.",
        ],
        sections: [
          {
            title: "Casos de uso reales en la Costa del Sol:",
            items: [
              "Restaurantes: Reservas a las 3 AM, responde preguntas sobre alergias, sugiere platos según preferencias",
              "Clínicas estéticas: Agenda citas, responde dudas sobre tratamientos, envía recordatorios",
              "Servicios locales: Capta leads, cualifica presupuestos, deriva casos urgentes",
            ],
          },
          {
            title: "Resultados típicos:",
            items: [
              "24/7 reservas sin intervención humana",
              "Reduce llamadas repetitivas en un 70%",
              "Captura y cualifica leads automáticamente",
              "ROI positivo en el primer mes",
            ],
          },
        ],
        price: "Desde €299/mes",
        cta: "Ver planes",
      },
      {
        title: "Web Inteligente Completa",
        icon: "🌐",
        for: "Para: Negocios listos para una web moderna + cerebro IA",
        description: [
          "Construimos tu nuevo sitio web Next.js (rápido, seguro, optimizado SEO) e integramos IA que vende, reserva y da soporte en español e inglés.",
        ],
        sections: [
          {
            title: "Lo que incluye:",
            items: [
              "Un sitio que convierte visitas en ventas",
              "Chat + WhatsApp incluidos",
              "Funciona en 2 idiomas desde el día uno",
              "IA con conocimiento profundo de tus productos/servicios",
              "Análisis avanzados y optimización continua",
            ],
          },
          {
            title: "Ideal para:",
            items: [
              "Restaurantes que necesitan presencia web profesional",
              "Inmobiliarias con catálogo de propiedades",
              "Empresas de alquiler que necesitan reservas automatizadas",
              "Negocios turísticos en zonas multilingües",
            ],
          },
        ],
        price: "Desde €749/mes",
        cta: "Ver planes",
      },
      {
        title: "Partner Estratégico de IA + Automatización Total",
        icon: "🚀",
        for: "Para: Grupos de restaurantes, equipos inmobiliarios, cadenas de alquiler",
        description: [
          "Nos convertimos en tu socio estratégico: IA multicanal (web, WhatsApp, llamadas), integraciones CRM, automatizaciones complejas y consultoría mensual.",
        ],
        sections: [
          {
            title: "Qué conseguimos juntos:",
            items: [
              "Escalar sin aumentar costes operativos",
              "IA que vende, da soporte y retiene clientes",
              "Integraciones profundas con tus sistemas existentes",
              "Automatizaciones personalizadas para tu flujo de trabajo",
              "Soporte prioritario + estrategia mensual",
              "Optimización continua basada en datos reales",
            ],
          },
          {
            title: "Para negocios que:",
            items: [
              "Tienen múltiples ubicaciones o marcas",
              "Gestionan alto volumen de leads/reservas",
              "Necesitan integraciones complejas (CRM, PMS, calendarios)",
              "Quieren un partner tecnológico de largo plazo",
            ],
          },
        ],
        price: "Desde €1.950/mes",
        cta: "Hablemos",
      },
    ],
    examplesTitle: "Casos de uso reales en Costa del Sol",
    examples: [
      {
        title: "🍽️ Restaurantes",
        text:
          "Tu web toma reservas a las 3 AM, responde sobre alérgenos y sugiere platos según preferencias del cliente.",
      },
      {
        title: "🏠 Inmobiliarias",
        text:
          "La IA responde dudas sobre propiedades, agenda visitas y cualifica leads mientras atiendes otros clientes.",
      },
      {
        title: "🚗 Rent a Car",
        text:
          "Cotiza, reserva y confirma vehículos sin intervención humana. Multiidioma para turistas.",
      },
    ],
    examplesCta: "Descubre tu plan ideal",
  },
  en: {
    headline: "Turn your website into a 24/7 intelligent salesperson",
    subheadline:
      "In 2026, customers expect instant answers, frictionless bookings, and personalized experiences. If your site can’t deliver, they’re going to your competitors.",
    cards: [
      {
        title: "AI Chat + Automated Bookings",
        icon: "💬",
        for: "For: Restaurants, clinics, local businesses with existing websites",
        description: [
          "Is your website losing customers after hours? In 2026, 49% of consumers consult AI chatbots before buying. If your site doesn't respond instantly, you lose that sale.",
          "Your website answers questions, takes bookings, and captures leads while you sleep. No complex apps, no lost customers after 10 PM.",
        ],
        sections: [
          {
            title: "Real use cases on the Costa del Sol:",
            items: [
              "Restaurants: Reservations at 3 AM, answers allergy questions, suggests dishes based on preferences",
              "Aesthetic clinics: Books appointments, answers treatment questions, sends reminders",
              "Local services: Captures leads, qualifies quotes, escalates urgent cases",
            ],
          },
          {
            title: "Typical results:",
            items: [
              "24/7 bookings without human intervention",
              "Reduce repetitive calls by 70%",
              "Capture and qualify leads automatically",
              "Positive ROI in the first month",
            ],
          },
        ],
        price: "From €299/month",
        cta: "View plans",
      },
      {
        title: "Full Smart Website",
        icon: "🌐",
        for: "For: Businesses ready for a modern site + AI brain",
        description: [
          "We build your new Next.js website (fast, secure, SEO-optimized) and integrate AI that sells, books, and supports in Spanish and English.",
        ],
        sections: [
          {
            title: "What's included:",
            items: [
              "A site that converts visits into sales",
              "Chat + WhatsApp included",
              "Runs in 2 languages from day one",
              "AI with deep knowledge of your products/services",
              "Advanced analytics and continuous optimization",
            ],
          },
          {
            title: "Ideal for:",
            items: [
              "Restaurants needing professional web presence",
              "Real estate with property catalogs",
              "Rental companies needing automated bookings",
              "Tourism businesses in multilingual areas",
            ],
          },
        ],
        price: "From €749/month",
        cta: "View plans",
      },
      {
        title: "AI Strategy Partner + Full Automation",
        icon: "🚀",
        for: "For: Restaurant groups, real estate teams, rental chains",
        description: [
          "We become your strategic partner: multichannel AI (web, WhatsApp, calls), CRM integrations, complex automations, and monthly consulting.",
        ],
        sections: [
          {
            title: "What we achieve together:",
            items: [
              "Scale without increasing operating costs",
              "AI that sells, supports, and retains customers",
              "Deep integrations with your existing systems",
              "Custom automations for your workflow",
              "Priority support + monthly strategy",
              "Continuous optimization based on real data",
            ],
          },
          {
            title: "For businesses that:",
            items: [
              "Have multiple locations or brands",
              "Manage high volume of leads/bookings",
              "Need complex integrations (CRM, PMS, calendars)",
              "Want a long-term technology partner",
            ],
          },
        ],
        price: "From €1,950/month",
        cta: "Let’s talk",
      },
    ],
    examplesTitle: "Real use cases on the Costa del Sol",
    examples: [
      {
        title: "🍽️ Restaurants",
        text:
          "Your site takes reservations at 3 AM, answers allergy questions, and suggests dishes based on preferences.",
      },
      {
        title: "🏠 Real Estate",
        text:
          "AI responds to property questions, books viewings, and qualifies leads while you help other clients.",
      },
      {
        title: "🚗 Rent a Car",
        text:
          "Quote, reserve, and confirm vehicles with no human intervention. Multi-language for tourists.",
      },
    ],
    examplesCta: "Find your ideal plan",
  },
} as const satisfies Record<Language, object>;

export default function HomePage() {
  const [lang, setLang] = useState<Language>("es");
  const [contactOpen, setContactOpen] = useState(false);
  const [leadForm, setLeadForm] = useState<LeadFormData>({ name: "", phone: "", business: "", type: "restaurant" });
  const [leadSubmitted, setLeadSubmitted] = useState(false);
  const content = useMemo(() => contentByLang[lang], [lang]);
  const heroSlides = useMemo<HeroSlide[]>(
    () => [
      {
        type: "image",
        id: "hero-banner",
        src: "/SiteMente-Banner.jpg",
        alt: "SiteMente hero banner",
      },
      {
        type: "stats",
        id: "ai-numbers",
        title: "IA en números",
        items: [
          {
            headline: "+67% en ventas",
            description:
              "Incremento medio tras añadir chatbots de IA.",
          },
          {
            headline: "26% de las transacciones",
            description:
              "Ya están influidas directamente por asistentes de IA.",
          },
          {
            headline: "290.000 M $ en 2025",
            description:
              "Compras a través de comercio conversacional (chat, mensajería y voz).",
          },
        ],
      },
    ],
    []
  );

  useEffect(() => {
    if (typeof window === "undefined") return;
    const saved = window.localStorage.getItem("sitemente:lang");
    if (saved === "es" || saved === "en") {
      setLang(saved);
      return;
    }
    const browserLang = window.navigator.language.toLowerCase();
    setLang(browserLang.startsWith("en") ? "en" : "es");
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem("sitemente:lang", lang);
  }, [lang]);

  return (
    <div className="font-sans text-white bg-[#5e4a8a]">
      <SeoMeta lang={lang} />
      <JsonLdSchemas lang={lang} />
      {/* Old widget disabled - V2 coming soon */}
      {/* <SiteMenteVoiceWidget initialLang={lang} /> */}
      <header className="relative overflow-hidden">
        <nav className="relative z-10 border-b border-white/10 bg-[#5e4a8a]/90 backdrop-blur">
          <div className="mx-auto flex w-full max-w-6xl items-center justify-between px-6 py-4">
            <div className="flex items-center">
              <a href="/" className="group">
                <span className="font-serif text-2xl md:text-3xl font-bold tracking-wide">
                  <span className="text-white group-hover:text-pink-400 transition-colors">Site</span>
                  <span className="text-pink-400 group-hover:text-white transition-colors">Mente</span>
                </span>
              </a>
            </div>
            <div className="flex items-center gap-4">
              <div className="hidden items-center gap-6 text-sm font-medium md:flex">
                <a className="hover:text-white/80" href="#services">
                  {content.nav.servicesPricing}
                </a>
                <a className="hover:text-white/80" href="#method">
                  {content.nav.method}
                </a>
              </div>
              <div className="flex items-center gap-3">
                <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>
                <button
                  onClick={() => setContactOpen(true)}
                  className="rounded-lg bg-brand-pink px-4 py-2 text-sm font-semibold text-white shadow-purple-soft transition hover:-translate-y-1 hover:bg-[#ff7bc0]"
                >
                  {content.nav.cta}
                </button>
              </div>
            </div>
          </div>
        </nav>

        <HeroSlider slides={heroSlides} autoAdvanceMs={7000} />

        <section className="relative mx-auto w-full max-w-6xl px-6 pb-24 pt-6 md:pt-10">
          <motion.div
            variants={fadeUp}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.8, delay: 0.1 }}
            className="mx-auto max-w-3xl text-center"
          >
            <div className="mb-6 flex justify-center">
              <span className="inline-flex items-center gap-2 rounded-full bg-white/20 px-4 py-1 text-sm backdrop-blur">
                <span className="h-2 w-2 rounded-full bg-brand-pink" />
                {content.hero.badge}
              </span>
            </div>
            <h1 className="text-4xl font-bold leading-tight text-white sm:text-5xl lg:text-6xl">
              {content.hero.title}
            </h1>
            <p className="mt-6 text-lg text-white/90 sm:text-xl">
              {content.hero.subtitle}
            </p>
          </motion.div>

          <motion.div
            variants={fadeUp}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.8, delay: 0.2 }}
            className="mt-8 flex flex-wrap justify-center gap-4"
          >
            <button
              onClick={() => setContactOpen(true)}
              className="rounded-lg bg-brand-pink px-6 py-3 text-base font-semibold text-white shadow-purple-soft transition hover:-translate-y-1 hover:bg-[#ff7bc0]"
            >
              {content.hero.ctaPrimary}
            </button>
            <button className="rounded-lg border border-white/80 px-6 py-3 text-base font-semibold text-white transition hover:bg-white/10">
              {content.hero.ctaSecondary}
            </button>
          </motion.div>

          <motion.div
            variants={fadeUp}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.8, delay: 0.3 }}
            className="mt-10 grid w-full gap-4 md:grid-cols-3"
          >
            {content.hero.highlights.map((text) => (
              <div
                key={text}
                className="rounded-xl border border-white/20 bg-white/10 px-4 py-3 text-sm font-medium backdrop-blur"
              >
                {text}
              </div>
            ))}
          </motion.div>

          {/* Lead Capture Form */}
          {!leadSubmitted && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.5 }}
              className="mt-12 max-w-md mx-auto"
            >
              <div className="bg-white/10 backdrop-blur rounded-xl p-6 border border-white/20">
                <h3 className="text-lg font-bold mb-4 text-center">🚀 Pruébalo Ahora - Es Gratis</h3>
                <p className="text-sm text-white/70 mb-4 text-center">Completa y te mostraremos tu AI en acción</p>
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    setLeadSubmitted(true);
                    // Here we'll connect to GHL later
                  }}
                  className="space-y-3"
                >
                  <input
                    type="text"
                    placeholder="Tu nombre"
                    required
                    value={leadForm.name}
                    onChange={(e) => setLeadForm({ ...leadForm, name: e.target.value })}
                    className="w-full bg-white/10 border border-white/20 rounded-lg px-4 py-2 text-white placeholder-white/50"
                  />
                  <input
                    type="tel"
                    placeholder="Tu teléfono"
                    required
                    value={leadForm.phone}
                    onChange={(e) => setLeadForm({ ...leadForm, phone: e.target.value })}
                    className="w-full bg-white/10 border border-white/20 rounded-lg px-4 py-2 text-white placeholder-white/50"
                  />
                  <input
                    type="text"
                    placeholder="Nombre de tu negocio"
                    required
                    value={leadForm.business}
                    onChange={(e) => setLeadForm({ ...leadForm, business: e.target.value })}
                    className="w-full bg-white/10 border border-white/20 rounded-lg px-4 py-2 text-white placeholder-white/50"
                  />
                  <select
                    value={leadForm.type}
                    onChange={(e) => setLeadForm({ ...leadForm, type: e.target.value })}
                    className="w-full bg-white/10 border border-white/20 rounded-lg px-4 py-2 text-white"
                  >
                    <option value="restaurant" className="text-black">🍽️ Restaurante</option>
                    <option value="real-estate" className="text-black">🏠 Inmobiliaria</option>
                    <option value="clinic" className="text-black">🏥 Clínica</option>
                    <option value="car-rental" className="text-black">🚗 Alquiler de coches</option>
                    <option value="other" className="text-black">📌 Otro</option>
                  </select>
                  <button
                    type="submit"
                    className="w-full bg-brand-pink hover:bg-[#ff7bc0] text-white font-bold py-3 rounded-lg transition"
                  >
                    Ver Demo AI Ahora →
                  </button>
                </form>
              </div>
            </motion.div>
          )}

          {leadSubmitted && (
            <motion.div
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              className="mt-12 max-w-md mx-auto text-center"
            >
              <div className="bg-green-500/20 backdrop-blur rounded-xl p-8 border border-green-500/30">
                <div className="text-5xl mb-4">🎉</div>
                <h3 className="text-2xl font-bold mb-2">Perfecto, {leadForm.name}!</h3>
                <p className="text-white/70 mb-4">Preparando tu demo personalizada...</p>
                <a
                  href={`/demos?type=${leadForm.type}&name=${encodeURIComponent(leadForm.business)}`}
                  className="inline-block bg-brand-pink hover:bg-[#ff7bc0] text-white font-bold px-8 py-3 rounded-lg transition"
                >
                  🚀 Entrar a Demo AI
                </a>
              </div>
            </motion.div>
          )}

        </section>
      </header>

      <main className="bg-[#5e4a8a]">
        <section className="mx-auto w-full max-w-6xl px-6 py-16">
          <motion.div
            variants={fadeUp}
            initial="hidden"
            whileInView="visible"
            viewport={{ once: true, amount: 0.3 }}
            transition={{ duration: 0.7 }}
          >
            <h2 className="text-3xl font-bold sm:text-4xl">
              {content.whyAi.title}
            </h2>
            <p className="mt-4 max-w-3xl text-base text-white/85">
              {content.whyAi.intro}
            </p>
          </motion.div>

          <div className="mt-10 grid gap-4 md:grid-cols-5">
            {content.whyAi.stats.map((stat) => (
              <div
                key={stat.value}
                className="rounded-xl border border-white/20 bg-white/10 p-4 text-center backdrop-blur"
              >
                <p className="text-xl font-semibold text-brand-pink">
                  {stat.value}
                </p>
                <p className="mt-2 text-sm text-white/80">
                  {stat.description}
                </p>
              </div>
            ))}
          </div>

          <p className="mt-8 text-center text-sm font-semibold text-white/90">
            {content.whyAi.footer}
          </p>
        </section>

        <ServicesAndPricing
          lang={lang}
          onContact={() => setContactOpen(true)}
        />

        <section className="mx-auto w-full max-w-6xl px-6 pb-20">
          <motion.div
            variants={fadeUp}
            initial="hidden"
            whileInView="visible"
            viewport={{ once: true, amount: 0.3 }}
            transition={{ duration: 0.7 }}
          >
            <h2 className="text-3xl font-bold sm:text-4xl">
              {content.testimonials.title}
            </h2>
          </motion.div>

          <div className="mt-10 grid gap-6 md:grid-cols-3">
            {content.testimonials.items.map((item, index) => (
              <motion.div
                key={`${item.author}-${item.location}`}
                variants={fadeUp}
                initial="hidden"
                whileInView="visible"
                viewport={{ once: true, amount: 0.2 }}
                transition={{ duration: 0.6, delay: index * 0.1 }}
                className="flex h-full flex-col rounded-2xl border border-white/20 bg-white/10 p-6 shadow-purple-soft backdrop-blur"
              >
                <div className="text-3xl">{item.icon}</div>
                <p className="mt-4 text-base text-white/90">
                  "{item.quote}"
                </p>
                <div className="mt-6">
                  <p className="text-sm font-semibold text-white">
                    {item.author}
                  </p>
                  <p className="text-sm text-white/70">{item.location}</p>
                </div>
              </motion.div>
            ))}
          </div>
        </section>


        <section
          id="method"
          className="mx-auto w-full max-w-6xl px-6 py-20"
        >
          <motion.div
            variants={fadeUp}
            initial="hidden"
            whileInView="visible"
            viewport={{ once: true, amount: 0.3 }}
            transition={{ duration: 0.7 }}
          >
            <p className="text-sm font-semibold uppercase tracking-[0.2em] text-white/70">
              {content.method.eyebrow}
            </p>
            <h2 className="mt-4 text-3xl font-bold sm:text-4xl">
              {content.method.title}
            </h2>
          </motion.div>

          <div className="mt-12 grid gap-8 md:grid-cols-3">
            {content.method.steps.map((step, index) => (
              <motion.div
                key={step.title}
                variants={fadeUp}
                initial="hidden"
                whileInView="visible"
                viewport={{ once: true, amount: 0.2 }}
                transition={{ duration: 0.6, delay: index * 0.1 }}
                className="rounded-xl border border-white/20 bg-white/10 p-6 backdrop-blur transition duration-300 hover:-translate-y-2 hover:border-white/50 hover:bg-white/15 hover:shadow-[0_25px_50px_-20px_rgba(118,75,162,0.65)]"
              >
                <div className="mb-4 h-1 w-12 rounded-full bg-brand-pink" />
                <h3 className="text-lg font-semibold">{step.title}</h3>
                <p className="mt-3 text-white/90">{step.text}</p>
              </motion.div>
            ))}
          </div>
        </section>

        <section id="faq" className="mx-auto w-full max-w-6xl px-6 py-20">
          <motion.div
            variants={fadeUp}
            initial="hidden"
            whileInView="visible"
            viewport={{ once: true, amount: 0.3 }}
            transition={{ duration: 0.7 }}
          >
            <h2 className="text-3xl font-bold sm:text-4xl">
              {content.faq.title}
            </h2>
          </motion.div>

          <div className="mt-10 space-y-4">
            {content.faq.items.map((item) => (
              <details
                key={item.question}
                className="group rounded-xl border border-white/20 bg-white/10 p-5 backdrop-blur"
              >
                <summary className="flex cursor-pointer list-none items-center justify-between gap-4 text-left text-base font-semibold text-white">
                  <span>{item.question}</span>
                  <span className="text-xl text-brand-pink transition group-open:rotate-45">
                    +
                  </span>
                </summary>
                <p className="mt-4 text-sm text-white/85">{item.answer}</p>
              </details>
            ))}
          </div>
        </section>

        <section className="mx-auto w-full max-w-6xl px-6 py-20">
          <motion.div
            variants={fadeUp}
            initial="hidden"
            whileInView="visible"
            viewport={{ once: true, amount: 0.3 }}
            transition={{ duration: 0.7 }}
            className="grid gap-6 rounded-2xl border border-white/20 bg-white/10 p-8 text-center backdrop-blur md:grid-cols-4"
          >
            {content.stats.map((stat) => (
              <div key={stat.label}>
                <p className="text-3xl font-bold text-brand-pink">
                  {stat.value}
                </p>
                <p className="mt-2 text-sm text-white/80">{stat.label}</p>
              </div>
            ))}
          </motion.div>
        </section>

        <section id="contact" className="bg-brand-gradient-dark py-20">
          <motion.div
            variants={fadeUp}
            initial="hidden"
            whileInView="visible"
            viewport={{ once: true, amount: 0.3 }}
            transition={{ duration: 0.7 }}
            className="mx-auto flex w-full max-w-5xl flex-col items-start gap-6 px-6 md:flex-row md:items-center md:justify-between"
          >
            <div>
              <h2 className="text-3xl font-bold sm:text-4xl">
                {content.cta.title}
              </h2>
              <p className="mt-4 max-w-xl text-white/90">
                {content.cta.text}
              </p>
            </div>
            <button
              onClick={() => setContactOpen(true)}
              className="rounded-lg bg-brand-pink px-6 py-3 text-base font-semibold text-white shadow-purple-soft transition hover:-translate-y-1 hover:bg-[#ff7bc0]"
            >
              {content.cta.button}
            </button>
          </motion.div>
        </section>
      </main>

      <footer className="bg-brand-purple-dark">
        <div className="mx-auto flex w-full max-w-6xl flex-col gap-6 px-6 py-12 md:flex-row md:items-center md:justify-between">
          <div>
            <p className="text-lg font-semibold">SiteMente</p>
            <p className="text-sm text-white/80">{content.footer.tagline}</p>
          </div>
          <div className="flex gap-3 text-sm text-white/80">
            <span>Costa del Sol</span>
            <span>Hola@SiteMente.com</span>
          </div>
        </div>
      </footer>

      {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, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            transition={{ duration: 0.3 }}
            className="relative z-10 w-full max-w-2xl rounded-2xl border border-white/20 bg-white/10 p-8 text-white shadow-purple-soft backdrop-blur"
          >
            <div className="flex items-start justify-between gap-4">
              <div>
                <p className="text-sm uppercase tracking-[0.3em] text-white/70">
                  {lang === "es" ? "Formulario" : "Contact form"}
                </p>
                <h3 className="mt-3 text-2xl font-bold">
                  {lang === "es"
                    ? "Cuéntanos sobre tu negocio"
                    : "Tell us about your business"}
                </h3>
                <p className="mt-2 text-white/80">
                  {lang === "es"
                    ? "Te respondemos en menos de 24 horas."
                    : "We reply within 24 hours."}
                </p>
              </div>
              <button
                onClick={() => setContactOpen(false)}
                className="rounded-full border border-white/40 px-3 py-1 text-xs font-semibold text-white/80 transition hover:bg-white/10 hover:text-white"
              >
                {lang === "es" ? "Cerrar" : "Close"}
              </button>
            </div>

            <form
              action="https://formsubmit.co/hola@sitemente.com"
              method="POST"
              className="mt-8 grid gap-4"
            >
              <input type="hidden" name="_captcha" value="false" />
              <input type="hidden" name="_subject" value="Nuevo lead SiteMente" />
              <div className="grid gap-4 md:grid-cols-2">
                <div>
                  <label className="text-sm font-semibold text-white/80">
                    {lang === "es" ? "Nombre" : "Name"}
                  </label>
                  <input
                    required
                    name="name"
                    placeholder={lang === "es" ? "Tu nombre" : "Your name"}
                    className="mt-2 w-full rounded-lg border border-white/20 bg-white/10 px-4 py-3 text-white placeholder:text-white/50 focus:border-white/60 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="text-sm font-semibold text-white/80">
                    Email
                  </label>
                  <input
                    required
                    name="email"
                    type="email"
                    placeholder="hola@empresa.com"
                    className="mt-2 w-full rounded-lg border border-white/20 bg-white/10 px-4 py-3 text-white placeholder:text-white/50 focus:border-white/60 focus:outline-none"
                  />
                </div>
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <div>
                  <label className="text-sm font-semibold text-white/80">
                    {lang === "es" ? "Empresa" : "Company"}
                  </label>
                  <input
                    name="company"
                    placeholder={
                      lang === "es" ? "Nombre del negocio" : "Business name"
                    }
                    className="mt-2 w-full rounded-lg border border-white/20 bg-white/10 px-4 py-3 text-white placeholder:text-white/50 focus:border-white/60 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="text-sm font-semibold text-white/80">
                    {lang === "es" ? "Teléfono" : "Phone"}
                  </label>
                  <input
                    name="phone"
                    placeholder="+34 600 000 000"
                    className="mt-2 w-full rounded-lg border border-white/20 bg-white/10 px-4 py-3 text-white placeholder:text-white/50 focus:border-white/60 focus:outline-none"
                  />
                </div>
              </div>
              <div>
                <label className="text-sm font-semibold text-white/80">
                  {lang === "es" ? "Mensaje" : "Message"}
                </label>
                <textarea
                  required
                  name="message"
                  rows={4}
                  placeholder={
                    lang === "es"
                      ? "¿Qué quieres automatizar?"
                      : "What would you like to automate?"
                  }
                  className="mt-2 w-full rounded-lg border border-white/20 bg-white/10 px-4 py-3 text-white placeholder:text-white/50 focus:border-white/60 focus:outline-none"
                />
              </div>
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <p className="text-xs text-white/60">
                  {lang === "es"
                    ? "Al enviar, aceptas que te contactemos por email."
                    : "By submitting, you agree to be contacted by email."}
                </p>
                <button
                  type="submit"
                  className="rounded-lg bg-brand-pink px-6 py-3 text-sm font-semibold text-white shadow-purple-soft transition hover:-translate-y-1 hover:bg-[#ff7bc0]"
                >
                  {lang === "es" ? "Enviar mensaje" : "Send message"}
                </button>
              </div>
            </form>
          </motion.div>
        </div>
      )}
    </div>
  );
}
