"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import { motion } from "framer-motion";

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: "Precios claros sin sorpresas. Incluye todo lo que necesitas.",
    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", name: "Nombre", email: "Email", phone: "Teléfono", message: "Mensaje", submit: "Enviar mensaje", close: "Cerrar" },
    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: "Clear prices with no surprises. Includes everything you need.",
    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", name: "Name", email: "Email", phone: "Phone", message: "Message", submit: "Send message", close: "Close" },
    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: "Esencial", price: "€299", features: ["1 agente IA", "Web básica", "WhatsApp incluido"] },
        { name: "Profesional", price: "€549", popular: true, features: ["2 agentes IA", "Web completa", "CRM integrado", "Analytics"] },
        { name: "Premium", price: "€949", features: ["Agentes ilimitados", "Web a medida", "API integrations", "Soporte 24/7"] },
      ],
    },
    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: "Essential", price: "€299", features: ["1 AI agent", "Basic website", "WhatsApp included"] },
        { name: "Professional", price: "€549", popular: true, features: ["2 AI agents", "Full website", "CRM integrated", "Analytics"] },
        { name: "Premium", price: "€949", features: ["Unlimited AI agents", "Custom website", "API integrations", "24/7 Support"] },
      ],
    },
  },
  "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: "Inicio", price: "€199", features: ["1 agente IA", "Web básica", "Reservas"] },
        { name: "Negocio", price: "€399", popular: true, features: ["2 agentes IA", "Web completa", "Pedidos", "CRM"] },
        { name: "Cadena", price: "€749", features: ["Agentes ilimitados", "Multi-sucursal", "API integrations", "Soporte 24/7"] },
      ],
    },
    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: "Starter", price: "€199", features: ["1 AI agent", "Basic website", "Reservations"] },
        { name: "Business", price: "€399", popular: true, features: ["2 AI agents", "Full website", "Orders", "CRM"] },
        { name: "Chain", price: "€749", features: ["Unlimited agents", "Multi-branch", "API integrations", "24/7 Support"] },
      ],
    },
  },
  "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: "Básico", price: "€249", features: ["1 agente IA", "Web básica", "Citas"] },
        { name: "Clínica", price: "€499", popular: true, features: ["2 agentes IA", "Web completa", "CRM médico", "Recordatorios"] },
        { name: "Grupo", price: "€899", features: ["Agentes ilimitados", "Multi-sede", "API integrations", "Soporte 24/7"] },
      ],
    },
    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: "Basic", price: "€249", features: ["1 AI agent", "Basic website", "Appointments"] },
        { name: "Clinic", price: "€499", popular: true, features: ["2 AI agents", "Full website", "Medical CRM", "Reminders"] },
        { name: "Group", price: "€899", features: ["Unlimited agents", "Multi-location", "API integrations", "24/7 Support"] },
      ],
    },
  },
  "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: "Profesional", price: "€249", features: ["1 agente IA", "Web básica", "Presupuestos"] },
        { name: "Empresa", price: "€449", popular: true, features: ["2 agentes IA", "Web completa", "CRM servicios", "Fotos/proyectos"] },
        { name: "Corporativo", price: "€849", features: ["Agentes ilimitados", "Flota/varios equipos", "API integrations", "Soporte 24/7"] },
      ],
    },
    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: "Professional", price: "€249", features: ["1 AI agent", "Basic website", "Quotes"] },
        { name: "Company", price: "€449", popular: true, features: ["2 AI agents", "Full website", "Service CRM", "Photos/projects"] },
        { name: "Corporate", price: "€849", features: ["Unlimited agents", "Fleet/multi-team", "API integrations", "24/7 Support"] },
      ],
    },
  },
};

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 } };

export default function DemosPage() {
  const [lang, setLang] = useState<Language>("es");
  const [selected, setSelected] = useState<Vertical>("real-estate");
  const [contactOpen, setContactOpen] = useState(false);
  const [formData, setFormData] = useState({ name: "", email: "", phone: "", message: "" });

  const t = contentByLang[lang];
  const v = verticals[selected][lang];
  const vName = verticalNames[lang][selected];

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

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    alert(lang === "es" ? "¡Gracias! Te contactaremos pronto." : "Thanks! We'll contact you soon.");
    setContactOpen(false);
    setFormData({ name: "", email: "", phone: "", message: "" });
  };

  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-8 border-b border-white/10">
        <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>

      {/* Hero */}
      <section className="py-16 md:py-24">
        <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">/mo</span></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">
                      <span className="text-brand-pink">✓</span> {f}
                    </li>
                  ))}
                </ul>
                <button onClick={() => setContactOpen(true)} className={`w-full mt-6 py-3 rounded-lg font-medium transition ${plan.popular ? "bg-brand-pink hover:bg-[#ff7bc0]" : "border border-white/20 hover:bg-white/10"}`}>
                  {lang === "es" ? "Elegir plan" : "Choose plan"}
                </button>
              </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>
    </div>
  );
}
