"use client";

import Image from "next/image";
import Link from "next/link";
import { useCallback, useEffect, useRef, useState } from "react";
import {
  ArrowRight,
  Wifi,
  Smartphone,
  Lock,
  BadgeCheck,
  Wrench,
  Building2,
  MapPin,
  Mail,
  MessageSquare,
  PhoneCall,
  Train,
  Server,
  Shield,
  Code,
  Settings,
  CheckCircle,
  AlertCircle,
  Check,
} from "lucide-react";
import { Spinner } from "@/components/atoms";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";

// =============================================================================
// CUSTOM HOOKS
// =============================================================================

/**
 * useInView - Intersection Observer hook for scroll-triggered animations
 * Returns a ref and boolean indicating if element is in viewport
 */
function useInView(options: IntersectionObserverInit = {}) {
  const ref = useRef<HTMLElement>(null);
  const [isInView, setIsInView] = useState(false);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry?.isIntersecting) {
          setIsInView(true);
          observer.disconnect(); // triggerOnce
        }
      },
      { threshold: 0.1, ...options }
    );

    observer.observe(element);
    return () => observer.disconnect();
  }, [options]);

  return [ref, isInView] as const;
}

// =============================================================================
// TYPES & DATA
// =============================================================================

type ServiceCategory = "personal" | "business";

interface ServiceItem {
  title: string;
  icon: React.ReactNode;
  href: string;
}

interface FormData {
  subject: string;
  name: string;
  email: string;
  phone: string;
  message: string;
}

interface FormErrors {
  subject?: string;
  name?: string;
  email?: string;
  message?: string;
}

interface FormTouched {
  subject?: boolean;
  name?: boolean;
  email?: boolean;
  phone?: boolean;
  message?: boolean;
}

const CONTACT_SUBJECTS = [
  { value: "", label: "Select a topic*" },
  { value: "internet", label: "Internet Service Inquiry" },
  { value: "sim", label: "Phone/SIM Plan Inquiry" },
  { value: "vpn", label: "VPN Service Inquiry" },
  { value: "business", label: "Business Solutions" },
  { value: "support", label: "Technical Support" },
  { value: "billing", label: "Billing Question" },
  { value: "other", label: "Other" },
];

const personalServices: ServiceItem[] = [
  {
    title: "Internet Plan",
    icon: <Wifi className="h-8 w-8 text-primary" />,
    href: "/services/internet",
  },
  {
    title: "Phone Plan",
    icon: <Smartphone className="h-8 w-8 text-primary" />,
    href: "/services/sim",
  },
  { title: "VPN Service", icon: <Lock className="h-8 w-8 text-primary" />, href: "/services/vpn" },
  {
    title: "Onsite Support",
    icon: <Wrench className="h-8 w-8 text-primary" />,
    href: "/services/onsite",
  },
];

const businessServices: ServiceItem[] = [
  {
    title: "Office LAN Setup",
    icon: <Server className="h-8 w-8 text-primary" />,
    href: "/services/business",
  },
  {
    title: "Onsite & Remote Tech Support",
    icon: <Wrench className="h-8 w-8 text-primary" />,
    href: "/services/onsite",
  },
  {
    title: "Dedicated Internet Access",
    icon: <Building2 className="h-8 w-8 text-primary" />,
    href: "/services/business",
  },
  {
    title: "Data Center Service",
    icon: <Shield className="h-8 w-8 text-primary" />,
    href: "/services/business",
  },
  {
    title: "Website Construction",
    icon: <Code className="h-8 w-8 text-primary" />,
    href: "/services/business",
  },
  {
    title: "Website Maintenance",
    icon: <Settings className="h-8 w-8 text-primary" />,
    href: "/services/business",
  },
];

const services = [
  {
    title: "Internet Plans",
    description:
      "High-speed NTT fiber with English installation support. No Japanese paperwork, we handle everything for you.",
    icon: <Wifi className="h-8 w-8 text-primary" />,
    href: "/services/internet",
  },
  {
    title: "Phone Plans",
    description:
      "SIM cards on Japan's best network. Foreign credit cards accepted, no hanko required. Get connected in days.",
    icon: <Smartphone className="h-8 w-8 text-primary" />,
    href: "/services/sim",
  },
  {
    title: "Business Solutions",
    description:
      "Enterprise IT for international companies. Dedicated internet, office networks, and bilingual tech support.",
    icon: <Building2 className="h-8 w-8 text-primary" />,
    href: "/services/business",
  },
  {
    title: "VPN",
    description:
      "Stream your favorite shows from home. Pre-configured router, just plug in and watch US/UK content.",
    icon: <Lock className="h-8 w-8 text-primary" />,
    href: "/services/vpn",
  },
  {
    title: "Onsite Support",
    description:
      "English-speaking technicians at your home or office. Router setup, network issues, and device help.",
    icon: <Wrench className="h-8 w-8 text-primary" />,
    href: "/services/onsite",
  },
];

const supportDownloads = [
  {
    title: "Acronis Quick Assist",
    href: "https://www.acronis.com/en/products/cloud/quick-assist/download/",
    image: "/assets/images/arconis.png",
    description:
      "Secure remote desktop tool for quick troubleshooting. Our technicians can view your screen and resolve issues in real-time.",
    useCase: "Best for: General tech support & diagnostics",
  },
  {
    title: "TeamViewer QS",
    href: "https://get.teamviewer.com/tokyo",
    image: "/assets/images/teamviewer.png",
    description:
      "Industry-standard remote access software. Allows our team to securely connect to your device for hands-on assistance.",
    useCase: "Best for: Complex configurations & file transfers",
  },
];

// Mobile quick services (top 3 most popular)
const mobileQuickServices = personalServices.slice(0, 3);

// =============================================================================
// FORM VALIDATION
// =============================================================================

function validateEmail(email: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

function validateForm(data: FormData): FormErrors {
  const errors: FormErrors = {};

  if (!data.subject) {
    errors.subject = "Please select a topic";
  }
  if (!data.name.trim()) {
    errors.name = "Name is required";
  }
  if (!data.email.trim()) {
    errors.email = "Email is required";
  } else if (!validateEmail(data.email)) {
    errors.email = "Please enter a valid email address";
  }
  if (!data.message.trim()) {
    errors.message = "Message is required";
  } else if (data.message.trim().length < 10) {
    errors.message = "Message must be at least 10 characters";
  }

  return errors;
}

// =============================================================================
// MAIN COMPONENT
// =============================================================================

/**
 * PublicLandingView - Marketing-focused landing page
 *
 * Purpose: Hook visitors, build trust, guide to shop.
 * Contains:
 * - Hero with tagline
 * - Solutions carousel
 * - Trust & Support sections
 */
export function PublicLandingView() {
  // Carousel state
  const carouselRef = useRef<HTMLDivElement>(null);
  const itemWidthRef = useRef(0);
  const [currentSlide, setCurrentSlide] = useState(0);
  const isScrollingRef = useRef(false);
  const autoScrollTimerRef = useRef<NodeJS.Timeout | null>(null);
  const touchStartXRef = useRef(0);
  const touchEndXRef = useRef(0);

  // Section state
  const [activeCategory, setActiveCategory] = useState<ServiceCategory>("personal");
  const [remoteSupportTab, setRemoteSupportTab] = useState(0);

  // Form state
  const [formData, setFormData] = useState<FormData>({
    subject: "",
    name: "",
    email: "",
    phone: "",
    message: "",
  });
  const [formErrors, setFormErrors] = useState<FormErrors>({});
  const [formTouched, setFormTouched] = useState<FormTouched>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitStatus, setSubmitStatus] = useState<"idle" | "success" | "error">("idle");

  // Intersection Observer refs for animations
  const [heroRef, heroInView] = useInView();
  const [trustRef, trustInView] = useInView();
  const [solutionsRef, solutionsInView] = useInView();
  const [popularRef, popularInView] = useInView();
  const [supportRef, supportInView] = useInView();
  const [contactRef, contactInView] = useInView();

  // Hero CTA visibility for sticky mobile CTA
  const heroCTARef = useRef<HTMLDivElement>(null);
  const [showStickyCTA, setShowStickyCTA] = useState(false);

  // =============================================================================
  // CAROUSEL LOGIC
  // =============================================================================

  const computeItemWidth = useCallback(() => {
    const container = carouselRef.current;
    if (!container) return;

    const card = container.querySelector<HTMLElement>("[data-service-card]");
    if (!card) return;

    const gap =
      Number.parseFloat(getComputedStyle(container).columnGap || "0") ||
      Number.parseFloat(getComputedStyle(container).gap || "0") ||
      24;

    itemWidthRef.current = card.getBoundingClientRect().width + gap;
  }, []);

  const scrollByOne = useCallback((direction: 1 | -1) => {
    const container = carouselRef.current;
    if (!container || !itemWidthRef.current || isScrollingRef.current) return;

    isScrollingRef.current = true;

    container.scrollBy({
      left: direction * itemWidthRef.current,
      behavior: "smooth",
    });

    setTimeout(() => {
      isScrollingRef.current = false;
    }, 500);
  }, []);

  const scrollToIndex = useCallback((index: number) => {
    const container = carouselRef.current;
    if (!container || !itemWidthRef.current) return;

    container.scrollTo({
      left: index * itemWidthRef.current,
      behavior: "smooth",
    });
  }, []);

  const updateCurrentSlide = useCallback(() => {
    const container = carouselRef.current;
    if (!container || !itemWidthRef.current) return;

    const scrollLeft = container.scrollLeft;
    const newIndex = Math.round(scrollLeft / itemWidthRef.current);
    setCurrentSlide(Math.max(0, Math.min(newIndex, services.length - 1)));
  }, []);

  const startAutoScroll = useCallback(() => {
    if (autoScrollTimerRef.current) {
      clearInterval(autoScrollTimerRef.current);
    }

    autoScrollTimerRef.current = setInterval(() => {
      scrollByOne(1);
    }, 5000);
  }, [scrollByOne]);

  const stopAutoScroll = useCallback(() => {
    if (autoScrollTimerRef.current) {
      clearInterval(autoScrollTimerRef.current);
      autoScrollTimerRef.current = null;
    }
  }, []);

  // Touch swipe handlers
  const handleTouchStart = useCallback((e: React.TouchEvent) => {
    const touch = e.touches[0];
    if (touch) {
      touchStartXRef.current = touch.clientX;
      touchEndXRef.current = touch.clientX;
    }
  }, []);

  const handleTouchMove = useCallback((e: React.TouchEvent) => {
    const touch = e.touches[0];
    if (touch) {
      touchEndXRef.current = touch.clientX;
    }
  }, []);

  const handleTouchEnd = useCallback(() => {
    const diff = touchStartXRef.current - touchEndXRef.current;
    const minSwipeDistance = 50;

    if (Math.abs(diff) > minSwipeDistance) {
      if (diff > 0) {
        scrollByOne(1); // Swipe left = next
      } else {
        scrollByOne(-1); // Swipe right = prev
      }
    }
    startAutoScroll();
  }, [scrollByOne, startAutoScroll]);

  // =============================================================================
  // FORM HANDLERS
  // =============================================================================

  const handleInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
      const { name, value } = e.target;
      setFormData(prev => ({ ...prev, [name]: value }));

      // Clear error when user starts typing
      if (formErrors[name as keyof FormErrors]) {
        setFormErrors(prev => ({ ...prev, [name]: undefined }));
      }
    },
    [formErrors]
  );

  const handleInputBlur = useCallback(
    (e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
      const { name } = e.target;
      setFormTouched(prev => ({ ...prev, [name]: true }));

      // Validate single field on blur
      const errors = validateForm(formData);
      if (errors[name as keyof FormErrors]) {
        setFormErrors(prev => ({ ...prev, [name]: errors[name as keyof FormErrors] }));
      }
    },
    [formData]
  );

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();

      // Validate all fields
      const errors = validateForm(formData);
      setFormErrors(errors);
      setFormTouched({ subject: true, name: true, email: true, message: true });

      if (Object.keys(errors).length > 0) {
        return;
      }

      setIsSubmitting(true);
      setSubmitStatus("idle");

      try {
        // Simulate API call - replace with actual endpoint
        await new Promise(resolve => {
          setTimeout(resolve, 1500);
        });

        // Success
        setSubmitStatus("success");
        setFormData({ subject: "", name: "", email: "", phone: "", message: "" });
        setFormTouched({});
        setFormErrors({});

        // Reset success message after 5 seconds
        setTimeout(() => setSubmitStatus("idle"), 5000);
      } catch {
        setSubmitStatus("error");
      } finally {
        setIsSubmitting(false);
      }
    },
    [formData]
  );

  // =============================================================================
  // EFFECTS
  // =============================================================================

  // Initialize carousel
  useEffect(() => {
    computeItemWidth();

    const handleResize = () => computeItemWidth();
    window.addEventListener("resize", handleResize);

    startAutoScroll();

    return () => {
      window.removeEventListener("resize", handleResize);
      stopAutoScroll();
    };
  }, [computeItemWidth, startAutoScroll, stopAutoScroll]);

  // Track carousel scroll position
  useEffect(() => {
    const container = carouselRef.current;
    if (!container) return;

    const handleScroll = () => {
      updateCurrentSlide();
    };

    container.addEventListener("scroll", handleScroll, { passive: true });
    return () => container.removeEventListener("scroll", handleScroll);
  }, [updateCurrentSlide]);

  // Sticky CTA visibility
  useEffect(() => {
    const ctaElement = heroCTARef.current;
    if (!ctaElement) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry) {
          setShowStickyCTA(!entry.isIntersecting);
        }
      },
      { threshold: 0 }
    );

    observer.observe(ctaElement);
    return () => observer.disconnect();
  }, []);

  // Pause auto-scroll on hover
  const handleMouseEnter = useCallback(() => {
    stopAutoScroll();
  }, [stopAutoScroll]);

  const handleMouseLeave = useCallback(() => {
    startAutoScroll();
  }, [startAutoScroll]);

  const handlePrevClick = useCallback(() => {
    scrollByOne(-1);
    startAutoScroll();
  }, [scrollByOne, startAutoScroll]);

  const handleNextClick = useCallback(() => {
    scrollByOne(1);
    startAutoScroll();
  }, [scrollByOne, startAutoScroll]);

  // =============================================================================
  // RENDER HELPERS
  // =============================================================================

  const getInputClassName = (fieldName: keyof FormErrors) => {
    const baseClass =
      "w-full rounded-md border px-4 py-3 text-sm focus-visible:outline-none focus-visible:ring-2 bg-white transition-colors";
    const hasError = formTouched[fieldName] && formErrors[fieldName];
    return `${baseClass} ${
      hasError
        ? "border-danger focus-visible:ring-danger/60"
        : "border-border focus-visible:ring-primary/60"
    }`;
  };

  // =============================================================================
  // RENDER
  // =============================================================================

  return (
    <div className="space-y-0 pb-8 pt-0">
      {/* Hero Section */}
      <section
        ref={heroRef as React.RefObject<HTMLElement>}
        className={`relative left-1/2 right-1/2 w-screen -translate-x-1/2 py-12 sm:py-16 overflow-hidden transition-all duration-700 ${
          heroInView ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
        }`}
      >
        {/* Gradient Background */}
        <div className="absolute inset-0 bg-gradient-to-br from-slate-50 via-white to-sky-50/80" />

        {/* Dot Grid Pattern Overlay */}
        <div
          className="absolute inset-0 pointer-events-none"
          style={{
            backgroundImage: `radial-gradient(circle at center, oklch(0.65 0.05 234.4 / 0.15) 1px, transparent 1px)`,
            backgroundSize: "24px 24px",
          }}
        />

        {/* Subtle gradient accent in corner */}
        <div
          className="absolute -top-32 -right-32 w-96 h-96 rounded-full pointer-events-none"
          style={{
            background: "radial-gradient(circle, oklch(0.85 0.08 200 / 0.3) 0%, transparent 70%)",
          }}
        />

        <div className="relative mx-auto max-w-6xl grid grid-cols-1 lg:grid-cols-[1.05fr_minmax(0,0.95fr)] items-center gap-10 lg:gap-16 px-6 sm:px-10 lg:px-14">
          <div className="space-y-6 text-left max-w-2xl">
            <h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold leading-tight text-foreground">
              <span className="block whitespace-nowrap">A One Stop Solution</span>
              <span className="block text-primary mt-2 whitespace-nowrap">for Your IT Needs</span>
            </h1>
            <p className="text-base sm:text-lg text-muted-foreground leading-relaxed font-semibold">
              No Japanese required. Get reliable internet, mobile, and VPN services with full
              English support. Serving expats and international businesses for over 20 years.
            </p>
            <div
              ref={heroCTARef}
              className="flex flex-col sm:flex-row items-start sm:items-center gap-3 sm:gap-4 pt-2"
            >
              <Link
                href="/services"
                className="inline-flex items-center justify-center gap-2 rounded-full px-6 sm:px-8 py-3 text-base font-semibold bg-primary text-primary-foreground hover:bg-primary/90 shadow-md shadow-primary/20 transition-transform hover:-translate-y-0.5"
              >
                Browse Services
                <ArrowRight className="h-5 w-5" />
              </Link>
              <Link
                href="/contact"
                className="inline-flex items-center justify-center gap-2 rounded-full px-6 sm:px-8 py-3 text-base font-semibold border border-border bg-white text-primary hover:bg-primary/5 transition-colors"
              >
                Need Assistance?
              </Link>
            </div>
          </div>

          {/* Mobile Quick Services - visible on mobile only */}
          <div className="lg:hidden w-full">
            <div
              className="flex gap-3 overflow-x-auto pb-4 snap-x snap-mandatory"
              style={{ scrollbarWidth: "none" }}
            >
              {mobileQuickServices.map(service => (
                <Link
                  key={service.title}
                  href={service.href}
                  className="flex-shrink-0 w-[140px] snap-start group"
                >
                  <div className="flex flex-col items-center gap-2 p-4 rounded-xl border border-border/70 bg-white shadow-sm hover:shadow-md transition-shadow">
                    <div className="w-12 h-12 rounded-full border-2 border-primary/30 flex items-center justify-center group-hover:border-primary/60 transition-colors">
                      <div className="[&>svg]:h-6 [&>svg]:w-6">{service.icon}</div>
                    </div>
                    <span className="text-xs font-semibold text-foreground text-center">
                      {service.title}
                    </span>
                  </div>
                </Link>
              ))}
              <Link href="/services" className="flex-shrink-0 w-[140px] snap-start group">
                <div className="flex flex-col items-center justify-center gap-2 p-4 rounded-xl border border-dashed border-primary/40 bg-primary/5 h-full min-h-[120px] hover:bg-primary/10 transition-colors">
                  <ArrowRight className="h-6 w-6 text-primary" />
                  <span className="text-xs font-semibold text-primary text-center">
                    See All Services
                  </span>
                </div>
              </Link>
            </div>
          </div>

          {/* Desktop Services Panel - hidden on mobile */}
          <div className="hidden lg:block relative w-full">
            <div className="rounded-2xl border border-border/70 bg-white shadow-lg p-6">
              {/* Tab Switcher */}
              <div className="flex mb-6 bg-gray-100 rounded-full p-1">
                <button
                  type="button"
                  onClick={() => setActiveCategory("personal")}
                  className={`flex-1 py-2.5 px-4 text-sm font-semibold rounded-full transition-all ${
                    activeCategory === "personal"
                      ? "bg-gray-900 text-white shadow-md"
                      : "text-gray-600 hover:text-gray-900"
                  }`}
                >
                  Personal Services
                </button>
                <button
                  type="button"
                  onClick={() => setActiveCategory("business")}
                  className={`flex-1 py-2.5 px-4 text-sm font-semibold rounded-full transition-all ${
                    activeCategory === "business"
                      ? "bg-gray-900 text-white shadow-md"
                      : "text-gray-600 hover:text-gray-900"
                  }`}
                >
                  Business Services
                </button>
              </div>

              {/* Services Grid */}
              <div className="grid grid-cols-2 gap-3 h-[320px] content-start overflow-hidden">
                {(activeCategory === "personal" ? personalServices : businessServices).map(
                  service => (
                    <Link
                      key={service.title}
                      href={service.href}
                      className={`group flex flex-col items-center justify-center gap-2 p-3 rounded-xl hover:bg-gray-50 transition-colors ${
                        activeCategory === "personal" ? "h-[152px]" : "h-[100px]"
                      }`}
                    >
                      <div
                        className={`rounded-full border-2 border-primary/30 flex items-center justify-center group-hover:border-primary/60 transition-colors flex-shrink-0 ${
                          activeCategory === "personal" ? "w-20 h-20" : "w-14 h-14"
                        }`}
                      >
                        <div
                          className={
                            activeCategory === "personal"
                              ? "[&>svg]:h-10 [&>svg]:w-10"
                              : "[&>svg]:h-7 [&>svg]:w-7"
                          }
                        >
                          {service.icon}
                        </div>
                      </div>
                      <span
                        className={`font-semibold text-foreground text-center leading-tight ${
                          activeCategory === "personal" ? "text-sm" : "text-xs"
                        }`}
                      >
                        {service.title}
                      </span>
                    </Link>
                  )
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Gradient fade to next section */}
        <div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-b from-transparent to-white pointer-events-none" />
      </section>

      {/* Trust and Excellence Section */}
      <section
        ref={trustRef as React.RefObject<HTMLElement>}
        className={`relative left-1/2 right-1/2 w-screen -translate-x-1/2 bg-white transition-all duration-700 ${
          trustInView ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
        }`}
      >
        {/* Gradient fade to next section */}
        <div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-b from-transparent to-[#e8f5ff] pointer-events-none" />

        <div className="max-w-6xl mx-auto px-6 sm:px-10 lg:px-14 py-14 sm:py-16">
          <div className="grid grid-cols-1 lg:grid-cols-[1fr_1.1fr] gap-10 lg:gap-14 items-center">
            <div className="relative w-full overflow-hidden rounded-2xl shadow-md border border-border/60 bg-white aspect-[4/5]">
              <Image
                src="/assets/images/Why_us.png"
                alt="Team collaborating with trust and excellence"
                fill
                priority
                className="object-cover"
                sizes="(max-width: 1024px) 100vw, 40vw"
              />
            </div>
            <div className="space-y-6">
              <div>
                <h2 className="text-2xl sm:text-3xl font-extrabold text-primary uppercase tracking-wide mb-3">
                  Built on Trust and Excellence
                </h2>
                <p className="text-xl sm:text-2xl font-semibold text-foreground leading-relaxed">
                  For over two decades, we&apos;ve been helping foreigners, expats, and
                  international businesses in Japan navigate the tech landscape with confidence.
                </p>
              </div>

              <ul className="space-y-3 text-foreground">
                {[
                  "Full English support, no Japanese needed",
                  "Foreign credit cards accepted",
                  "Bilingual contracts and documentation",
                ].map(item => (
                  <li key={item} className="flex items-center gap-3 text-base font-semibold">
                    <BadgeCheck className="h-5 w-5 text-primary" />
                    <span>{item}</span>
                  </li>
                ))}
              </ul>
              <Link
                href="/about"
                className="inline-flex items-center gap-2 text-primary font-semibold hover:text-primary/80 transition-colors"
              >
                About our company
                <ArrowRight className="h-4 w-4" />
              </Link>
            </div>
          </div>
        </div>
      </section>

      {/* Solutions Carousel */}
      <section
        ref={solutionsRef as React.RefObject<HTMLElement>}
        className={`relative left-1/2 right-1/2 w-screen -translate-x-1/2 bg-[#e8f5ff] py-12 sm:py-14 transition-all duration-700 ${
          solutionsInView ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
        }`}
      >
        {/* Gradient fade to next section */}
        <div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-b from-transparent to-white pointer-events-none" />
        <div className="mx-auto max-w-6xl px-6 sm:px-10 lg:px-14">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-3xl sm:text-4xl font-extrabold text-foreground">Solutions</h2>
          </div>
          <div className="relative" onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
            <div
              ref={carouselRef}
              className="flex gap-6 overflow-x-auto scroll-smooth pb-6 pr-16 snap-x snap-mandatory"
              style={{ scrollbarWidth: "none", WebkitOverflowScrolling: "touch" }}
              onTouchStart={handleTouchStart}
              onTouchMove={handleTouchMove}
              onTouchEnd={handleTouchEnd}
            >
              {services.map((service, index) => (
                <Link
                  key={`${service.title}-${index}`}
                  href={service.href}
                  className="group flex-shrink-0 w-[260px] snap-start"
                >
                  <article
                    data-service-card
                    className="h-full rounded-3xl bg-white px-6 py-8 shadow-md border border-white/60 transition-transform duration-300 group-hover:-translate-y-1 flex flex-col"
                  >
                    <div className="mb-5">{service.icon}</div>
                    <h3 className="text-xl font-semibold text-foreground mb-3">{service.title}</h3>
                    <p className="text-muted-foreground leading-relaxed flex-grow">
                      {service.description}
                    </p>
                  </article>
                </Link>
              ))}
            </div>

            {/* Navigation buttons with larger touch targets */}
            <div className="absolute bottom-0 right-0 flex gap-3 pr-2">
              <button
                type="button"
                aria-label="Scroll solutions left"
                onClick={handlePrevClick}
                className="h-12 w-12 rounded-full border border-black/20 bg-white/80 text-foreground shadow-sm hover:bg-white transition-colors active:scale-95 flex items-center justify-center"
              >
                <span aria-hidden className="text-xl">
                  ‹
                </span>
              </button>
              <button
                type="button"
                aria-label="Scroll solutions right"
                onClick={handleNextClick}
                className="h-12 w-12 rounded-full border border-black/20 bg-white/80 text-foreground shadow-sm hover:bg-white transition-colors active:scale-95 flex items-center justify-center"
              >
                <span aria-hidden className="text-xl">
                  ›
                </span>
              </button>
            </div>
          </div>

          {/* Progress dots */}
          <div className="flex justify-center gap-2 mt-4">
            {services.map((_, index) => (
              <button
                key={index}
                className={`h-2 rounded-full transition-all duration-200 ${
                  currentSlide === index ? "bg-primary w-6" : "bg-primary/30 w-2"
                }`}
                onClick={() => scrollToIndex(index)}
                aria-label={`Go to slide ${index + 1}`}
              />
            ))}
          </div>
        </div>
      </section>

      {/* Most Popular Services Section */}
      <section
        ref={popularRef as React.RefObject<HTMLElement>}
        className={`relative left-1/2 right-1/2 w-screen -translate-x-1/2 bg-white py-14 sm:py-16 transition-all duration-700 ${
          popularInView ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
        }`}
      >
        <div className="max-w-6xl mx-auto px-6 sm:px-10 lg:px-14">
          {/* Section Header */}
          <div className="text-center mb-10 sm:mb-12">
            <h2 className="text-3xl sm:text-4xl font-extrabold text-foreground mb-4">
              Most Popular Services
            </h2>
            <p className="text-base sm:text-lg text-muted-foreground max-w-2xl mx-auto">
              Get connected with ease. No Japanese required, no complicated paperwork, and full
              English support every step of the way.
            </p>
          </div>

          {/* Two-column card layout */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 lg:gap-8">
            {/* Internet Plans Card */}
            <div className="relative rounded-2xl border border-sky-200 bg-white shadow-lg shadow-sky-100/50 p-6 sm:p-8 flex flex-col">
              {/* Popular Badge */}
              <div className="absolute top-4 right-4 sm:top-6 sm:right-6">
                <span className="inline-flex items-center rounded-full bg-primary px-3 py-1 text-xs font-bold text-white uppercase tracking-wide">
                  Popular
                </span>
              </div>

              {/* Icon Container */}
              <div className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl bg-sky-50 flex items-center justify-center mb-5">
                <Wifi className="h-8 w-8 sm:h-10 sm:w-10 text-primary" />
              </div>

              {/* Title */}
              <h3 className="text-xl sm:text-2xl font-bold text-foreground mb-3">Internet Plans</h3>

              {/* Description */}
              <p className="text-muted-foreground mb-5 leading-relaxed">
                High-speed fiber internet on Japan&apos;s reliable NTT network. We handle all the
                Japanese paperwork and coordinate installation in English.
              </p>

              {/* Feature List */}
              <ul className="space-y-3 mb-6 flex-grow">
                {[
                  "Speeds up to 10 Gbps available",
                  "English installation coordination",
                  "No Japanese contracts to sign",
                  "Foreign credit cards accepted",
                ].map(feature => (
                  <li key={feature} className="flex items-start gap-3">
                    <span className="flex-shrink-0 w-5 h-5 rounded-full bg-primary/10 flex items-center justify-center mt-0.5">
                      <Check className="h-3 w-3 text-primary" />
                    </span>
                    <span className="text-sm text-foreground">{feature}</span>
                  </li>
                ))}
              </ul>

              {/* CTA Button */}
              <Link
                href="/services/internet"
                className="w-full inline-flex items-center justify-center gap-2 rounded-full bg-primary px-6 py-3.5 text-base font-semibold text-primary-foreground hover:bg-primary/90 shadow-md shadow-primary/20 transition-all hover:-translate-y-0.5"
              >
                View Plans
                <ArrowRight className="h-5 w-5" />
              </Link>
            </div>

            {/* Phone Plans Card */}
            <div className="relative rounded-2xl border border-sky-200 bg-white shadow-lg shadow-sky-100/50 p-6 sm:p-8 flex flex-col">
              {/* Popular Badge */}
              <div className="absolute top-4 right-4 sm:top-6 sm:right-6">
                <span className="inline-flex items-center rounded-full bg-primary px-3 py-1 text-xs font-bold text-white uppercase tracking-wide">
                  Popular
                </span>
              </div>

              {/* Icon Container */}
              <div className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl bg-sky-50 flex items-center justify-center mb-5">
                <Smartphone className="h-8 w-8 sm:h-10 sm:w-10 text-primary" />
              </div>

              {/* Title */}
              <h3 className="text-xl sm:text-2xl font-bold text-foreground mb-3">Phone Plans</h3>

              {/* Description */}
              <p className="text-muted-foreground mb-5 leading-relaxed">
                Mobile SIM cards with voice and data on Japan&apos;s top network. Sign up online, no
                hanko needed, and get your SIM delivered fast.
              </p>

              {/* Feature List */}
              <ul className="space-y-3 mb-6 flex-grow">
                {[
                  "Data-only and voice + data options",
                  "Keep your number with MNP transfer",
                  "eSIM available for instant activation",
                  "Flexible plans with no long-term contracts",
                ].map(feature => (
                  <li key={feature} className="flex items-start gap-3">
                    <span className="flex-shrink-0 w-5 h-5 rounded-full bg-primary/10 flex items-center justify-center mt-0.5">
                      <Check className="h-3 w-3 text-primary" />
                    </span>
                    <span className="text-sm text-foreground">{feature}</span>
                  </li>
                ))}
              </ul>

              {/* CTA Button */}
              <Link
                href="/services/sim"
                className="w-full inline-flex items-center justify-center gap-2 rounded-full bg-primary px-6 py-3.5 text-base font-semibold text-primary-foreground hover:bg-primary/90 shadow-md shadow-primary/20 transition-all hover:-translate-y-0.5"
              >
                View Plans
                <ArrowRight className="h-5 w-5" />
              </Link>
            </div>
          </div>
        </div>
      </section>

      {/* Remote Support - Full section with mobile-optimized card layout */}
      <section
        ref={supportRef as React.RefObject<HTMLElement>}
        className={`relative left-1/2 right-1/2 w-screen -translate-x-1/2 bg-white py-12 sm:py-16 transition-all duration-700 overflow-hidden ${
          supportInView ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
        }`}
      >
        {/* Gradient fade to next section */}
        <div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-b from-transparent to-[#e8f5ff] pointer-events-none" />

        <div className="relative max-w-6xl mx-auto px-6 sm:px-10 lg:px-14">
          {/* Section header with connection metaphor */}
          <div className="flex items-center gap-4 mb-8">
            <div className="relative">
              <h2 className="text-3xl sm:text-4xl font-extrabold text-primary tracking-tight">
                Remote Support
              </h2>
              <p className="text-sm sm:text-base text-muted-foreground mt-2 max-w-md">
                Download one of our secure tools and let our technicians help you remotely
              </p>
            </div>
          </div>

          {/* Mobile: Stacked Cards Layout */}
          <div className="md:hidden space-y-4">
            {supportDownloads.map(item => (
              <div
                key={item.title}
                className="group relative bg-white rounded-2xl border border-border/60 shadow-sm hover:shadow-lg transition-all duration-300 overflow-hidden"
              >
                {/* Card accent line */}
                <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-sky-400 to-cyan-500" />

                <div className="p-5">
                  <div className="flex items-start gap-4">
                    {/* Tool icon with animated ring */}
                    <div className="relative flex-shrink-0">
                      <div className="w-16 h-16 rounded-xl flex items-center justify-center bg-gradient-to-br from-sky-50 to-cyan-100">
                        <Image
                          src={item.image}
                          alt={item.title}
                          width={48}
                          height={48}
                          className="object-contain w-10 h-10"
                        />
                      </div>
                      {/* Pulse indicator */}
                      <span className="absolute -top-1 -right-1 w-3 h-3 rounded-full bg-sky-400 animate-pulse" />
                    </div>

                    {/* Content */}
                    <div className="flex-1 min-w-0">
                      <h3 className="text-lg font-bold text-foreground mb-1">{item.title}</h3>
                      <p className="text-xs font-semibold uppercase tracking-wide mb-2 text-sky-600">
                        {item.useCase.replace("Best for: ", "")}
                      </p>
                      <p className="text-sm text-muted-foreground leading-relaxed line-clamp-2">
                        {item.description}
                      </p>
                    </div>
                  </div>

                  {/* Download button - full width on mobile for easy tapping */}
                  <Link
                    href={item.href}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mt-4 flex items-center justify-center gap-2 w-full rounded-xl py-3.5 text-sm font-semibold text-white transition-all duration-200 active:scale-[0.98] bg-gradient-to-r from-sky-500 to-cyan-600 hover:from-sky-600 hover:to-cyan-700"
                  >
                    <svg
                      className="w-4 h-4"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                      strokeWidth={2}
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
                      />
                    </svg>
                    Download {item.title.split(" ")[0]}
                  </Link>
                </div>
              </div>
            ))}
          </div>

          {/* Desktop: Tabbed Layout (improved) */}
          <div className="hidden md:block">
            <div className="bg-white rounded-3xl border border-border/60 shadow-lg overflow-hidden">
              {/* Tab buttons */}
              <div className="flex border-b border-border/40">
                {supportDownloads.map((item, index) => (
                  <button
                    key={item.title}
                    type="button"
                    onClick={() => setRemoteSupportTab(index)}
                    className={`flex-1 flex items-center justify-center gap-3 py-4 px-6 text-base font-medium transition-all duration-200 relative ${
                      remoteSupportTab === index
                        ? "text-primary bg-primary/5"
                        : "text-muted-foreground hover:text-foreground hover:bg-muted/30"
                    }`}
                    aria-pressed={remoteSupportTab === index}
                  >
                    <div
                      className={`w-10 h-10 rounded-lg flex items-center justify-center transition-colors ${
                        remoteSupportTab === index ? "bg-sky-100" : "bg-muted/50"
                      }`}
                    >
                      <Image
                        src={item.image}
                        alt=""
                        width={28}
                        height={28}
                        className="object-contain"
                      />
                    </div>
                    <span>{item.title}</span>
                    {/* Active indicator */}
                    {remoteSupportTab === index && (
                      <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-gradient-to-r from-sky-400 to-cyan-500" />
                    )}
                  </button>
                ))}
              </div>

              {/* Tab content */}
              {(() => {
                const currentDownload = supportDownloads[remoteSupportTab];
                if (!currentDownload) return null;
                return (
                  <div className="p-8 lg:p-12">
                    <div className="flex items-start gap-8 lg:gap-12">
                      <div className="h-32 w-32 lg:h-40 lg:w-40 rounded-2xl flex items-center justify-center flex-shrink-0 transition-colors bg-gradient-to-br from-sky-50 to-cyan-100">
                        <Image
                          src={currentDownload.image}
                          alt={currentDownload.title}
                          width={96}
                          height={96}
                          className="object-contain w-20 h-20 lg:w-24 lg:h-24"
                        />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-bold uppercase tracking-wide mb-2 text-sky-600">
                          {currentDownload.useCase}
                        </p>
                        <h3 className="text-2xl lg:text-3xl font-bold text-foreground mb-4">
                          {currentDownload.title}
                        </h3>
                        <p className="text-base lg:text-lg text-muted-foreground leading-relaxed mb-6">
                          {currentDownload.description}
                        </p>
                        <Link
                          href={currentDownload.href}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-2 rounded-full px-8 py-3.5 text-base font-semibold text-white transition-all duration-200 hover:-translate-y-0.5 hover:shadow-lg bg-gradient-to-r from-sky-500 to-cyan-600 hover:from-sky-600 hover:to-cyan-700 shadow-sky-200"
                        >
                          <svg
                            className="w-5 h-5"
                            fill="none"
                            viewBox="0 0 24 24"
                            stroke="currentColor"
                            strokeWidth={2}
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
                            />
                          </svg>
                          Download Now
                          <ArrowRight className="h-4 w-4" />
                        </Link>
                      </div>
                    </div>
                  </div>
                );
              })()}
            </div>
          </div>
        </div>
      </section>

      {/* Contact Section */}
      <section
        ref={contactRef as React.RefObject<HTMLElement>}
        className={`relative left-1/2 right-1/2 w-screen -translate-x-1/2 bg-[#e8f5ff] py-14 sm:py-16 transition-all duration-700 ${
          contactInView ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
        }`}
      >
        <div className="max-w-6xl mx-auto px-6 sm:px-10 lg:px-14 space-y-6">
          <h2 className="text-3xl sm:text-4xl font-extrabold text-foreground">CONTACT US</h2>
          <div className="rounded-3xl bg-white border border-primary/20 shadow-sm p-6 sm:p-8">
            <div className="grid grid-cols-1 lg:grid-cols-[1.1fr_0.9fr] gap-10 lg:gap-12">
              <div className="space-y-5">
                <div className="flex items-center gap-2 text-primary font-bold text-lg">
                  <Mail className="h-5 w-5" />
                  <span>By Online Form (Anytime)</span>
                </div>

                {/* Form Status Messages */}
                {submitStatus === "success" && (
                  <AlertBanner variant="success" title="Message sent successfully!">
                    Thank you for contacting us. We&apos;ll get back to you within 24 hours.
                  </AlertBanner>
                )}
                {submitStatus === "error" && (
                  <AlertBanner variant="error" title="Failed to send message">
                    Please try again or contact us directly by phone.
                  </AlertBanner>
                )}

                <form className="space-y-4" onSubmit={handleSubmit} noValidate>
                  {/* Subject Dropdown */}
                  <div className="space-y-1">
                    <label htmlFor="contact-subject" className="sr-only">
                      Subject
                    </label>
                    <select
                      id="contact-subject"
                      name="subject"
                      value={formData.subject}
                      onChange={handleInputChange}
                      onBlur={handleInputBlur}
                      aria-required="true"
                      aria-invalid={formTouched.subject && !!formErrors.subject}
                      aria-describedby={formErrors.subject ? "subject-error" : undefined}
                      className={getInputClassName("subject")}
                    >
                      {CONTACT_SUBJECTS.map(option => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </select>
                    {formTouched.subject && formErrors.subject && (
                      <p id="subject-error" className="text-sm text-danger flex items-center gap-1">
                        <AlertCircle className="h-4 w-4" />
                        {formErrors.subject}
                      </p>
                    )}
                  </div>

                  {/* Name Input */}
                  <div className="space-y-1">
                    <label htmlFor="contact-name" className="sr-only">
                      Name
                    </label>
                    <input
                      id="contact-name"
                      type="text"
                      name="name"
                      placeholder="Name*"
                      value={formData.name}
                      onChange={handleInputChange}
                      onBlur={handleInputBlur}
                      aria-required="true"
                      aria-invalid={formTouched.name && !!formErrors.name}
                      aria-describedby={formErrors.name ? "name-error" : undefined}
                      className={getInputClassName("name")}
                    />
                    {formTouched.name && formErrors.name && (
                      <p id="name-error" className="text-sm text-danger flex items-center gap-1">
                        <AlertCircle className="h-4 w-4" />
                        {formErrors.name}
                      </p>
                    )}
                  </div>

                  {/* Email Input */}
                  <div className="space-y-1">
                    <label htmlFor="contact-email" className="sr-only">
                      Email
                    </label>
                    <input
                      id="contact-email"
                      type="email"
                      name="email"
                      placeholder="Email*"
                      value={formData.email}
                      onChange={handleInputChange}
                      onBlur={handleInputBlur}
                      aria-required="true"
                      aria-invalid={formTouched.email && !!formErrors.email}
                      aria-describedby={formErrors.email ? "email-error" : undefined}
                      className={getInputClassName("email")}
                    />
                    {formTouched.email && formErrors.email && (
                      <p id="email-error" className="text-sm text-danger flex items-center gap-1">
                        <AlertCircle className="h-4 w-4" />
                        {formErrors.email}
                      </p>
                    )}
                  </div>

                  {/* Phone Input (optional) */}
                  <div className="space-y-1">
                    <label htmlFor="contact-phone" className="sr-only">
                      Phone (optional)
                    </label>
                    <input
                      id="contact-phone"
                      type="tel"
                      name="phone"
                      placeholder="Phone (optional)"
                      value={formData.phone}
                      onChange={handleInputChange}
                      className="w-full rounded-md border border-border px-4 py-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 bg-white"
                    />
                  </div>

                  {/* Message Textarea */}
                  <div className="space-y-1">
                    <label htmlFor="contact-message" className="sr-only">
                      Inquiry
                    </label>
                    <textarea
                      id="contact-message"
                      name="message"
                      placeholder="Inquiry*"
                      rows={4}
                      value={formData.message}
                      onChange={handleInputChange}
                      onBlur={handleInputBlur}
                      aria-required="true"
                      aria-invalid={formTouched.message && !!formErrors.message}
                      aria-describedby={formErrors.message ? "message-error" : undefined}
                      className={`${getInputClassName("message")} resize-none`}
                    />
                    {formTouched.message && formErrors.message && (
                      <p id="message-error" className="text-sm text-danger flex items-center gap-1">
                        <AlertCircle className="h-4 w-4" />
                        {formErrors.message}
                      </p>
                    )}
                  </div>

                  {/* Submit Button */}
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="w-full inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-3 text-sm font-semibold text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
                  >
                    {isSubmitting ? (
                      <>
                        <Spinner size="sm" />
                        Sending...
                      </>
                    ) : submitStatus === "success" ? (
                      <>
                        <CheckCircle className="h-4 w-4" />
                        Sent!
                      </>
                    ) : (
                      "Submit"
                    )}
                  </button>
                </form>

                <div className="flex flex-col gap-3">
                  <div className="inline-flex items-center gap-2 text-primary font-semibold">
                    <MessageSquare className="h-5 w-5" />
                    <span>By Chat (Anytime)</span>
                  </div>
                  <p className="text-sm text-foreground">
                    Click the bottom right &ldquo;Chat Button&rdquo; to reach our team anytime.
                  </p>
                  <div className="inline-flex items-center gap-2 text-primary font-semibold">
                    <PhoneCall className="h-5 w-5" />
                    <span>By Phone (9:30-18:00 JST)</span>
                  </div>
                  <div className="text-sm text-foreground">
                    <p className="font-semibold">Toll Free within Japan</p>
                    <p className="text-lg font-bold text-primary">0120-660-470</p>
                    <p className="font-semibold mt-1">From Overseas (may incur calling rates)</p>
                    <p className="text-lg font-bold text-primary">+81-3-3560-1006</p>
                  </div>
                </div>
              </div>

              <div className="space-y-6">
                <div className="w-full rounded-2xl overflow-hidden shadow-md border border-border/60 bg-white aspect-[4/3]">
                  <iframe
                    title="Assist Solutions Corp Map"
                    src="https://www.google.com/maps?q=Assist+Solutions+Corp,+3-8-2+Higashi+Azabu,+Minato-ku,+Tokyo&output=embed"
                    className="w-full h-full"
                    loading="lazy"
                    allowFullScreen
                    referrerPolicy="no-referrer-when-downgrade"
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="rounded-2xl bg-white shadow-sm border border-border/60 p-5 space-y-2">
                    <div className="inline-flex items-center gap-2 text-primary font-semibold">
                      <Train className="h-5 w-5" />
                      <span>Access</span>
                    </div>
                    <p className="text-sm text-foreground">
                      Subway Oedo Line / Nanboku Line
                      <br />
                      Short distance walk from exit 6 of Azabu-Juban Station
                      <br />
                      (1F of our building is Domino&apos;s Pizza)
                    </p>
                  </div>

                  <div className="rounded-2xl bg-white shadow-sm border border-border/60 p-5 space-y-2">
                    <div className="inline-flex items-center gap-2 text-primary font-semibold">
                      <MapPin className="h-5 w-5" />
                      <span>Address</span>
                    </div>
                    <p className="text-sm text-foreground">
                      3F Azabu Maruka Bldg.,
                      <br />
                      3-8-2 Higashi Azabu, Minato-ku,
                      <br />
                      Tokyo 106-0044
                      <br />
                      Tel: 03-3560-1006 Fax: 03-3560-1007
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Sticky Mobile CTA */}
      {showStickyCTA && (
        <div className="fixed bottom-0 left-0 right-0 bg-background/95 backdrop-blur-sm border-t border-border p-4 z-50 md:hidden animate-in slide-in-from-bottom-4 duration-300">
          <Link
            href="/services"
            className="flex items-center justify-center gap-2 w-full rounded-full bg-primary px-6 py-3 text-base font-semibold text-primary-foreground shadow-lg"
          >
            Browse Services
            <ArrowRight className="h-5 w-5" />
          </Link>
        </div>
      )}
    </div>
  );
}
