import React, { useEffect, useState } from 'react';
import { motion, AnimatePresence, useScroll, useTransform, useMotionValueEvent } from 'framer-motion';
import Contact from '../../components/Contact';
import SEO from '../../components/SEO';

const services = [
    {
        id: 2,
        title: 'Bay Area Email Services',
description: 'Business email hosting with redundant cloud infrastructure, premium deliverability, and local Corpus Christi support — 25 GB mailboxes for $5 per inbox.',
        challenge: 'Missed emails, spam-folder delivery, and server downtime quietly cost businesses leads, approvals, and customer trust.',
        approach: 'We run a resilient email platform built on AWS: incoming messages are safely buffered in Amazon S3 before delivery, outgoing mail uses Amazon SES for industry-leading deliverability, and a hot standby server takes over within minutes if the primary ever goes offline. DNS setup, migration, and day-to-day management — all handled locally.',
        deliverables: [
            '25 GB business mailbox for $5 per inbox',
            'High availability through redundant infrastructure and automated failover',
            'Inbound email buffering in Amazon S3 — no message lost, even during maintenance',
            'Amazon SES sending for strong inbox placement and low spam risk',
            'Per-inbox forwards, auto-replies, and custom spam filtering',
            'DNS setup, migration, and ongoing technical support'
        ],
        needs: [
            'Your domain access',
            'Mailbox count and user list',
            'Current email provider details'
        ],
        icon: 'mail',
        image: '/assets/services/business-email-services.webp'
    },
    {
        id: 7,
        title: 'IT Help Desk',
        description: 'Fast and reliable help desk support for employees, resolving technical issues remotely or on-site.',
        challenge: 'When employees do not have a clear support channel, small technical issues quickly turn into company-wide delays.',
        approach: 'We provide a structured help desk workflow that resolves day-to-day IT issues quickly and keeps your team productive.',
        deliverables: [
            'Remote troubleshooting and issue resolution',
            'User account and access support',
            'Software and email assistance',
            'Escalation path for on-site issues',
            'Clear communication on ticket status'
        ],
        needs: [
            'Primary support contacts',
            'User and device overview'
        ],
        icon: 'support_agent',
        image: ''
    },
    {
        id: 4,
        title: 'New/Refurbished Desktop Hardware',
        description: 'Supply and installation of new or refurbished desktop hardware, tailored to meet your business requirements.',
        challenge: 'Sourcing the right hardware at the right price can be time-consuming and risky.',
        approach: 'We source high-quality new and refurbished equipment that meets your specs and budget, fully tested and ready to go.',
        deliverables: [
            'Hardware procurement',
            'Quality assurance testing',
            'Image deployment',
            'Peripherals setup',
            'Warranty management'
        ],
        needs: [
            'Budget constraints',
            'Performance requirements'
        ],
        icon: 'computer',
        image: ''
    },
    {
        id: 3,
        title: 'Printer & Scanner Installation',
        description: 'Professional installation and configuration of printers and scanners to ensure seamless integration into your workflow.',
        challenge: 'Printer connectivity issues are a leading cause of office support tickets and downtime.',
        approach: 'We set up reliable printing environments with proper drivers, networking, and user access controls.',
        deliverables: [
            'Network printer setup',
            'Scanner configuration (Scan-to-Email/Folder)',
            'Print server management',
            'One-click user deployment',
            'Troubleshooting training'
        ],
        needs: [
            'Printer/Scanner hardware',
            'Network access details'
        ],
        icon: 'print',
        image: ''
    },
    {
        id: 1,
        title: 'Web Design',
        description: 'Professional website design backed by domain registration and DNS support, so your online presence looks credible and works reliably.',
        challenge: 'If your site looks dated, loads poorly, or your domain setup is messy, customers lose trust before they ever contact you.',
        approach: 'We build clean business websites and handle the domain and DNS layer correctly, so your site, forms, and connected services stay dependable.',
        deliverables: [
            'Custom website design & development',
            'Domain registration & management',
            'DNS setup and support',
            'SEO optimization basics',
            'Hosting & maintenance'
        ],
        needs: [
            'Brand guidelines / Logo',
            'Content & copy',
            'Domain access (if existing)'
        ],
        icon: 'language',
        image: '/assets/services/managed-it.webp'
    },
    {
        id: 6,
        title: 'Shared Drive',
        description: 'Setup and management of shared drive solutions so your team can store, access, and organize files reliably.',
        challenge: 'Data growth requires scalable storage that is accessible yet secure from loss.',
        approach: 'We deploy shared drive solutions that centralize your files and make them easy for your team to access securely.',
        deliverables: [
            'Shared drive setup and configuration',
            'Folder structure and permissions',
            'User permission management',
            'Remote access configuration',
            'Backup integration'
        ],
        needs: [
            'Capacity requirements',
            'Access patterns'
        ],
        icon: 'storage',
        image: ''
    },
    {
        id: 5,
        title: 'Network Infrastructure Support',
        description: 'Robust network solutions to ensure connectivity, security, and efficiency, including routers, access points, and switches.',
        challenge: 'A weak network backbone leads to slow speeds, dropped calls, and security holes.',
        approach: 'We design and maintain enterprise-grade networks that handle your data traffic reliably and securely.',
        deliverables: [
            'Router & Switch configuration',
            'VLAN segmentation',
            'Wi-Fi optimization',
            'Network monitoring setup',
            'Cable management'
        ],
        needs: [
            'Floor plans (for Wi-Fi)',
            'ISP details'
        ],
        icon: 'lan',
        image: ''
    }
];

const ServiceModal: React.FC<{ service: typeof services[0] | null; onClose: () => void }> = ({ service, onClose }) => {
    if (!service) return null;

    // ESC key & Body Scroll Lock
    useEffect(() => {
        const handleEsc = (e: KeyboardEvent) => {
            if (e.key === 'Escape') onClose();
        };

        // Lock scroll on both html and body to prevent background scrolling
        const originalHtmlOverflow = document.documentElement.style.overflow;
        const originalBodyOverflow = document.body.style.overflow;

        document.documentElement.style.overflow = 'hidden';
        document.body.style.overflow = 'hidden';

        window.addEventListener('keydown', handleEsc);

        return () => {
            window.removeEventListener('keydown', handleEsc);
            document.documentElement.style.overflow = originalHtmlOverflow;
            document.body.style.overflow = originalBodyOverflow;
        };
    }, [onClose]);

    return (
        <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md"
            onClick={onClose}
        >
            <motion.div
                initial={{ scale: 0.9, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                exit={{ scale: 0.9, opacity: 0 }}
                className="bg-[#1a1a1a] border border-white/10 rounded-2xl w-full max-w-4xl max-h-[90vh] overflow-y-auto relative shadow-2xl custom-scrollbar"
                onClick={(e) => e.stopPropagation()}
                data-lenis-prevent
            >
                {/* Close Button - Sticky and distinct */}
                <button
                    onClick={onClose}
                    className="fixed md:absolute top-6 right-6 p-2 text-white bg-black/60 hover:bg-white/20 backdrop-blur-sm rounded-full transition-all z-50 group border border-white/10 hover:border-white/40 shadow-lg"
                    aria-label="Close modal"
                >
                    <span className="material-symbols-outlined group-hover:scale-110 transition-transform">close</span>
                </button>

                {/* Hero Image in Modal */}
                {service.image && (
                    <div className="w-full h-64 relative">
                        <img
                            src={service.image}
                            alt={service.title}
                            loading="lazy"
                            decoding="async"
                            fetchPriority="low"
                            className="w-full h-full object-cover"
                        />
                        <div className="absolute inset-0 bg-gradient-to-t from-[#1a1a1a] to-transparent"></div>
                    </div>
                )}

                <div className="p-8 md:p-12 relative">
                    <div className="flex items-center gap-6 mb-8">
                        <div className="w-16 h-16 bg-white/5 border border-white/10 rounded-2xl flex items-center justify-center shrink-0">
                            <span className="material-symbols-outlined text-3xl text-white">{service.icon}</span>
                        </div>
                        <div>
                            <h2 className="text-3xl font-bold text-white mb-2">{service.title}</h2>
                            <p className="text-gray-400 text-lg">{service.description}</p>
                        </div>
                    </div>
                    {/* ... rest of content */}

                    <div className="grid md:grid-cols-2 gap-12 mb-12">
                        <div>
                            <h4 className="text-white font-bold uppercase tracking-wider text-xs mb-4 flex items-center gap-2">
                                <span className="material-symbols-outlined text-sm">warning</span> The Challenge
                            </h4>
                            <p className="text-gray-300 leading-relaxed text-sm md:text-base">{service.challenge}</p>
                        </div>
                        <div>
                            <h4 className="text-white font-bold uppercase tracking-wider text-xs mb-4 flex items-center gap-2">
                                <span className="material-symbols-outlined text-sm">lightbulb</span> Our Approach
                            </h4>
                            <p className="text-gray-300 leading-relaxed text-sm md:text-base">{service.approach}</p>
                        </div>
                    </div>

                    <div className="mb-8">
                        <h4 className="font-bold text-white mb-6 flex items-center gap-2">
                            <span className="material-symbols-outlined">check_circle</span>
                            What We Deliver
                        </h4>
                        <div className="grid md:grid-cols-2 gap-4">
                            {service.deliverables.map((item, i) => (
                                <div key={i} className="flex items-start gap-3 p-3 rounded-xl bg-white/5 border border-white/5 hover:border-white/20 transition-colors">
                                    <span className="w-1.5 h-1.5 rounded-full bg-white mt-2 flex-shrink-0 shadow-[0_0_8px_rgba(255,255,255,0.5)]"></span>
                                    <span className="text-gray-300 text-sm">{item}</span>
                                </div>
                            ))}
                        </div>
                    </div>

                    <div className="pt-8 border-t border-white/10">
                        <h4 className="font-semibold text-white mb-3 text-sm uppercase tracking-wide opacity-80">What we need from you</h4>
                        <ul className="text-sm text-gray-400 space-y-2">
                            {service.needs.map((item, i) => (
                                <li key={i} className="flex items-center gap-2">
                                    <span className="w-1 h-1 rounded-full bg-white/50"></span>
                                    {item}
                                </li>
                            ))}
                        </ul>
                    </div>
                </div>
            </motion.div>
        </motion.div>
    );
};

const ServicesPage: React.FC = () => {
    const [selectedService, setSelectedService] = useState<typeof services[0] | null>(null);
    const containerRef = React.useRef<HTMLDivElement>(null);
    const { scrollYProgress } = useScroll({
        target: containerRef,
        offset: ["start end", "end center"]
    });

    const heightTransform = useTransform(scrollYProgress, [0, 1], ["0%", "100%"]);

    const [activeTimelineIndex, setActiveTimelineIndex] = useState(0);

    useMotionValueEvent(scrollYProgress, "change", (latest) => {
        // Calculate index based on scroll progress (0-1)
        // Adjust multiplier to trigger slightly earlier or exact matches
        const index = Math.min(Math.floor((latest) * services.length), services.length - 1);
        setActiveTimelineIndex(index);
    });

    useEffect(() => {
        window.scrollTo(0, 0);
    }, []);

    return (
        <>
        <SEO
            title="IT Services | Bay Area IT Support, Email, Networking and Web"
            description="Explore Bay Area IT services for Corpus Christi businesses, including help desk support, business email, networking, hardware, web design, and day-to-day IT support."
            keywords={['IT services Corpus Christi', 'help desk services', 'business email setup', 'network support']}
            canonicalUrl="https://bayareait.services/services"
        />
        <div className="pt-20 min-h-screen bg-[#0a0a0a] relative overflow-x-hidden">
            {/* Gradient for Services Page */}
            <div className="absolute top-0 left-0 right-0 h-[800px] bg-[radial-gradient(ellipse_80%_50%_at_50%_-20%,rgba(255,255,255,0.15),rgba(255,255,255,0))] dark:bg-[radial-gradient(ellipse_80%_50%_at_50%_-20%,rgba(255,255,255,0.25),rgba(255,255,255,0))] pointer-events-none" />

            {/* Hero */}
            <section className="py-20 px-6 bg-transparent border-b border-white/5 relative z-10">
                <div className="max-w-4xl mx-auto text-center">
                    <span className="text-white/60 font-bold tracking-widest uppercase text-sm mb-3 block">Expertise</span>
                    <h1 className="font-display text-4xl md:text-5xl font-bold mb-6 text-white">
                        Reliable business technology <br /><span className="text-gray-500">that keeps communication moving</span>
                    </h1>
                    <p className="text-xl text-gray-400 max-w-2xl mx-auto">
                        From enterprise-grade email to day-to-day infrastructure and web support, we help businesses stay reachable, credible, and operational.
                    </p>
                </div>
            </section>

            {/* Timeline Section */}
            <section ref={containerRef} className="py-24 px-6 relative overflow-hidden bg-[radial-gradient(ellipse_80%_50%_at_50%_-20%,rgba(255,255,255,0.05),rgba(255,255,255,0))]">
                <div className="max-w-7xl mx-auto relative z-10">
                    {/* Central Timeline Line */}
                    <div className="absolute left-4 md:left-1/2 md:-ml-[0.5px] top-0 bottom-0 w-px bg-white/5 -translate-x-1/2 md:translate-x-0"></div>

                    {/* Active Timeline Line (Scroll Driven) */}
                    <motion.div
                        style={{ height: heightTransform }}
                        className="absolute left-4 md:left-1/2 md:-ml-[0.5px] top-0 w-px bg-white origin-top shadow-[0_0_40px_2px_rgba(255,255,255,1)] drop-shadow-[0_0_10px_rgba(255,255,255,1)] -translate-x-1/2 md:translate-x-0"
                    ></motion.div>

                    <div className="space-y-40 pb-40">
                        {services.map((service, index) => (
                            <div
                                key={service.id}
                                className={`relative flex flex-col md:flex-row gap-8 md:gap-0 ${index % 2 === 0 ? 'md:flex-row' : 'md:flex-row-reverse'}`}
                            >
                                {/* Timeline Dot */}
                                <motion.div
                                    animate={index <= activeTimelineIndex ? {
                                        scale: 1.2,
                                        opacity: 1,
                                        backgroundColor: "#ffffff",
                                        borderColor: "#ffffff",
                                        boxShadow: "0 0 30px rgba(255,255,255,1)"
                                    } : {
                                        scale: 0.5,
                                        opacity: 0.2,
                                        backgroundColor: "#0a0a0a",
                                        borderColor: "rgba(255,255,255,0.1)",
                                        boxShadow: "none"
                                    }}
                                    viewport={{ margin: "-50% 0px -50% 0px" }}
                                    transition={{ duration: 0.3 }}
                                    className="absolute left-4 md:left-1/2 md:-ml-[6px] -translate-x-1/2 md:translate-x-0 w-3 h-3 rounded-full border border-white/20 z-20 top-1/2 -translate-y-1/2 shrink-0"
                                ></motion.div>

                                {/* Content Card */}
                                <motion.div
                                    initial={{ opacity: 0, y: 24 }}
                                    whileInView={{ opacity: 1, y: 0 }}
                                    viewport={{ once: true, margin: "-100px" }}
                                    transition={{ duration: 0.5, ease: "easeOut" }}
                                    className={`md:w-1/2 ${index % 2 === 0 ? 'md:pr-24 pl-12' : 'md:pl-24 pl-12'}`}
                                >
                                    <div
                                        onClick={() => setSelectedService(service)}
                                        className="group cursor-pointer bg-white/5 backdrop-blur-sm rounded-2xl p-10 border border-white/10 hover:border-white/30 hover:bg-white/10 transition-all duration-300 relative overflow-hidden"
                                    >
                                        <div className="w-14 h-14 bg-white/5 rounded-xl flex items-center justify-center mb-8 border border-white/10 group-hover:scale-110 transition-transform duration-500">
                                            <span className="material-symbols-outlined text-3xl text-white">{service.icon}</span>
                                        </div>

                                        <h3 className="text-3xl font-bold text-white mb-4">{service.title}</h3>
                                        <p className="text-gray-400 mb-8 line-clamp-3 text-lg leading-relaxed">{service.description}</p>

                                        <div className="flex items-center text-sm font-bold text-white uppercase tracking-wider group-hover:gap-2 transition-all">
                                            See Details <span className="material-symbols-outlined text-sm ml-1">arrow_forward</span>
                                        </div>
                                    </div>
                                </motion.div>

                                {/* Spacer for the other side */}
                                <div className="md:w-1/2"></div>
                            </div>
                        ))}
                    </div>
                </div>
            </section>

            <Contact />

            {/* Modal */}
            <AnimatePresence>
                {selectedService && (
                    <ServiceModal service={selectedService} onClose={() => setSelectedService(null)} />
                )}
            </AnimatePresence>
        </div>
        </>
    );
};

export default ServicesPage;
