
import React, { useState, useRef, useEffect, useCallback } from 'react';
import ReactDOM from 'react-dom/client';
import { GoogleGenAI, Chat } from '@google/genai';

// --- TYPE DEFINITIONS ---
interface Service {
  icon: React.ReactNode;
  title: string;
  description: string;
}
interface PortfolioItem {
  id: number;
  title: string;
  description: string;
  imageUrl: string;
}
interface Message {
  sender: 'user' | 'bot';
  text: string;
}
interface NavLink {
  href: string;
  label: string;
}

// --- ICON COMPONENTS ---
const iconProps = { className: "w-12 h-12", strokeWidth: 1.5 };
const BriefcaseIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...iconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M20.25 14.15v4.07a2.25 2.25 0 0 1-2.25 2.25H5.92a2.25 2.25 0 0 1-2.25-2.25v-4.07a2.25 2.25 0 0 1 .84-1.64l4.5-3.5a2.25 2.25 0 0 1 2.82 0l4.5 3.5a2.25 2.25 0 0 1 .84 1.64Z" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M12 21V14.25m0 0a2.25 2.25 0 0 1 2.25-2.25h1.5a2.25 2.25 0 0 1 2.25 2.25v.075M12 14.25a2.25 2.25 0 0 0-2.25-2.25H8.25a2.25 2.25 0 0 0-2.25 2.25v.075" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9v.75m16.5-1.5v.75m-3.75 0V3.75c0-1.108-.892-2-2-2h-3.5c-1.108 0-2 .892-2 2v4.5" />
  </svg>
);
const MegaphoneIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...iconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 6a7.5 7.5 0 1 0 7.5 7.5h-7.5V6Z" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 10.5H21A7.5 7.5 0 0 0 13.5 3v7.5Z" />
  </svg>
);
const BuildingOfficeIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...iconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 21h16.5M4.5 3h15M5.25 3v18m13.5-18v18M9 6.75h1.5m-1.5 3h1.5m-1.5 3h1.5m3-6h1.5m-1.5 3h1.5m-1.5 3h1.5M9 21v-3.375c0-.621.504-1.125 1.125-1.125h3.75c.621 0 1.125.504 1.125 1.125V21" />
  </svg>
);
const ComputerDesktopIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...iconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M9 17.25v1.007a3 3 0 0 1-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0 1 15 18.257V17.25m6-12V15a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 15V5.25A2.25 2.25 0 0 1 5.25 3h13.5A2.25 2.25 0 0 1 21 5.25Z" />
  </svg>
);
const ShoppingCartIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...iconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 0 0-3 3h15.75m-12.75-3h11.218c.51 0 .962-.343 1.087-.835l1.838-5.513A1.875 1.875 0 0 0 18.156 6H5.25L5.63 7.854M7.5 14.25 6.106 5.132A7.5 7.5 0 0 1 13.5 3h.034a7.5 7.5 0 0 1 6.868 4.632l-1.838 5.513M1.5 21h3.375a.75.75 0 0 0 .75-.75V18a.75.75 0 0 0-.75-.75H1.5a.75.75 0 0 0-.75.75v2.25c0 .414.336.75.75.75Zm15 0h3.375a.75.75 0 0 0 .75-.75V18a.75.75 0 0 0-.75-.75H16.5a.75.75 0 0 0-.75.75v2.25c0 .414.336.75.75.75Z" />
  </svg>
);
const TruckIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...iconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M8.25 18.75a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m3 0h6m-9 0H3.375a1.125 1.125 0 0 1-1.125-1.125V14.25m17.25 4.5a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m3 0h1.125c.621 0 1.125-.504 1.125-1.125V14.25m-17.25 4.5v-1.875a3.375 3.375 0 0 1 3.375-3.375h9.75a3.375 3.375 0 0 1 3.375 3.375v1.875M3.75 14.25v-1.125a3.375 3.375 0 0 1 3.375-3.375h9.75a3.375 3.375 0 0 1 3.375 3.375v1.125" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M15 9.75h4.5v4.5H15z" />
  </svg>
);
const VideoCameraIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...iconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 10.5l4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9A2.25 2.25 0 0 0 4.5 18.75Z" />
  </svg>
);
const navIconProps = { className: "w-8 h-8", strokeWidth: 2 };
const Bars3Icon = () => (
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...navIconProps}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
    </svg>
);
const XMarkIcon = () => (
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...navIconProps}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
    </svg>
);
const sliderIconProps = { className: "w-8 h-8", strokeWidth: 2 };
const ChevronLeftIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...sliderIconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5 8.25 12l7.5-7.5" />
  </svg>
);
const ChevronRightIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...sliderIconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
  </svg>
);
const chatIconProps = { className: "w-6 h-6", strokeWidth: 2 };
const ChatBubbleIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...chatIconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.847 2.1-1.98 2.193l-3.722.28c-1.131.084-2.183-.5-2.735-1.485l-2.004-3.527c-.412-.723-.553-1.57-.368-2.355l1.233-3.085c.184-.46.52- .88.944-1.186l3.36-2.1c.54-.338 1.18-.463 1.79-.348Z" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M7.5 14.25c0-1.628 1.322-2.95 2.95-2.95h1.5c1.628 0 2.95 1.322 2.95 2.95v.2c0 1.628-1.322 2.95-2.95 2.95h-1.5a2.95 2.95 0 0 1-2.95-2.95v-.2Z" />
  </svg>
);
const CloseIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...chatIconProps}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
  </svg>
);
const PaperAirplaneIcon = () => (
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...chatIconProps}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M6 12 3.269 3.125A59.769 59.769 0 0 1 21.485 12 59.768 59.768 0 0 1 3.27 20.875L5.999 12Zm0 0h7.5" />
    </svg>
);
const adminIconProps = { className: "w-6 h-6", strokeWidth: 1.5 };
const Cog6ToothIcon = () => (
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...adminIconProps}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.24-.438.613-.43.992a6.759 6.759 0 0 1 0 1.903c-.008.378.137.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.333.183-.582.495-.645.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.063-.374-.313-.686-.645-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.075-.124l-1.217.456a1.125 1.125 0 0 1-1.37-.49l-1.296-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.759 6.759 0 0 1 0-1.903c.008-.378-.137-.75-.43-.99l-1.004-.828a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.75.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281Z" />
        <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
    </svg>
);
const socialIconProps = { className: "w-6 h-6" };
const FacebookIcon = () => (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" {...socialIconProps}>
        <path d="M22 12c0-5.523-4.477-10-10-10S2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.878v-6.987h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.988C18.343 21.128 22 16.991 22 12z" />
    </svg>
);
const InstagramIcon = () => (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" {...socialIconProps}>
        <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.85s-.011 3.585-.069 4.85c-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07s-3.585-.012-4.85-.07c-3.252-.148-4.771-1.691-4.919-4.919-.058-1.265-.069-1.645-.069-4.85s.011-3.585.069-4.85c.149-3.225 1.664-4.771 4.919-4.919 1.266-.058 1.644-.07 4.85-.07zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948s.014 3.667.072 4.947c.2 4.358 2.618 6.78 6.98 6.98 1.281.059 1.689.073 4.948.073s3.667-.014 4.947-.072c4.358-.2 6.78-2.618 6.98-6.98.059-1.281.073-1.689.073-4.948s-.014-3.667-.072-4.947c-.2-4.358-2.618-6.78-6.98-6.98-1.281-.059-1.689-.073-4.948-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.162 6.162 6.162 6.162-2.759 6.162-6.162-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4s1.791-4 4-4 4 1.79 4 4-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44 1.441-.645 1.441-1.44-.645-1.44-1.441-1.44z" />
    </svg>
);

// --- MOCK DATA ---
const navLinksData: NavLink[] = [
    { href: '#services', label: 'Servicios' },
    { href: '#portfolio', label: 'Portafolio' },
    { href: '#contact', label: 'Contacto' },
];
const servicesData: Service[] = [
  { icon: React.createElement(BriefcaseIcon), title: 'Incubadora', description: 'Transformamos tu idea en un negocio viable y escalable con nuestra metodología de incubación probada.' },
  { icon: React.createElement(MegaphoneIcon), title: 'Marketing', description: 'Creamos estrategias de marketing digital y tradicional que conectan tu marca con la audiencia correcta.' },
  { icon: React.createElement(BuildingOfficeIcon), title: 'Arquitectura', description: 'Diseño arquitectónico innovador y funcional para espacios comerciales y corporativos que inspiran.' },
  { icon: React.createElement(ComputerDesktopIcon), title: 'Tecnología', description: 'Desarrollo de software a medida, aplicaciones web y móviles para potenciar la transformación digital.' },
  { icon: React.createElement(ShoppingCartIcon), title: 'POS', description: 'Soluciones de Punto de Venta (POS) eficientes y seguras para optimizar tus operaciones de venta.' },
  { icon: React.createElement(TruckIcon), title: 'Drive Thru', description: 'Implementación y optimización de sistemas Drive Thru para una experiencia de cliente rápida y fluida.' },
  { icon: React.createElement(VideoCameraIcon), title: 'Audiovisual', description: 'Producción de contenido audiovisual de alta calidad, desde videos corporativos hasta campañas publicitarias.' },
];
const portfolioData: PortfolioItem[] = [
  { id: 1, title: 'Branding Corporativo para Fintech', description: 'Desarrollamos una identidad de marca completa para una startup financiera, logrando un posicionamiento sólido en el mercado.', imageUrl: 'https://picsum.photos/seed/tech1/1200/800' },
  { id: 2, title: 'Diseño de Oficinas Modernas', description: 'Proyecto arquitectónico para un hub tecnológico, creando un espacio de trabajo colaborativo y vanguardista.', imageUrl: 'https://picsum.photos/seed/arch1/1200/800' },
  { id: 3, title: 'Campaña de Marketing Digital 360°', description: 'Ejecutamos una campaña multicanal para una marca de consumo masivo, aumentando su alcance en un 200%.', imageUrl: 'https://picsum.photos/seed/market1/1200/800' },
  { id: 4, title: 'App Móvil para E-commerce', description: 'Una aplicación móvil intuitiva y de alto rendimiento que impulsó las ventas online de un cliente retail en un 40%.', imageUrl: 'https://picsum.photos/seed/ecomm1/1200/800' },
];

// --- UI COMPONENTS ---
const Header: React.FC<{ navLinks: NavLink[] }> = ({ navLinks }) => {
  const [isOpen, setIsOpen] = useState(false);
  const handleScroll = (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>, href: string) => {
    e.preventDefault();
    const targetId = href.replace(/.*#/, "");
    const elem = document.getElementById(targetId);
    elem?.scrollIntoView({ behavior: 'smooth' });
    setIsOpen(false);
  };
  return (
    <header className="bg-brand-gray/80 backdrop-blur-sm sticky top-0 z-50">
      <div className="container mx-auto px-6 py-4 flex justify-between items-center">
        <a href="#home" onClick={(e) => handleScroll(e, '#home')} className="text-2xl font-bold text-white">Imagi<span className="text-brand-red">Done</span>.</a>
        <nav className="hidden md:flex items-center space-x-8">
          {navLinks.map((link) => ( <a key={link.href} href={link.href} onClick={(e) => handleScroll(e, link.href)} className="text-gray-300 hover:text-brand-red transition-colors duration-300">{link.label}</a> ))}
        </nav>
        <div className="md:hidden"><button onClick={() => setIsOpen(!isOpen)} className="text-white focus:outline-none">{isOpen ? <XMarkIcon /> : <Bars3Icon />}</button></div>
      </div>
      {isOpen && (
        <div className="md:hidden bg-brand-gray-light">
          <nav className="flex flex-col items-center py-4">
            {navLinks.map((link) => (<a key={link.href} href={link.href} onClick={(e) => handleScroll(e, link.href)} className="text-gray-200 py-2 hover:text-brand-red transition-colors duration-300">{link.label}</a>))}
          </nav>
        </div>
      )}
    </header>
  );
};

const Hero: React.FC = () => {
  const handleScrollToContact = (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
    e.preventDefault();
    document.getElementById('contact')?.scrollIntoView({ behavior: 'smooth' });
  };
  return (
    <section id="home" className="relative h-screen flex items-center justify-center text-center bg-cover bg-center" style={{ backgroundImage: "url('https://picsum.photos/seed/hero/1920/1080')" }}>
      <div className="absolute inset-0 bg-brand-gray bg-opacity-80"></div>
      <div className="relative z-10 px-6">
        <h1 className="text-4xl md:text-6xl lg:text-7xl font-extrabold text-white leading-tight mb-4">Donde las Grandes Ideas <br className="hidden md:block"/> se Convierten en <span className="text-brand-red">Realidades.</span></h1>
        <p className="text-lg md:text-xl text-gray-300 max-w-3xl mx-auto mb-8">Somos ImagiDone, la agencia de servicios integrales que impulsa tu visión desde la concepción hasta la ejecución.</p>
        <a href="#contact" onClick={handleScrollToContact} className="bg-brand-red text-white font-bold py-3 px-8 rounded-full hover:bg-brand-red-dark transition-all duration-300 transform hover:scale-105 text-lg">Hablemos de tu Proyecto</a>
      </div>
    </section>
  );
};

const ServiceCard: React.FC<{ service: Service }> = ({ service }) => (
  <div className="bg-brand-gray-light p-8 rounded-lg shadow-lg hover:shadow-brand-red/20 hover:-translate-y-2 transition-all duration-300 flex flex-col items-center text-center">
    <div className="text-brand-red mb-4">{service.icon}</div>
    <h3 className="text-xl font-bold text-white mb-2">{service.title}</h3>
    <p className="text-gray-400 text-base flex-grow">{service.description}</p>
  </div>
);

const Services: React.FC<{ services: Service[] }> = ({ services }) => (
  <section id="services" className="py-20 bg-brand-gray">
    <div className="container mx-auto px-6">
      <div className="text-center mb-12">
        <h2 className="text-4xl font-extrabold text-white">Nuestros Servicios</h2>
        <p className="text-gray-400 mt-4 text-lg max-w-2xl mx-auto">Soluciones integrales para llevar tu negocio al siguiente nivel.</p>
        <div className="mt-4 h-1 w-24 bg-brand-red mx-auto"></div>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
        <div className="lg:col-span-1 xl:col-span-1"><ServiceCard service={services[0]} /></div>
        <div className="lg:col-span-1 xl:col-span-1"><ServiceCard service={services[1]} /></div>
        <div className="lg:col-span-1 xl:col-span-1"><ServiceCard service={services[2]} /></div>
        <div className="lg:col-span-1 xl:col-span-1"><ServiceCard service={services[3]} /></div>
        <div className="md:col-span-2 lg:col-span-3 xl:col-span-4 grid grid-cols-1 md:grid-cols-3 gap-8">
          <ServiceCard service={services[4]} />
          <ServiceCard service={services[5]} />
          <ServiceCard service={services[6]} />
        </div>
      </div>
    </div>
  </section>
);

const Portfolio: React.FC<{ portfolioItems: PortfolioItem[] }> = ({ portfolioItems }) => {
  const [currentIndex, setCurrentIndex] = useState(0);

  const prevSlide = () => {
    setCurrentIndex(prevIndex => prevIndex === 0 ? portfolioItems.length - 1 : prevIndex - 1);
  };

  const nextSlide = useCallback(() => {
    setCurrentIndex(prevIndex => prevIndex === portfolioItems.length - 1 ? 0 : prevIndex + 1);
  }, [portfolioItems.length]);

  useEffect(() => {
    if (portfolioItems.length === 0) return;
    const slideInterval = setInterval(nextSlide, 5000);
    return () => clearInterval(slideInterval);
  }, [nextSlide, portfolioItems.length]);

  if (portfolioItems.length === 0) {
    return (
      <section id="portfolio" className="py-20 bg-brand-gray-light">
        <div className="container mx-auto px-6 text-center">
          <h2 className="text-4xl font-extrabold text-white">Nuestro Portafolio</h2>
          <p className="text-gray-400 mt-4 text-lg">Próximamente mostraremos nuestros casos de éxito.</p>
        </div>
      </section>
    );
  }

  const currentItem = portfolioItems[currentIndex];
  return (
    <section id="portfolio" className="py-20 bg-brand-gray-light">
      <div className="container mx-auto px-6">
        <div className="text-center mb-12"><h2 className="text-4xl font-extrabold text-white">Nuestro Portafolio</h2><p className="text-gray-400 mt-4 text-lg max-w-2xl mx-auto">Casos de éxito que demuestran nuestra pasión y experiencia.</p><div className="mt-4 h-1 w-24 bg-brand-red mx-auto"></div></div>
        <div className="relative max-w-4xl mx-auto h-[60vh] rounded-lg shadow-2xl overflow-hidden group">
          <div style={{ backgroundImage: `url(${currentItem.imageUrl})` }} className="w-full h-full bg-center bg-cover duration-500 ease-in-out transform"></div>
          <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent"></div>
          <div className="absolute bottom-0 left-0 p-8 text-white"><h3 className="text-3xl font-bold mb-2">{currentItem.title}</h3><p className="text-gray-200 text-lg">{currentItem.description}</p></div>
          <button onClick={prevSlide} className="absolute top-1/2 -translate-y-1/2 left-5 text-white bg-black/30 rounded-full p-2 group-hover:bg-black/50 transition-colors focus:outline-none"><ChevronLeftIcon /></button>
          <button onClick={nextSlide} className="absolute top-1/2 -translate-y-1/2 right-5 text-white bg-black/30 rounded-full p-2 group-hover:bg-black/50 transition-colors focus:outline-none"><ChevronRightIcon /></button>
          <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex space-x-2">
            {portfolioItems.map((_, index) => (<div key={index} onClick={() => setCurrentIndex(index)} className={`w-3 h-3 rounded-full cursor-pointer transition-colors ${currentIndex === index ? 'bg-brand-red' : 'bg-gray-400'}`}></div>))}
          </div>
        </div>
      </div>
    </section>
  );
};

const ContactForm: React.FC = () => {
  const [formData, setFormData] = useState({ name: '', email: '', message: '' });
  const [isSubmitted, setIsSubmitted] = useState(false);
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prevState => ({ ...prevState, [name]: value }));
  };
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    console.log('Form submitted:', formData);
    setIsSubmitted(true);
    setTimeout(() => {
      setIsSubmitted(false);
      setFormData({ name: '', email: '', message: '' });
    }, 3000);
  };
  return (
    <section id="contact" className="py-20 bg-brand-gray">
      <div className="container mx-auto px-6">
        <div className="text-center mb-12"><h2 className="text-4xl font-extrabold text-white">Contáctanos</h2><p className="text-gray-400 mt-4 text-lg max-w-2xl mx-auto">¿Listo para empezar? Cuéntanos sobre tu proyecto.</p><div className="mt-4 h-1 w-24 bg-brand-red mx-auto"></div></div>
        <div className="max-w-2xl mx-auto">
          <form onSubmit={handleSubmit} className="space-y-6">
            <div><label htmlFor="name" className="block text-sm font-medium text-gray-300">Nombre</label><input type="text" name="name" id="name" value={formData.name} onChange={handleChange} required className="mt-1 block w-full bg-brand-gray-light border border-gray-600 rounded-md shadow-sm py-3 px-4 text-white focus:outline-none focus:ring-brand-red focus:border-brand-red" /></div>
            <div><label htmlFor="email" className="block text-sm font-medium text-gray-300">Correo Electrónico</label><input type="email" name="email" id="email" value={formData.email} onChange={handleChange} required className="mt-1 block w-full bg-brand-gray-light border border-gray-600 rounded-md shadow-sm py-3 px-4 text-white focus:outline-none focus:ring-brand-red focus:border-brand-red" /></div>
            <div><label htmlFor="message" className="block text-sm font-medium text-gray-300">Mensaje</label><textarea name="message" id="message" rows={5} value={formData.message} onChange={handleChange} required className="mt-1 block w-full bg-brand-gray-light border border-gray-600 rounded-md shadow-sm py-3 px-4 text-white focus:outline-none focus:ring-brand-red focus:border-brand-red"></textarea></div>
            <div><button type="submit" className="w-full flex justify-center py-3 px-4 border border-transparent rounded-full shadow-sm text-lg font-bold text-white bg-brand-red hover:bg-brand-red-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-brand-gray focus:ring-brand-red transition-colors duration-300">Enviar Mensaje</button></div>
          </form>
          {isSubmitted && (<p className="text-center mt-4 text-green-400">¡Gracias! Tu mensaje ha sido enviado con éxito.</p>)}
        </div>
      </div>
    </section>
  );
};

const Footer: React.FC<{ onAdminClick: () => void; }> = ({ onAdminClick }) => (
  <footer className="bg-black py-6">
    <div className="container mx-auto px-6 text-gray-400 flex justify-between items-center">
      <p className="text-sm">&copy; {new Date().getFullYear()} ImagiDone. Todos los derechos reservados.</p>
      <div className="flex items-center space-x-4">
        <a href="https://facebook.com" target="_blank" rel="noopener noreferrer" aria-label="Visita nuestro Facebook" className="text-gray-500 hover:text-brand-red transition-colors duration-300"><FacebookIcon /></a>
        <a href="https://instagram.com" target="_blank" rel="noopener noreferrer" aria-label="Visita nuestro Instagram" className="text-gray-500 hover:text-brand-red transition-colors duration-300"><InstagramIcon /></a>
        <button onClick={onAdminClick} className="text-gray-500 hover:text-brand-red transition-colors duration-300" aria-label="Admin Login"><Cog6ToothIcon /></button>
      </div>
    </div>
  </footer>
);

const Chatbot: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const chatRef = useRef<Chat | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); };
  useEffect(scrollToBottom, [messages]);
  const initializeChat = () => {
    const apiKey = 'TU_CLAVE_DE_API_AQUI'; // IMPORTANTE: Reemplaza con tu clave de API de Google Gemini.
    if (!apiKey || apiKey === 'TU_CLAVE_DE_API_AQUI') {
      setMessages([{ sender: 'bot', text: '¡Hola! Para usar el chat, el propietario del sitio debe configurar una clave de API válida.' }]);
      return;
    }
    const ai = new GoogleGenAI({ apiKey: apiKey });
    const servicesInfo = servicesData.map(s => `- ${s.title}: ${s.description}`).join('\n');
    const portfolioInfo = portfolioData.map(p => `- ${p.title}: ${p.description}`).join('\n');
    const systemInstruction = `Eres un asistente virtual amigable y profesional para "ImagiDone", una agencia de servicios integrales. Tu objetivo es responder las preguntas de los usuarios basándote únicamente en la siguiente información. No inventes servicios, proyectos o detalles. Si no sabes la respuesta a una pregunta, di amablemente que no tienes esa información. Sé conciso y directo.\n\nInformación de Servicios de ImagiDone:\n${servicesInfo}\n\nInformación del Portafolio de ImagiDone:\n${portfolioInfo}\n\nResponde siempre en español.`;
    chatRef.current = ai.chats.create({ model: 'gemini-3-flash-preview', config: { systemInstruction } });
    setMessages([{ sender: 'bot', text: '¡Hola! Soy el asistente de ImagiDone. ¿En qué puedo ayudarte hoy?' }]);
  };
  useEffect(() => { if (isOpen && messages.length === 0) { initializeChat(); } }, [isOpen]);
  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim() || isLoading) return;
    const userMessage: Message = { sender: 'user', text: input };
    setMessages(prev => [...prev, userMessage]);
    setInput('');
    setIsLoading(true);
    try {
      if (!chatRef.current) { throw new Error('Chat not initialized. API key might be missing.'); }
      const response = await chatRef.current.sendMessage({ message: input });
      const botMessage: Message = { sender: 'bot', text: response.text };
      setMessages(prev => [...prev, botMessage]);
    } catch (error) {
      console.error('Error sending message to Gemini:', error);
      const errorMessage: Message = { sender: 'bot', text: 'Lo siento, estoy teniendo problemas para conectarme. Por favor, verifica la configuración de la API o inténtalo de nuevo más tarde.' };
      setMessages(prev => [...prev, errorMessage]);
    } finally { setIsLoading(false); }
  };
  return (
    <>
      <div className={`fixed bottom-0 right-0 m-6 transition-all duration-300 ease-in-out ${isOpen ? 'opacity-0 scale-90' : 'opacity-100 scale-100'}`}><button onClick={() => setIsOpen(true)} className="bg-brand-red text-white rounded-full p-4 shadow-lg hover:bg-brand-red-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-brand-gray focus:ring-brand-red" aria-label="Abrir chat"><ChatBubbleIcon /></button></div>
      <div className={`fixed bottom-0 right-0 m-6 flex flex-col bg-brand-gray-light w-full max-w-sm h-full max-h-[70vh] rounded-lg shadow-2xl transition-all duration-300 ease-in-out origin-bottom-right ${isOpen ? 'opacity-100 scale-100' : 'opacity-0 scale-90 pointer-events-none'}`}>
        <header className="flex items-center justify-between p-4 bg-brand-gray border-b border-gray-700 rounded-t-lg"><h3 className="text-lg font-bold text-white">Asistente ImagiDone</h3><button onClick={() => setIsOpen(false)} className="text-gray-400 hover:text-white" aria-label="Cerrar chat"><CloseIcon /></button></header>
        <div className="flex-1 p-4 overflow-y-auto">
          <div className="flex flex-col space-y-4">
            {messages.map((msg, index) => (<div key={index} className={`flex items-end gap-2 ${msg.sender === 'user' ? 'justify-end' : 'justify-start'}`}><div className={`max-w-xs md:max-w-md lg:max-w-xs rounded-lg px-4 py-2 ${msg.sender === 'user' ? 'bg-brand-red text-white rounded-br-none' : 'bg-gray-700 text-gray-200 rounded-bl-none'}`}><p className="text-sm">{msg.text}</p></div></div>))}
            {isLoading && (<div className="flex justify-start"><div className="bg-gray-700 text-gray-200 rounded-lg px-4 py-2 rounded-bl-none"><div className="flex items-center space-x-2"><span className="w-2 h-2 bg-gray-400 rounded-full animate-pulse delay-75"></span><span className="w-2 h-2 bg-gray-400 rounded-full animate-pulse delay-150"></span><span className="w-2 h-2 bg-gray-400 rounded-full animate-pulse delay-300"></span></div></div></div>)}
            <div ref={messagesEndRef} />
          </div>
        </div>
        <form onSubmit={handleSendMessage} className="p-4 bg-brand-gray border-t border-gray-700 rounded-b-lg">
          <div className="flex items-center space-x-2">
            <input type="text" value={input} onChange={e => setInput(e.target.value)} placeholder="Escribe tu pregunta..." className="flex-1 bg-brand-gray-light border border-gray-600 rounded-full py-2 px-4 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-brand-red" disabled={isLoading || messages.length === 0} />
            <button type="submit" className="bg-brand-red text-white rounded-full p-2 disabled:bg-brand-red-dark disabled:opacity-50" disabled={isLoading || !input.trim() || messages.length === 0} aria-label="Enviar mensaje"><PaperAirplaneIcon /></button>
          </div>
        </form>
      </div>
    </>
  );
};

interface AdminProps {
  onLogout: () => void;
  navLinks: NavLink[];
  setNavLinks: React.Dispatch<React.SetStateAction<NavLink[]>>;
  services: Service[];
  setServices: React.Dispatch<React.SetStateAction<Service[]>>;
  portfolioItems: PortfolioItem[];
  setPortfolioItems: React.Dispatch<React.SetStateAction<PortfolioItem[]>>;
}
const Admin: React.FC<AdminProps> = ({ onLogout, navLinks, setNavLinks, services, setServices, portfolioItems, setPortfolioItems }) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [localNavLinks, setLocalNavLinks] = useState(navLinks);
  const [localServices, setLocalServices] = useState(services);
  const [localPortfolio, setLocalPortfolio] = useState(portfolioItems);
  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    if (username === 'ima2018' && password === 'DunnCorp@6775') { setIsLoggedIn(true); setError(''); } else { setError('Usuario o contraseña incorrectos.'); }
  };
  const handleSave = () => {
    setNavLinks(localNavLinks); setServices(localServices); setPortfolioItems(localPortfolio);
    alert('¡Contenido guardado exitosamente!'); onLogout();
  };
  const handleNavLinkChange = (index: number, field: keyof NavLink, value: string) => {
    const updated = [...localNavLinks]; updated[index] = { ...updated[index], [field]: value }; setLocalNavLinks(updated);
  };
  const handleServiceChange = (index: number, field: keyof Service, value: string) => {
    const updated = [...localServices];
    const serviceToUpdate = { ...updated[index] };
    if (field === 'title' || field === 'description') { serviceToUpdate[field] = value; }
    updated[index] = serviceToUpdate; setLocalServices(updated);
  };
  const handlePortfolioChange = (index: number, field: keyof PortfolioItem, value: string) => {
    const updated = [...localPortfolio];
    const itemToUpdate = { ...updated[index] };
    if (field === 'title' || field === 'description' || field === 'imageUrl') { itemToUpdate[field] = value; }
    updated[index] = itemToUpdate; setLocalPortfolio(updated);
  };
  if (!isLoggedIn) {
    return (
      <div className="min-h-screen bg-brand-gray flex items-center justify-center">
        <div className="bg-brand-gray-light p-8 rounded-lg shadow-lg w-full max-w-md">
          <h2 className="text-2xl font-bold text-white text-center mb-6">Admin Login</h2>
          <form onSubmit={handleLogin} className="space-y-4">
            <input type="text" placeholder="Usuario" value={username} onChange={e => setUsername(e.target.value)} className="w-full bg-gray-700 text-white p-3 rounded-md focus:outline-none focus:ring-2 focus:ring-brand-red" />
            <input type="password" placeholder="Contraseña" value={password} onChange={e => setPassword(e.target.value)} className="w-full bg-gray-700 text-white p-3 rounded-md focus:outline-none focus:ring-2 focus:ring-brand-red" />
            {error && <p className="text-red-500 text-sm text-center">{error}</p>}
            <button type="submit" className="w-full bg-brand-red text-white font-bold py-3 rounded-md hover:bg-brand-red-dark transition-colors">Ingresar</button>
            <button type="button" onClick={onLogout} className="w-full text-center text-gray-400 hover:text-white mt-2">Volver al Sitio</button>
          </form>
        </div>
      </div>
    );
  }
  return (
    <div className="bg-brand-gray min-h-screen p-8 text-white">
      <div className="max-w-4xl mx-auto">
        <div className="flex justify-between items-center mb-8"><h1 className="text-3xl font-bold">Panel de Administración</h1><div><button onClick={handleSave} className="bg-brand-red font-bold py-2 px-6 rounded-md hover:bg-brand-red-dark transition-colors mr-4">Guardar y Salir</button><button onClick={onLogout} className="bg-brand-gray-light font-bold py-2 px-4 rounded-md hover:bg-gray-600 transition-colors">Salir sin Guardar</button></div></div>
        <div className="bg-brand-gray-light p-6 rounded-lg mb-6"><h2 className="text-2xl font-bold mb-4 border-b border-gray-600 pb-2">Menú de Navegación</h2>{localNavLinks.map((link, index) => (<div key={index} className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-2"><input type="text" value={link.label} onChange={e => handleNavLinkChange(index, 'label', e.target.value)} className="bg-gray-700 p-2 rounded-md" placeholder="Texto del botón"/><input type="text" value={link.href} onChange={e => handleNavLinkChange(index, 'href', e.target.value)} className="bg-gray-700 p-2 rounded-md" placeholder="Enlace (ej. #services)"/></div>))}</div>
        <div className="bg-brand-gray-light p-6 rounded-lg mb-6"><h2 className="text-2xl font-bold mb-4 border-b border-gray-600 pb-2">Servicios</h2>{localServices.map((service, index) => (<div key={index} className="mb-4"><div className="flex items-center mb-2"><div className="text-brand-red mr-3 w-8 h-8">{servicesData[index].icon}</div><input type="text" value={service.title} onChange={e => handleServiceChange(index, 'title', e.target.value)} className="bg-gray-700 p-2 rounded-md w-full font-bold"/></div><textarea value={service.description} onChange={e => handleServiceChange(index, 'description', e.target.value)} className="bg-gray-700 p-2 rounded-md w-full h-24" placeholder="Descripción del servicio"/></div>))}</div>
        <div className="bg-brand-gray-light p-6 rounded-lg"><h2 className="text-2xl font-bold mb-4 border-b border-gray-600 pb-2">Portafolio</h2>{localPortfolio.map((item, index) => (<div key={item.id} className="mb-4"><input type="text" value={item.title} onChange={e => handlePortfolioChange(index, 'title', e.target.value)} className="bg-gray-700 p-2 rounded-md w-full font-bold mb-2" placeholder="Título del Proyecto"/><input type="text" value={item.imageUrl} onChange={e => handlePortfolioChange(index, 'imageUrl', e.target.value)} className="bg-gray-700 p-2 rounded-md w-full mb-2" placeholder="URL de la Imagen"/><textarea value={item.description} onChange={e => handlePortfolioChange(index, 'description', e.target.value)} className="bg-gray-700 p-2 rounded-md w-full h-20" placeholder="Descripción del proyecto"/></div>))}</div>
      </div>
    </div>
  );
};

// --- MAIN APP COMPONENT ---
const App: React.FC = () => {
  const [isAdminView, setIsAdminView] = useState(false);
  const [navLinks, setNavLinks] = useState<NavLink[]>(navLinksData);
  const [services, setServices] = useState<Service[]>(servicesData);
  const [portfolioItems, setPortfolioItems] = useState<PortfolioItem[]>(portfolioData);
  if (isAdminView) {
    return (<Admin onLogout={() => setIsAdminView(false)} navLinks={navLinks} setNavLinks={setNavLinks} services={services} setServices={setServices} portfolioItems={portfolioItems} setPortfolioItems={setPortfolioItems} />);
  }
  return (
    <div className="bg-brand-gray font-sans">
      <Header navLinks={navLinks} />
      <main>
        <Hero />
        <Services services={services} />
        <Portfolio portfolioItems={portfolioItems} />
        <ContactForm />
      </main>
      <Footer onAdminClick={() => setIsAdminView(true)} />
      <Chatbot />
    </div>
  );
};

// --- RENDER APPLICATION ---
const rootElement = document.getElementById('root');
if (!rootElement) {
  throw new Error("Could not find root element to mount to");
}
const root = ReactDOM.createRoot(rootElement);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
