"use client";

import Link from "next/link";
import { useCallback, useEffect, useRef, useState } from "react";
import ToolIcon from "@/components/ToolIcon";
import { Price } from "@/lib/currency";

export type DeckTool = {
  name: string;
  slug: string;
  price: number;
  period: string;
  iconUrl?: string | null;
  features: string[];
  checkoutToken: string;
};

export default function HeroDeck({ tools }: { tools: DeckTool[] }) {
  const [current, setCurrent] = useState(0);
  const timer = useRef<ReturnType<typeof setInterval> | null>(null);
  const total = tools.length;

  const start = useCallback(() => {
    if (timer.current) return;
    timer.current = setInterval(() => {
      setCurrent((c) => (c + 1) % total);
    }, 3500);
  }, [total]);

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

  useEffect(() => {
    start();
    return stop;
  }, [start, stop]);

  const positionOf = (idx: number) => {
    let offset = idx - current;
    if (offset > total / 2) offset -= total;
    if (offset < -total / 2) offset += total;
    return Math.max(-2, Math.min(2, offset));
  };

  return (
    <div
      className="relative mx-auto h-[430px] w-full max-w-md select-none sm:h-[460px]"
      onMouseEnter={stop}
      onMouseLeave={start}
    >
      {tools.map((tool, idx) => {
        const pos = positionOf(idx);
        const isActive = pos === 0;
        const style: React.CSSProperties = {
          transform: `translateX(${pos * 44}px) translateY(${Math.abs(pos) * 18}px) scale(${
            1 - Math.abs(pos) * 0.08
          }) rotate(${pos * 3}deg)`,
          zIndex: 10 - Math.abs(pos),
          opacity: Math.abs(pos) === 2 ? 0.35 : 1,
        };
        return (
          <div
            key={tool.slug}
            style={style}
            onClick={() => !isActive && setCurrent(idx)}
            className={`absolute inset-x-0 top-0 mx-auto flex h-full max-w-sm cursor-pointer flex-col rounded-3xl border bg-white p-6 shadow-xl transition-all duration-700 ease-[cubic-bezier(0.16,1,0.3,1)] ${
              isActive ? "border-brand-200 shadow-brand-600/10" : "border-slate-100"
            }`}
          >
            <div className="flex items-center gap-4">
              <ToolIcon name={tool.name} iconUrl={tool.iconUrl} />
              <div>
                <Link
                  href={`/tools/${tool.slug}/`}
                  className="text-lg font-bold text-slate-900 hover:text-brand-600"
                >
                  {tool.name}
                </Link>
                <p className="text-sm font-semibold text-brand-600">
                  <Price bdt={tool.price} />
                  <span className="text-xs font-medium text-slate-400"> /mo</span>
                </p>
              </div>
            </div>
            <p className="mt-5 text-xs font-semibold text-slate-400">✨ Features:</p>
            <ul className="mt-2 flex-1 space-y-1.5 overflow-hidden">
              {tool.features.map((f, i) => (
                <li key={i} className="text-sm leading-relaxed text-slate-600">
                  {f}
                </li>
              ))}
            </ul>
            <Link
              href={`/checkout/${tool.checkoutToken}/`}
              className="mt-4 rounded-xl bg-brand-600 px-5 py-3 text-center text-sm font-semibold text-white transition-colors hover:bg-brand-700"
            >
              Get Now
            </Link>
          </div>
        );
      })}

      <div className="absolute -bottom-8 left-1/2 flex -translate-x-1/2 gap-2">
        {tools.map((_, idx) => (
          <button
            key={idx}
            aria-label={`Show card ${idx + 1}`}
            onClick={() => setCurrent(idx)}
            className={`h-2 rounded-full transition-all duration-300 ${
              idx === current ? "w-6 bg-brand-600" : "w-2 bg-slate-300 hover:bg-slate-400"
            }`}
          />
        ))}
      </div>
    </div>
  );
}
