"use client";

import { memo, useState } from "react";
import Link from "next/link";
import { AnimatePresence, motion } from "framer-motion";
import { ArrowRight, ChevronLeft, ChevronRight } from "lucide-react";
import { cn } from "@/shared/utils";
import { useCarousel, useInView } from "@/features/landing-page/hooks";
import {
  personalConversionCards,
  businessConversionCards,
  type ConversionServiceCard,
  type CarouselAccent,
} from "@/features/landing-page/data";

type Tab = "personal" | "business";

/* ─── Accent color system ─── */

interface AccentStyles {
  iconBg: string;
  iconText: string;
  ctaBg: string;
  dotBg: string;
  border: string;
  glowFrom: string;
  cssVar: string;
}

const ACCENTS: Record<CarouselAccent, AccentStyles> = {
  blue: {
    iconBg: "bg-blue-500/12",
    iconText: "text-blue-600",
    ctaBg: "bg-blue-600 hover:bg-blue-700",
    dotBg: "bg-blue-600",
    border: "border-blue-500/20",
    glowFrom: "from-blue-500/5",
    cssVar: "var(--color-blue-500)",
  },
  emerald: {
    iconBg: "bg-emerald-500/12",
    iconText: "text-emerald-600",
    ctaBg: "bg-emerald-600 hover:bg-emerald-700",
    dotBg: "bg-emerald-600",
    border: "border-emerald-500/20",
    glowFrom: "from-emerald-500/5",
    cssVar: "var(--color-emerald-500)",
  },
  violet: {
    iconBg: "bg-violet-500/12",
    iconText: "text-violet-600",
    ctaBg: "bg-violet-600 hover:bg-violet-700",
    dotBg: "bg-violet-600",
    border: "border-violet-500/20",
    glowFrom: "from-violet-500/5",
    cssVar: "var(--color-violet-500)",
  },
  amber: {
    iconBg: "bg-amber-500/12",
    iconText: "text-amber-600",
    ctaBg: "bg-amber-600 hover:bg-amber-700",
    dotBg: "bg-amber-600",
    border: "border-amber-500/20",
    glowFrom: "from-amber-500/5",
    cssVar: "var(--color-amber-500)",
  },
  indigo: {
    iconBg: "bg-indigo-500/12",
    iconText: "text-indigo-600",
    ctaBg: "bg-indigo-600 hover:bg-indigo-700",
    dotBg: "bg-indigo-600",
    border: "border-indigo-500/20",
    glowFrom: "from-indigo-500/5",
    cssVar: "var(--color-indigo-500)",
  },
  cyan: {
    iconBg: "bg-cyan-500/12",
    iconText: "text-cyan-600",
    ctaBg: "bg-cyan-600 hover:bg-cyan-700",
    dotBg: "bg-cyan-600",
    border: "border-cyan-500/20",
    glowFrom: "from-cyan-500/5",
    cssVar: "var(--color-cyan-500)",
  },
  rose: {
    iconBg: "bg-rose-500/12",
    iconText: "text-rose-600",
    ctaBg: "bg-rose-600 hover:bg-rose-700",
    dotBg: "bg-rose-600",
    border: "border-rose-500/20",
    glowFrom: "from-rose-500/5",
    cssVar: "var(--color-rose-500)",
  },
  slate: {
    iconBg: "bg-slate-500/12",
    iconText: "text-slate-600",
    ctaBg: "bg-slate-600 hover:bg-slate-700",
    dotBg: "bg-slate-600",
    border: "border-slate-500/20",
    glowFrom: "from-slate-500/5",
    cssVar: "var(--color-slate-500)",
  },
};

/* ─── Framer Motion variants ─── */

const tabContentVariants = {
  enter: { opacity: 0, y: 20, scale: 0.98 },
  center: { opacity: 1, y: 0, scale: 1 },
  exit: { opacity: 0, y: -20, scale: 0.98 },
};

const headingVariants = {
  enter: { opacity: 0, y: 12 },
  center: { opacity: 1, y: 0 },
  exit: { opacity: 0, y: -12 },
};

/* ─── Service Card ─── */

const ServiceCard = memo(function ServiceCard({
  card,
  wasDragging,
}: {
  card: ConversionServiceCard;
  wasDragging: () => boolean;
}) {
  const a = ACCENTS[card.accent];

  return (
    <Link
      href={card.href}
      draggable={false}
      onClick={e => {
        if (wasDragging()) e.preventDefault();
      }}
      className={cn(
        "block rounded-3xl border overflow-hidden",
        "shadow-lg hover:shadow-xl transition-shadow duration-300",
        a.border
      )}
      style={{
        background: `linear-gradient(145deg, color-mix(in oklch, ${a.cssVar} 6%, white), white)`,
      }}
    >
      <div className="flex flex-col sm:flex-row gap-6 sm:gap-10 p-7 sm:p-10">
        <div className="flex-1 flex flex-col justify-center min-w-0">
          <div className="flex items-center gap-3 mb-5">
            <div
              className={cn(
                "h-12 w-12 rounded-2xl flex items-center justify-center shrink-0",
                a.iconBg,
                a.iconText
              )}
            >
              <div className="[&>svg]:h-6 [&>svg]:w-6">{card.icon}</div>
            </div>
            {card.badge && (
              <span className="inline-flex items-center rounded-full bg-success/10 text-success px-3 py-1 text-xs font-bold tracking-wide">
                {card.badge}
              </span>
            )}
          </div>

          <p className="text-sm font-medium text-muted-foreground mb-1">{card.problemHook}</p>
          <h3 className="text-2xl sm:text-3xl font-extrabold text-foreground mb-3 leading-tight">
            {card.title}
          </h3>
          <p className="text-[15px] text-muted-foreground leading-relaxed mb-6 max-w-lg">
            {card.description}
          </p>

          <span
            className={cn(
              "inline-flex items-center gap-2 rounded-full px-6 py-3 text-sm font-bold text-white",
              "transition-all duration-200 self-start shadow-md hover:shadow-lg hover:gap-3",
              a.ctaBg
            )}
          >
            {card.ctaLabel}
            <ArrowRight className="h-4 w-4" />
          </span>
        </div>

        <div
          className={cn(
            "hidden sm:flex items-center justify-center w-56 shrink-0",
            "rounded-2xl bg-gradient-to-br to-transparent",
            a.glowFrom
          )}
        >
          <div className="text-center px-6 py-8">
            <div
              className={cn(
                "h-16 w-16 rounded-2xl flex items-center justify-center mx-auto mb-4",
                a.iconBg,
                a.iconText
              )}
            >
              <div className="[&>svg]:h-8 [&>svg]:w-8">{card.icon}</div>
            </div>
            <p className="text-sm font-semibold text-foreground/80">{card.keyBenefit}</p>
          </div>
        </div>
      </div>
    </Link>
  );
});

/* ─── Header + Tab Toggle ─── */

const TAB_COPY: Record<Tab, { heading: string; subheading: string }> = {
  personal: {
    heading: "Personal Services",
    subheading: "Everything you need to stay connected in Japan",
  },
  business: {
    heading: "Business Services",
    subheading: "Enterprise connectivity solutions for your team",
  },
};

function CarouselHeader({
  activeTab,
  onTabChange,
}: {
  activeTab: Tab;
  onTabChange: (tab: Tab) => void;
}) {
  const copy = TAB_COPY[activeTab];

  return (
    <div className="mx-auto max-w-3xl px-6 sm:px-10 mb-10">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div className="min-h-[4.5rem]">
          <AnimatePresence mode="wait">
            <motion.div
              key={activeTab}
              variants={headingVariants}
              initial="enter"
              animate="center"
              exit="exit"
              transition={{ duration: 0.25, ease: "easeOut" }}
            >
              <h2 className="text-3xl sm:text-4xl font-extrabold text-foreground font-heading">
                {copy.heading}
              </h2>
              <p className="mt-2 text-lg text-muted-foreground">{copy.subheading}</p>
            </motion.div>
          </AnimatePresence>
        </div>
        <div className="flex bg-muted rounded-full p-1 self-start relative">
          {(["personal", "business"] as const).map(tab => (
            <button
              key={tab}
              type="button"
              onClick={() => onTabChange(tab)}
              className={cn(
                "relative z-10 px-5 py-2.5 text-sm font-semibold rounded-full transition-colors duration-300",
                activeTab === tab
                  ? "text-background"
                  : "text-muted-foreground hover:text-foreground"
              )}
            >
              {activeTab === tab && (
                <motion.span
                  layoutId="tab-indicator"
                  className="absolute inset-0 rounded-full bg-foreground shadow-sm"
                  transition={{ type: "spring", stiffness: 400, damping: 30 }}
                />
              )}
              <span className="relative z-10">
                {tab === "personal" ? "For You" : "For Business"}
              </span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ─── Dots + Arrow Navigation ─── */

function CarouselNav({
  cards,
  activeIndex,
  goTo,
  goPrev,
  goNext,
}: {
  cards: ConversionServiceCard[];
  activeIndex: number;
  goTo: (i: number) => void;
  goPrev: () => void;
  goNext: () => void;
}) {
  return (
    <div className="mx-auto max-w-3xl px-6 sm:px-10">
      <div className="flex items-center justify-center gap-6 mt-8">
        <button
          type="button"
          aria-label="Previous service"
          onClick={goPrev}
          className="h-10 w-10 rounded-full border border-border bg-card text-foreground shadow-sm hover:bg-muted transition-colors flex items-center justify-center"
        >
          <ChevronLeft className="h-5 w-5" />
        </button>
        <div className="flex items-center gap-2">
          {cards.map((card, i) => {
            const styles = ACCENTS[card.accent];
            return (
              <button
                key={`${card.title}-${i}`}
                type="button"
                aria-label={`Go to ${card.title}`}
                onClick={() => goTo(i)}
                className={cn(
                  "rounded-full transition-all duration-300 h-2.5",
                  i === activeIndex
                    ? cn("w-8", styles.dotBg)
                    : "w-2.5 bg-border hover:bg-muted-foreground"
                )}
              />
            );
          })}
        </div>
        <button
          type="button"
          aria-label="Next service"
          onClick={goNext}
          className="h-10 w-10 rounded-full border border-border bg-card text-foreground shadow-sm hover:bg-muted transition-colors flex items-center justify-center"
        >
          <ChevronRight className="h-5 w-5" />
        </button>
      </div>
    </div>
  );
}

/* ─── Slide styles ─── */

function slideStyles(offset: number, isDragging: boolean) {
  const absOffset = Math.abs(offset);
  const isVisible = absOffset < 2.5;
  const t = Math.min(absOffset, 2);

  const translateX = offset * 100;
  const scale = 1 - t * 0.15;
  const opacity = isVisible ? 1 - t * 0.3 : 0;
  const blur = t * 2;

  return {
    opacity,
    transform: `translateX(${translateX}%) scale(${scale})`,
    filter: blur > 0.1 ? `blur(${blur}px)` : "none",
    transition: isDragging ? "none" : "all 500ms cubic-bezier(0.25, 1, 0.5, 1)",
    zIndex: isVisible ? Math.round((1 - absOffset) * 10) : 0,
    pointerEvents: (absOffset < 0.5 ? "auto" : "none") as "auto" | "none",
    visibility: (isVisible ? "visible" : "hidden") as "visible" | "hidden",
  };
}

/* ─── Carousel track (extracted so AnimatePresence can swap it) ─── */

function CarouselTrack({
  cards,
  carousel,
}: {
  cards: ConversionServiceCard[];
  carousel: ReturnType<typeof useCarousel<ConversionServiceCard>>;
}) {
  const c = carousel;

  return (
    <>
      <div
        className="relative overflow-hidden select-none cursor-grab active:cursor-grabbing"
        onTouchStart={c.onTouchStart}
        onTouchMove={c.onTouchMove}
        onTouchEnd={c.onTouchEnd}
        onMouseDown={c.onMouseDown}
        onMouseMove={c.onMouseMove}
        onMouseUp={c.onMouseUp}
        onMouseLeave={c.onMouseLeave}
        onKeyDown={c.onKeyDown}
        tabIndex={0}
        role="region"
        aria-label="Services carousel"
        aria-roledescription="carousel"
      >
        <div className="mx-auto max-w-3xl px-6 sm:px-10">
          <div className="relative">
            {cards.map((card, i) => {
              const offset = c.getSlideOffset(i);
              const absOffset = Math.abs(offset);
              const isActive = absOffset < 0.5;
              const styles = slideStyles(offset, c.isDragging);

              return (
                <div
                  key={`${card.title}-${i}`}
                  className={cn(isActive ? "relative shadow-2xl rounded-3xl" : "absolute inset-0")}
                  style={styles}
                  role="group"
                  aria-roledescription="slide"
                  aria-label={`${i + 1} of ${c.total}: ${card.title}`}
                  aria-hidden={!isActive}
                >
                  <ServiceCard card={card} wasDragging={c.wasDragging} />
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <CarouselNav
        cards={cards}
        activeIndex={c.activeIndex}
        goTo={c.goTo}
        goPrev={c.goPrev}
        goNext={c.goNext}
      />
    </>
  );
}

/* ─── Main Carousel ─── */

export function ServicesCarousel() {
  const [activeTab, setActiveTab] = useState<Tab>("personal");
  const [sectionRef, isInView] = useInView<HTMLDivElement>();
  const cards = activeTab === "personal" ? personalConversionCards : businessConversionCards;
  const c = useCarousel({ items: cards, autoPlayMs: 10000 });

  const handleTabChange = (tab: Tab) => {
    if (tab === activeTab) return;
    setActiveTab(tab);
    c.reset();
  };

  return (
    <div
      ref={sectionRef}
      className={cn(
        "py-16 sm:py-20 transition-all duration-700",
        isInView ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
      )}
    >
      <CarouselHeader activeTab={activeTab} onTabChange={handleTabChange} />

      <AnimatePresence mode="wait">
        <motion.div
          key={activeTab}
          variants={tabContentVariants}
          initial="enter"
          animate="center"
          exit="exit"
          transition={{ duration: 0.3, ease: [0.25, 1, 0.5, 1] }}
        >
          <CarouselTrack cards={cards} carousel={c} />
        </motion.div>
      </AnimatePresence>
    </div>
  );
}
