"use client";

import SectionBackdrop from "@/components/ui/SectionBackdrop";
import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent,
} from "react";
import Image from "next/image";
import { techStack } from "@/lib/content";
import { useReveal } from "@/hooks/use-reveal";

export default function Technologies() {
  const { ref, visible } = useReveal<HTMLDivElement>();
  const [activeId, setActiveId] = useState(techStack[0].id);
  const activeIndex = Math.max(
    0,
    techStack.findIndex((g) => g.id === activeId),
  );
  const active = techStack[activeIndex];

  const scrollerRef = useRef<HTMLDivElement>(null);
  const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const [indicator, setIndicator] = useState({
    left: 0,
    width: 0,
    ready: false,
  });

  // Slide the highlight under the active tab (re-measured on resize).
  useLayoutEffect(() => {
    function measure() {
      const tab = tabRefs.current[activeIndex];
      if (!tab) return;
      setIndicator({
        left: tab.offsetLeft,
        width: tab.offsetWidth,
        ready: true,
      });
    }
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, [activeIndex]);

  // Keep the active tab in view inside the scroller (mobile) without moving the page.
  useEffect(() => {
    const scroller = scrollerRef.current;
    const tab = tabRefs.current[activeIndex];
    if (!scroller || !tab) return;
    const target =
      tab.offsetLeft - (scroller.clientWidth - tab.offsetWidth) / 2;
    scroller.scrollTo({ left: Math.max(0, target), behavior: "smooth" });
  }, [activeIndex]);

  function onKeyDown(e: KeyboardEvent<HTMLDivElement>) {
    const last = techStack.length - 1;
    let next = activeIndex;
    if (e.key === "ArrowRight")
      next = activeIndex === last ? 0 : activeIndex + 1;
    else if (e.key === "ArrowLeft")
      next = activeIndex === 0 ? last : activeIndex - 1;
    else if (e.key === "Home") next = 0;
    else if (e.key === "End") next = last;
    else return;
    e.preventDefault();
    setActiveId(techStack[next].id);
    tabRefs.current[next]?.focus();
  }

  const enter = (delay: number) => ({
    className: visible ? "animate-fade-up" : "opacity-0",
    style: { animationDelay: `${delay}ms` },
  });

  const ActiveIcon = active.icon;
  const cols =
    active.items.length >= 3
      ? "sm:grid-cols-2 lg:grid-cols-3"
      : "sm:grid-cols-2";

  return (
    <section
      id="technologies"
      className="relative scroll-mt-24 overflow-x-clip py-20 sm:py-24 lg:py-32"
    >
      <TechBackground />

      <div className="container" ref={ref}>
        <div className="mx-auto max-w-3xl text-center">
          <p
            className={`inline-flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.24em] text-accent-600 ${enter(0).className}`}
            style={enter(0).style}
          >
            <span className="h-1.5 w-1.5 rounded-full bg-accent" />
            Technology Stack
          </p>
          <h2
            className={`mt-5 font-display text-[2rem] font-bold leading-[1.1] tracking-tight text-[#0F172A] sm:text-4xl lg:text-[2.9rem] ${enter(100).className}`}
            style={enter(100).style}
          >
            The technology behind our products
          </h2>
          <p
            className={`mx-auto mt-5 max-w-xl text-base leading-[1.75] text-ink-300 sm:text-lg ${enter(220).className}`}
            style={enter(220).style}
          >
            We build on mature, well-supported technologies so our products stay
            fast, secure and maintainable for years.
          </p>
        </div>

        {/* Tabs */}
        <div
          className={`mt-12 flex justify-center ${enter(340).className}`}
          style={enter(340).style}
        >
          <div className="max-w-full rounded-2xl border border-slate-200 bg-white p-1.5 shadow-card">
            <div ref={scrollerRef} className="no-scrollbar overflow-x-auto">
              <div
                role="tablist"
                aria-label="Technology categories"
                onKeyDown={onKeyDown}
                className="relative flex w-max gap-1"
              >
                <span
                  aria-hidden="true"
                  className={`absolute inset-y-0 rounded-xl border border-accent/25 bg-accent-50 shadow-[0_4px_14px_-6px_rgba(0,148,238,0.35)] transition-[transform,width] duration-300 ease-out ${
                    indicator.ready ? "opacity-100" : "opacity-0"
                  }`}
                  style={{
                    width: indicator.width,
                    transform: `translateX(${indicator.left}px)`,
                  }}
                />
                {techStack.map((group, i) => {
                  const Icon = group.icon;
                  const selected = group.id === activeId;
                  return (
                    <button
                      key={group.id}
                      ref={(el) => {
                        tabRefs.current[i] = el;
                      }}
                      id={`tech-tab-${group.id}`}
                      role="tab"
                      type="button"
                      aria-selected={selected}
                      aria-controls={`tech-panel-${group.id}`}
                      tabIndex={selected ? 0 : -1}
                      onClick={() => setActiveId(group.id)}
                      className={`relative z-10 inline-flex min-h-11 shrink-0 cursor-pointer items-center gap-2 rounded-xl px-4 text-sm font-semibold transition-colors duration-300 focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-0 sm:px-6 ${
                        selected
                          ? "text-accent"
                          : "text-ink-400 hover:text-slate-900"
                      }`}
                    >
                      <Icon
                        className="h-4 w-4"
                        strokeWidth={1.85}
                        aria-hidden
                      />
                      {group.category}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </div>

        {/* Panel */}
        <div
          className={`relative mx-auto mt-8 max-w-4xl ${enter(460).className}`}
          style={enter(460).style}
        >

          <div
            role="tabpanel"
            id={`tech-panel-${active.id}`}
            aria-labelledby={`tech-tab-${active.id}`}
            tabIndex={0}
            className="relative overflow-hidden rounded-3xl border border-slate-200 bg-white p-6 shadow-[0_24px_60px_-28px_rgba(15,23,42,0.2),0_2px_6px_rgba(15,23,42,0.04)] sm:p-9"
          >
            <ActiveIcon
              aria-hidden
              strokeWidth={1}
              className="pointer-events-none absolute -right-6 -top-6 h-48 w-48 text-accent/6 sm:h-64 sm:w-64"
            />

            <div key={active.id} className="animate-tab-in relative">
              <div className="flex items-center gap-4">
                <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl bg-accent/10 text-accent">
                  <ActiveIcon
                    className="h-6 w-6"
                    strokeWidth={1.75}
                    aria-hidden
                  />
                </span>
                <div>
                  <h3 className="font-display text-xl font-semibold tracking-tight text-[#0F172A] sm:text-2xl">
                    {active.title}
                  </h3>
                  <p className="mt-0.5 max-w-xl text-sm leading-relaxed text-ink-400">
                    {active.description}
                  </p>
                </div>
              </div>

              <ul className={`mt-8 grid grid-cols-1 gap-3.5 ${cols}`}>
                {active.items.map((item) => {
                  return (
                    <li key={item.name}>
                      <div className="group flex items-center gap-3.5 rounded-[14px] border border-slate-200 bg-white px-4 py-4 transition-all duration-200 ease-out hover:-translate-y-0.5 hover:border-accent-200 hover:shadow-[0_10px_24px_-14px_rgba(0,148,238,0.4)]">
                        <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-slate-200/70 bg-slate-50 transition-colors duration-200 group-hover:bg-accent/10">
                          <Image
                            src={item.logo}
                            alt=""
                            width={26}
                            height={26}
                            unoptimized
                            className="h-6.5 w-6.5 object-contain"
                          />
                        </span>
                        <span className="text-base font-semibold text-[#0F172A]">
                          {item.name}
                        </span>
                      </div>
                    </li>
                  );
                })}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function TechBackground() {
  return <SectionBackdrop variant="dots" />;
}
