"use client";

import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/cn";

type Quote = { initials: string; quote: string; name: string; role: string };

const ROW1: Quote[] = [
  {
    initials: "AP",
    quote:
      "The leadership at Franstek Belts thank each of you at ACGIL for ensuring that the go-live target is achieved. Together we can!",
    name: "Avinash G Pai",
    role: "Managing Director, Franstek Belts (CHIORINO Group, Italy)",
  },
  {
    initials: "SP",
    quote:
      "We are using Mx-ERP supplied & successfully implemented by M/s ACG Infotech Limited for past one year and is in fully commercial use.",
    name: "Management",
    role: "Shree Prayag Air Controls Pvt Ltd",
  },
  {
    initials: "PI",
    quote:
      "They are associated with us for past two years and we found them fully committed and supportive on regular basis.",
    name: "Authorised Signatory",
    role: "Passive Infra Projects Pvt Ltd",
  },
  {
    initials: "GE",
    quote:
      "We have been using ERP software of M/s ACG Infotech Limited to track procurement, inventory and for management reporting at our Energy project sites.",
    name: "K. Ramesh Babu",
    role: "General Manager – CMM, Greenko Energy Projects",
  },
  {
    initials: "BF",
    quote:
      "This project (Mx-ERP for Construction Management) is substantially completed and now operable.",
    name: "Hassan Tariq",
    role: "Managing Director, Bangladesh Foundry & Engineering Works",
  },
  {
    initials: "VL",
    quote:
      "We are using LAB-ERP supplied & successfully implemented by M/s ACG InfoTech Limited and is in full commercial use.",
    name: "Dr. Maneesh Kumar Gupta",
    role: "Director, All Vet Diagnostic Solutions",
  },
  {
    initials: "ST",
    quote:
      "The ERP is up and running. At this stage, the ERP can be declared ready for use.",
    name: "Edeha Prosper",
    role: "Head ICT, Starzs Investments, Nigeria",
  },
];

const PROOFS = [
  {
    initials: "HW",
    title: "Honeywell Automation India Ltd",
    body: "MX ERP implementation for Running Accounts Billing Management, ordered October 2022.",
    role: "Enterprise client",
  },
  {
    initials: "WA",
    title: "WAPCOS Ltd",
    body: "A Govt. of India undertaking engaged since 2011 on a Tamil Nadu project.",
    role: "Public sector engagement",
  },
  {
    initials: "SR",
    title: "SRS Limited",
    body: "Monitoring software delivered in seven months, running successfully since September 2010.",
    role: "Facilities & retail portfolio",
  },
];

function QuoteCard({ q }: { q: Quote }) {
  return (
    <figure className="flex w-[320px] shrink-0 flex-col rounded-2xl border border-line bg-white p-6 max-sm:w-[82vw]">
      <span aria-hidden="true" className="font-serif text-[36px] font-extrabold leading-[0.8] text-brand">
        &ldquo;
      </span>
      <blockquote className="mt-2 min-h-[96px] text-[14.5px] font-medium leading-relaxed text-ink">
        {q.quote}
      </blockquote>
      <figcaption className="mt-4 flex items-center gap-3 border-t border-line pt-4">
        <span
          aria-hidden="true"
          className="grid size-10 shrink-0 place-items-center rounded-full bg-navy font-display text-[13px] font-bold text-white"
        >
          {q.initials}
        </span>
        <span className="min-w-0">
          <b className="block truncate text-[13.5px] text-ink">{q.name}</b>
          <small className="block truncate text-[12px] text-muted">{q.role}</small>
        </span>
      </figcaption>
    </figure>
  );
}

function ProofCard({ p }: { p: (typeof PROOFS)[number] }) {
  return (
    <figure className="flex w-[320px] shrink-0 flex-col rounded-2xl border border-line bg-white p-6 max-sm:w-[82vw]">
      <span aria-hidden="true" className="font-serif text-[36px] font-extrabold leading-[0.8] text-brand">
        &ldquo;
      </span>
      <blockquote className="mt-2 min-h-[96px] text-[14.5px] font-medium leading-relaxed text-ink">
        {p.body}
      </blockquote>
      <figcaption className="mt-4 flex items-center gap-3 border-t border-line pt-4">
        <span
          aria-hidden="true"
          className="grid size-10 shrink-0 place-items-center rounded-full bg-navy font-display text-[13px] font-bold text-white"
        >
          {p.initials}
        </span>
        <span className="min-w-0">
          <b className="block truncate text-[13.5px] text-ink">{p.title}</b>
          <small className="block truncate text-[12px] text-muted">{p.role}</small>
        </span>
      </figcaption>
    </figure>
  );
}

function Row({
  reverse,
  label,
  children,
}: {
  reverse?: boolean;
  label: string;
  children: React.ReactNode;
}) {
  const outerRef = useRef<HTMLDivElement>(null);
  const drag = useRef<{ x: number; left: number } | null>(null);
  const hover = useRef(false);
  const [grabbing, setGrabbing] = useState(false);

  // One infinite mechanism: rAF advances scrollLeft; wrap-around at one
  // copy width makes manual + auto scrolling seamlessly endless.
  useEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    let raf = 0;
    const step = () => {
      const el = outerRef.current;
      if (el && !drag.current && !hover.current) {
        const half = el.scrollWidth / 2;
        if (half > 0) {
          let next = el.scrollLeft + (reverse ? -0.6 : 0.6);
          if (next >= half) next -= half;
          if (next < 0) next += half;
          el.scrollLeft = next;
        }
      }
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [reverse]);

  return (
    <div
      ref={outerRef}
      role="region"
      aria-label={`${label} — drag or use arrow keys to browse`}
      tabIndex={0}
      onMouseEnter={() => { hover.current = true; }}
      onMouseLeave={() => { hover.current = false; }}
      onKeyDown={(e) => {
        const el = outerRef.current;
        if (!el) return;
        if (e.key === "ArrowRight") el.scrollBy({ left: 340, behavior: "smooth" });
        if (e.key === "ArrowLeft") el.scrollBy({ left: -340, behavior: "smooth" });
      }}
      onPointerDown={(e) => {
        if (e.pointerType === "mouse" && e.button !== 0) return;
        const el = outerRef.current;
        if (!el) return;
        drag.current = { x: e.clientX, left: el.scrollLeft };
        setGrabbing(true);
        el.setPointerCapture(e.pointerId);
      }}
      onPointerMove={(e) => {
        const el = outerRef.current;
        if (!el || !drag.current) return;
        const half = el.scrollWidth / 2;
        let next = drag.current.left - (e.clientX - drag.current.x);
        if (half > 0) {
          // Wrap during the gesture too — never a blank edge
          next = ((next % half) + half) % half;
        }
        el.scrollLeft = next;
      }}
      onPointerUp={() => {
        drag.current = null;
        setGrabbing(false);
      }}
      onPointerCancel={() => {
        drag.current = null;
        setGrabbing(false);
      }}
      className={cn(
        "no-scrollbar cursor-grab overflow-x-auto pb-1",
        grabbing && "cursor-grabbing"
      )}
      style={{ touchAction: "pan-y" }}
    >
      <div className="flex w-max gap-5">
        <div className="flex shrink-0 gap-5">{children}</div>
        <div className="flex shrink-0 gap-5" aria-hidden="true">{children}</div>
      </div>
    </div>
  );
}

export default function TestimonialMarquee() {
  const row2 = [...PROOFS.map((p) => ({ kind: "proof" as const, p })), ...[ROW1[0], ROW1[1]].map((q) => ({ kind: "quote" as const, q }))];
  return (
    <div className="space-y-5">
      <Row label="Customer testimonials">
        {ROW1.map((q) => (
          <QuoteCard key={q.name} q={q} />
        ))}
      </Row>
      <Row reverse label="Enterprise and engagement proof">
        {row2.map((item, i) =>
          item.kind === "proof" ? (
            <ProofCard key={item.p.title} p={item.p} />
          ) : (
            <QuoteCard key={item.q.name + i} q={item.q} />
          )
        )}
      </Row>
    </div>
  );
}
