import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import { ArrowRight, Server, Network, ShieldCheck, Cloud, MonitorSpeaker, Code2, Headphones } from "lucide-react";
import { SOLUTIONS } from "../data/solutions";

const PILLAR_ICONS: Record<string, typeof Server> = {
  server: Server, network: Network, shield: ShieldCheck, cloud: Cloud,
  "monitor-speaker": MonitorSpeaker, code: Code2, headset: Headphones,
};

// Tabbed platform showcase — one active pillar at a time with cinematic imagery,
// capability chips and an honest stat rail. Auto-cycles; pauses on hover/focus
// and under reduced motion. Light enterprise styling.
export default function PlatformShowcase() {
  const [active, setActive] = useState(0);
  const [paused, setPaused] = useState(false);
  const reduce = useReducedMotion();
  const s = SOLUTIONS[active];

  useEffect(() => {
    if (paused || reduce) return;
    const t = setInterval(() => setActive((a) => (a + 1) % SOLUTIONS.length), 6500);
    return () => clearInterval(t);
  }, [paused, reduce]);

  const onKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "ArrowDown" || e.key === "ArrowRight") {
      e.preventDefault();
      setActive((a) => (a + 1) % SOLUTIONS.length);
    } else if (e.key === "ArrowUp" || e.key === "ArrowLeft") {
      e.preventDefault();
      setActive((a) => (a - 1 + SOLUTIONS.length) % SOLUTIONS.length);
    }
  };

  return (
    <section
      className="relative bg-[#F6F8FA] py-24 md:py-32 overflow-hidden border-y border-[#E2E7EF]"
      data-testid="platform-showcase"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      <div className="grain" aria-hidden="true" />
      <div className="absolute -bottom-40 -left-40 h-[480px] w-[480px] rounded-full bg-cy/15 blur-[140px] pointer-events-none" aria-hidden="true" />
      <div className="mx-auto max-w-[1320px] px-5 md:px-10 relative">
        <div className="flex flex-col md:flex-row md:items-end md:justify-between gap-6 mb-14">
          <div>
            <p className="text-xs font-tech tracking-[0.35em] text-cydeep mb-5">PLATFORM SHOWCASE</p>
            <h2 className="font-display font-black text-4xl md:text-5xl text-[#101828] leading-[1.05] tracking-tight max-w-xl">
              Inside every practice.
            </h2>
          </div>
          <p className="font-tech text-[10px] tracking-[0.24em] text-mist/50" data-testid="showcase-hint">
            AUTO-CYCLING // HOVER TO PAUSE
          </p>
        </div>

        {/* Auto-cycle progress — shows time until the next tab */}
        {!paused && !reduce && (
          <motion.div
            key={active}
            className="h-px bg-gradient-to-r from-cydeep to-ember origin-left mb-10 -mt-6"
            initial={{ scaleX: 0 }}
            animate={{ scaleX: 1 }}
            transition={{ duration: 6.5, ease: "linear" }}
            data-testid="showcase-progress"
            aria-hidden="true"
          />
        )}

        <div className="grid lg:grid-cols-[300px_1fr] gap-8 lg:gap-12 items-start">
          {/* Tab rail */}
          <div role="tablist" aria-label="Solution pillars" onKeyDown={onKeyDown} className="flex lg:flex-col gap-1 overflow-x-auto lg:overflow-visible pb-2 lg:pb-0 -mx-5 px-5 lg:mx-0 lg:px-0">
            {SOLUTIONS.map((p, i) => {
              const Icon = PILLAR_ICONS[p.icon];
              const on = i === active;
              return (
                <button
                  key={p.slug}
                  role="tab"
                  id={`showcase-tab-${p.slug}`}
                  aria-selected={on}
                  aria-controls="showcase-panel"
                  tabIndex={on ? 0 : -1}
                  onClick={() => setActive(i)}
                  onMouseEnter={() => setActive(i)}
                  className={`shrink-0 lg:w-full text-left border-l-2 py-3.5 lg:py-4 pl-4 pr-5 flex items-center gap-3 transition-all duration-300 ${on ? "border-cydeep bg-white shadow-[0_10px_30px_-18px_rgba(10,31,68,0.25)]" : "border-[#E2E7EF] text-mist/55 hover:text-[#101828] hover:border-mist/50"}`}
                  data-testid={`showcase-tab-${p.slug}`}
                >
                  <Icon size={16} strokeWidth={1.6} className={`shrink-0 ${on ? "text-cydeep" : ""}`} aria-hidden="true" />
                  <span className={`font-tech text-[10px] tabular-nums ${on ? "text-cydeep" : "text-mist/40"}`}>{p.num}</span>
                  <span className={`text-[13px] font-bold whitespace-nowrap lg:whitespace-normal ${on ? "text-[#101828]" : ""}`}>{p.shortTitle}</span>
                </button>
              );
            })}
          </div>

          {/* Active panel */}
          <div role="tabpanel" id="showcase-panel" aria-labelledby={`showcase-tab-${s.slug}`} data-testid="showcase-panel">
            <AnimatePresence mode="wait">
              <motion.div
                key={s.slug}
                initial={reduce ? false : { opacity: 0, y: 18 }}
                animate={{ opacity: 1, y: 0 }}
                exit={reduce ? undefined : { opacity: 0, y: -12 }}
                transition={{ duration: 0.45, ease: [0.22, 1, 0.36, 1] }}
                className="grid md:grid-cols-2 gap-8 items-start"
              >
                <div className="relative border border-[#E2E7EF] p-2.5 bg-white shadow-[0_24px_60px_-30px_rgba(10,31,68,0.25)]">
                  <img
                    src={`/images/solutions/${s.slug}.jpg`}
                    alt={`${s.title} — Aviokan solution practice`}
                    loading="lazy"
                    className="w-full aspect-[4/3] object-cover"
                  />
                  <span className="absolute bottom-5 left-5 font-tech text-[10px] tracking-[0.25em] text-white/90 bg-[#14151A]/70 px-3 py-1.5 border border-white/15">
                    {s.num} // {s.shortTitle.toUpperCase()}
                  </span>
                </div>
                <div>
                  <h3 className="font-display font-black text-2xl md:text-3xl text-[#101828] leading-tight tracking-tight">{s.title}</h3>
                  <p className="mt-4 text-sm md:text-[15px] text-mist/70 leading-relaxed">{s.heroDesc}</p>
                  <div className="mt-6 flex flex-wrap gap-1.5">
                    {s.services.slice(0, 6).map((sv) => (
                      <span key={sv} className="text-[10px] font-tech border border-[#E2E7EF] bg-white text-mist/65 px-2.5 py-1">{sv}</span>
                    ))}
                    <span className="text-[10px] font-tech border border-ember/40 text-ember bg-white px-2.5 py-1">+{s.services.length - 6} more</span>
                  </div>
                  <div className="mt-8 grid grid-cols-3 gap-4 border-t border-[#E2E7EF] pt-6" data-testid="showcase-stats">
                    {[
                      { v: `${s.services.length}`, l: "CAPABILITIES" },
                      { v: `${s.oems.length}`, l: "OEM PARTNERS" },
                      { v: `${s.industries.length}`, l: "INDUSTRIES" },
                    ].map((st) => (
                      <div key={st.l}>
                        <p className="font-tech text-2xl md:text-3xl text-cydeep tabular-nums tracking-tight">{st.v}</p>
                        <p className="font-tech text-[9px] tracking-[0.2em] text-mist/55 mt-1.5">{st.l}</p>
                      </div>
                    ))}
                  </div>
                  <Link
                    to={`/solutions/${s.slug}`}
                    className="inline-flex items-center gap-2 text-xs font-bold text-ember mt-8 hover:gap-3.5 transition-all duration-300"
                    data-testid={`showcase-link-${s.slug}`}
                  >
                    Explore {s.shortTitle} <ArrowRight size={14} />
                  </Link>
                </div>
              </motion.div>
            </AnimatePresence>
          </div>
        </div>
      </div>
    </section>
  );
}
