"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { ChevronLeft, ChevronRight, Star, UserCheck, FileText, CheckCircle2, Award } from "lucide-react";

export interface WriterItem {
  id: string | number;
  /** Real writer alias (from `getWriters()`), when known — links "View
   * Profile" to that writer's actual `/writers/{alias}` page. Absent for
   * the hardcoded `DEFAULT_WRITERS` network-outage fallback below, which
   * has no real profile to link to. */
  alias?: string;
  name: string;
  rating: number;
  completedProjects: number;
  qualification: string;
  bio: string;
  location: string;
  avatarUrl: string;
  sampleTitle?: string;
  sampleExcerpt?: string;
}

const DEFAULT_WRITERS: WriterItem[] = [
  {
    id: "w-1",
    name: "Sofia Macquire",
    rating: 5.0,
    completedProjects: 2344,
    qualification: "Master's Degree in Journalism",
    bio: "I have a master's degree in Journalism with a distinction from the University of South Australia.",
    location: "Australia",
    avatarUrl: "/images/defaultWritter.png",
    sampleTitle: "Journalism & Media Analysis",
    sampleExcerpt: "A comprehensive investigation into modern digital media ethics and editorial standards.",
  },
  {
    id: "w-2",
    name: "Jay Bond",
    rating: 5.0,
    completedProjects: 1657,
    qualification: "Master's Degree in Law",
    bio: "I hold a Master's degree in Tort Law from the University of Manchester, with over five years of academic research.",
    location: "UK",
    avatarUrl: "/images/defaultWritter.png",
    sampleTitle: "Comparative International Law",
    sampleExcerpt: "An analytical critique of cross-border trade governance and corporate dispute frameworks.",
  },
  {
    id: "w-3",
    name: "Stephen Barron",
    rating: 5.0,
    completedProjects: 450,
    qualification: "Ph.D. in Business Administration",
    bio: "I have almost ten years of experience working with students as a professional academic writer and consultant.",
    location: "USA",
    avatarUrl: "/images/defaultWritter.png",
    sampleTitle: "Strategic Management Frameworks",
    sampleExcerpt: "Strategic analysis on organizational change leadership during digital transformations.",
  },
  {
    id: "w-4",
    name: "Lucy Johansson",
    rating: 4.9,
    completedProjects: 1980,
    qualification: "DPhil in Atmospheric Physics",
    bio: "DPhil in Atmospheric & Planetary Physics from Oxford. Specializing in numerical modeling and environmental data.",
    location: "UK",
    avatarUrl: "/images/defaultWritter.png",
    sampleTitle: "Climate Systems & Environmental Policy",
    sampleExcerpt: "Quantitative assessment of atmospheric carbon dynamics and renewable energy transition models.",
  },
  {
    id: "w-5",
    name: "Hillary Clarke",
    rating: 4.8,
    completedProjects: 2150,
    qualification: "M.Sc. in Computer Science",
    bio: "Certified academic writer with 7+ years of experience in algorithm design, software architecture, and AI ethics.",
    location: "USA",
    avatarUrl: "/images/defaultWritter.png",
    sampleTitle: "Artificial Intelligence in Healthcare",
    sampleExcerpt: "Evaluating machine learning diagnostic accuracy and privacy-preserving federated learning pipelines.",
  },
  {
    id: "w-6",
    name: "Matilda Murphy",
    rating: 4.9,
    completedProjects: 1420,
    qualification: "Master of Public Health",
    bio: "Healthcare management expert helping students master health policy analysis, biostatistics, and hospital administration.",
    location: "UK",
    avatarUrl: "/images/defaultWritter.png",
    sampleTitle: "Epidemiological Data Analysis",
    sampleExcerpt: "Public health intervention strategies for post-pandemic healthcare system resilience.",
  },
];

/**
 * Recreates the exact paper sheet + orange right folder flap graphic
 * shown in the live site's reference image (`.Group .book`).
 */
function BookIcon() {
  return (
    <div className="relative shrink-0 w-12 h-16 sm:w-14 sm:h-18 flex items-center justify-center">
      <svg width="50" height="62" viewBox="0 0 50 62" fill="none" xmlns="http://www.w3.org/2000/svg">
        {/* White document sheet */}
        <rect x="2" y="2" width="36" height="56" rx="2" fill="white" stroke="#D1D5DB" strokeWidth="1.5" />
        {/* Grey document text lines */}
        <line x1="7" y1="12" x2="30" y2="12" stroke="#9CA3AF" strokeWidth="2" strokeLinecap="round" />
        <line x1="7" y1="18" x2="32" y2="18" stroke="#CBD5E1" strokeWidth="2" strokeLinecap="round" />
        <line x1="7" y1="24" x2="28" y2="24" stroke="#CBD5E1" strokeWidth="2" strokeLinecap="round" />
        <line x1="7" y1="30" x2="32" y2="30" stroke="#CBD5E1" strokeWidth="2" strokeLinecap="round" />
        <line x1="7" y1="36" x2="24" y2="36" stroke="#CBD5E1" strokeWidth="2" strokeLinecap="round" />
        <line x1="7" y1="42" x2="30" y2="42" stroke="#CBD5E1" strokeWidth="2" strokeLinecap="round" />
        {/* Right side orange/gold folder spine flap */}
        <path d="M38 4H44C45.1046 4 46 4.89543 46 6V54C46 55.1046 45.1046 56 44 56H38V4Z" fill="#F58E0E" />
        <line x1="38" y1="4" x2="38" y2="56" stroke="#D97706" strokeWidth="1" />
      </svg>
    </div>
  );
}

function getCpanelOrderUrl(writerName: string) {
  const baseUrl = process.env.NEXT_PUBLIC_CPANEL_URL || "https://customerpanel.globalassignmenthelp.com";
  return `${baseUrl}/Order?writer=${encodeURIComponent(writerName)}`;
}

const DEFAULT_AVATAR = "/images/defaultWritter.png";

/**
 * Writer avatar as a plain `<img>`, not `next/image`: the CMS host sits
 * behind Cloudflare bot protection that blocks `next/image`'s server-side
 * optimization fetch (403, confirmed on beta) — a plain `<img>` loads
 * directly in the visitor's own browser instead, which Cloudflare doesn't
 * challenge. The fallback itself is load-bearing, not defensive — writer
 * photos whose CMS paths 404 are a known, documented case for this install
 * (AGENTS.md lists `defaultWritter.png` for exactly this), so dropping it
 * would leave real gaps in the carousel.
 */
function WriterAvatar({ src, alt }: { src: string | null | undefined; alt: string }) {
  const [imgSrc, setImgSrc] = useState(src || DEFAULT_AVATAR);

  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={imgSrc}
      alt={alt}
      className="absolute inset-0 w-full h-full object-cover"
      onError={() => setImgSrc(DEFAULT_AVATAR)}
    />
  );
}

interface WritersCarouselProps {
  writers?: WriterItem[];
  title?: string;
  subtitle?: string;
}

export function WritersCarousel({
  writers = DEFAULT_WRITERS,
  subtitle = "Our Experts List",
  title = "Get Your Assignments Crafted by Our Experts Perfected for Excellence",
}: WritersCarouselProps) {
  const baseList = writers.length > 0 ? writers : DEFAULT_WRITERS;
  const N = baseList.length;

  // Tripled array to support smooth infinite looping without jump
  const extendedList = [...baseList, ...baseList, ...baseList];

  const [currentIndex, setCurrentIndex] = useState(N);
  const [isTransitioning, setIsTransitioning] = useState(true);
  const [isPaused, setIsPaused] = useState(false);
  const [selectedSample, setSelectedSample] = useState<WriterItem | null>(null);

  // Handle tab visibility change so auto-play pauses when browser tab is inactive
  useEffect(() => {
    const handleVisibility = () => {
      setIsPaused(document.hidden);
    };
    document.addEventListener("visibilitychange", handleVisibility);
    return () => document.removeEventListener("visibilitychange", handleVisibility);
  }, []);

  // Responsive cardsToShow detection (1 on mobile, 3 on desktop)
  const [cardsToShow, setCardsToShow] = useState(3);

  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth < 768) {
        setCardsToShow(1);
      } else {
        setCardsToShow(3);
      }
    };
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  // Auto-play interval for continuous sliding
  useEffect(() => {
    if (isPaused) return;
    const timer = setInterval(() => {
      handleNext();
    }, 2500);
    return () => clearInterval(timer);
  }, [isPaused, currentIndex]);

  // Failsafe boundary check effect in case CSS onTransitionEnd doesn't fire
  useEffect(() => {
    if (currentIndex >= 2 * N) {
      const timeout = setTimeout(() => {
        setIsTransitioning(false);
        setCurrentIndex((prev) => (prev >= 2 * N ? prev - N : prev));
      }, 750);
      return () => clearTimeout(timeout);
    } else if (currentIndex < N) {
      const timeout = setTimeout(() => {
        setIsTransitioning(false);
        setCurrentIndex((prev) => (prev < N ? prev + N : prev));
      }, 750);
      return () => clearTimeout(timeout);
    }
  }, [currentIndex, N]);

  const handleNext = () => {
    setIsTransitioning(true);
    setCurrentIndex((prev) => (prev >= 2 * N ? N + 1 : prev + 1));
  };

  const handlePrev = () => {
    setIsTransitioning(true);
    setCurrentIndex((prev) => (prev <= 0 ? N - 1 : prev - 1));
  };

  // Seamless wrap reset when reaching cloned boundaries
  const handleTransitionEnd = () => {
    if (currentIndex >= 2 * N) {
      setIsTransitioning(false);
      setCurrentIndex(currentIndex - N);
    } else if (currentIndex < N) {
      setIsTransitioning(false);
      setCurrentIndex(currentIndex + N);
    }
  };

  // Calculate safe index to prevent track from ever translating past available cards
  const maxAllowedIndex = extendedList.length - cardsToShow;
  const safeCurrentIndex = Math.min(Math.max(0, currentIndex), maxAllowedIndex);

  // Calculate center item for desktop highlighting
  const centerItemIndex = cardsToShow === 3 ? safeCurrentIndex + 1 : safeCurrentIndex;

  return (
    <section
      className="w-full py-10 sm:py-14 bg-white overflow-hidden relative"
      onMouseEnter={() => setIsPaused(true)}
      onMouseLeave={() => setIsPaused(false)}
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8">
        {/* Header Section — real `.home-heading`/`.home-subheading` classes
            (home-page.css, copied from the live `homenew.scss`), so the
            underline is the same sprite-based `:after` decoration used by
            every other homepage section heading (e.g. "How it Works ?"),
            not a separate invented bar. */}
        <div className="text-left mx-auto">
          <p className="home-heading">{subtitle}</p>
          <h2 className="home-subheading">{title}</h2>
        </div>

        {/* Carousel Viewport Wrapper */}
        <div className="relative px-2 sm:px-12">
          {/* Chevron Left Button */}
          <button
            onClick={handlePrev}
            aria-label="Previous Writer"
            className="absolute left-0 sm:left-2 top-1/2 -translate-y-1/2 z-30 w-10 h-10 sm:w-11 sm:h-11 rounded-full bg-slate-200/90 hover:bg-slate-300 text-slate-700 shadow-md flex items-center justify-center transition-all cursor-pointer hover:scale-105 active:scale-95"
          >
            <ChevronLeft className="w-5 h-5 sm:w-6 sm:h-6 stroke-[2.5]" />
          </button>

          {/* Chevron Right Button */}
          <button
            onClick={handleNext}
            aria-label="Next Writer"
            className="absolute right-0 sm:right-2 top-1/2 -translate-y-1/2 z-30 w-10 h-10 sm:w-11 sm:h-11 rounded-full bg-slate-200/90 hover:bg-slate-300 text-slate-700 shadow-md flex items-center justify-center transition-all cursor-pointer hover:scale-105 active:scale-95"
          >
            <ChevronRight className="w-5 h-5 sm:w-6 sm:h-6 stroke-[2.5]" />
          </button>

          {/* Overflow-Hidden Viewport */}
          <div className="overflow-hidden py-4">
            {/* Horizontal Track */}
            <div
              className={`flex ${isTransitioning ? "transition-transform duration-700 ease-in-out" : ""
                }`}
              style={{
                transform: `translateX(-${(safeCurrentIndex * 100) / cardsToShow}%)`,
              }}
              onTransitionEnd={handleTransitionEnd}
            >
              {extendedList.map((writer, idx) => {
                const isCenter = idx === centerItemIndex;

                return (
                  <div
                    key={`${writer.id}-${idx}`}
                    style={{ width: `${100 / cardsToShow}%` }}
                    className="shrink-0 px-2 lg:px-3 flex flex-col"
                  >
                    <div
                      className={`rounded-2xl p-5 transition-all duration-500 ease-in-out flex flex-col justify-between h-full ${isCenter
                        ? "bg-gradient-to-t from-[#EFFFDB] to-[#D8F7B1] border-2 border-[#8CBD48]/70 shadow-md scale-100 md:scale-105 z-10"
                        : "bg-[#F3F3F3] border border-slate-200/80 shadow-xs scale-95 opacity-90 hover:opacity-100"
                        }`}
                    >
                      {/* Top Profile Header (.profile_info) */}
                      <div className="flex items-center gap-3.5 pb-3 border-b border-[#51B53C]/40">
                        <div className="relative shrink-0 w-14 h-14 sm:w-16 sm:h-16 rounded-full overflow-hidden border-2 border-[#5C7A36] bg-slate-100 shadow-xs">
                          {/* `next/image` via `WriterAvatar`, not a plain
                              `<img>`: these render in a 56–64px circle but the
                              CMS serves 300x300 originals, so each downloaded
                              ~5x more than needed (Lighthouse: "300x300 for
                              displayed dimensions (60x60)", 359 KiB of savings
                              across the carousel). `sizes="64px"` makes Next
                              serve ~that width (plus a 2x retina variant) and
                              convert to WebP/AVIF. Needs the CMS host
                              allowlisted in `next.config.ts` — see
                              `cmsImageHostPatterns`. */}
                          <WriterAvatar src={writer.avatarUrl} alt={writer.name} />
                        </div>

                        <div className="flex-1 min-w-0">
                          <h3
                            className={`font-bold text-sm sm:text-base leading-snug truncate ${isCenter ? "text-[#345A05]" : "text-[#454545]"
                              }`}
                          >
                            {writer.name}
                          </h3>
                          <div className="flex items-center gap-1.5 mt-1 text-xs text-slate-700">
                            <span className="flex items-center gap-0.5 font-bold text-slate-800">
                              <Star className="w-3.5 h-3.5 fill-[#f58e0e] text-[#f58e0e]" />
                              {writer.rating.toFixed(1)}
                            </span>
                            <span className="font-medium truncate">{writer.completedProjects} Project Complete</span>
                          </div>
                        </div>
                      </div>

                      {/* Middle Section (.Group) - Sits directly on card background */}
                      <div className="py-3.5 border-b border-[#51B53C]/40 flex items-center gap-3">
                        <BookIcon />
                        <div className="flex-1 min-w-0">
                          <p className="text-xs sm:text-sm text-[#454545] leading-snug line-clamp-3 text-left">
                            {writer.bio}
                          </p>
                          <br />
                          <button
                            onClick={() => setSelectedSample(writer)}
                            className="inline-block mt-1 text-xs sm:text-sm text-black hover:text-[#5C7A36] transition-colors cursor-pointer"
                          >
                            View sample
                          </button>
                        </div>
                      </div>

                      {/* Bottom Action Row (.botom-buttons) */}
                      <div className="flex items-center justify-between pt-3">
                        {writer.alias ? (
                          <Link
                            href={`/writers/${writer.alias}`}
                            className="inline-flex items-center gap-1 text-xs sm:text-sm font-medium text-black hover:text-[#5C7A36] transition-colors cursor-pointer"
                          >
                            <UserCheck className="w-4 h-4 text-[#5C7A36]" />
                            View Profile
                          </Link>
                        ) : (
                          <button
                            onClick={() => setSelectedSample(writer)}
                            className="inline-flex items-center gap-1 text-xs sm:text-sm font-medium text-black hover:text-[#5C7A36] transition-colors cursor-pointer"
                          >
                            <UserCheck className="w-4 h-4 text-[#5C7A36]" />
                            View Profile
                          </button>
                        )}

                        <a
                          href={getCpanelOrderUrl(writer.name)}
                          className="!bg-[#F58E0E] hover:bg-green-600 !text-white font-semibold text-xs sm:text-sm px-4 py-1.5 rounded-[3px] shadow-xs transition-colors shrink-0 inline-block text-center"
                        >
                          Hire Writer
                        </a>

                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Dots Indicator */}
          <div className="flex items-center justify-center gap-2 mt-4">
            {baseList.map((_, idx) => {
              const activeDot = (currentIndex % N) === idx;
              return (
                <button
                  key={idx}
                  onClick={() => {
                    setIsTransitioning(true);
                    setCurrentIndex(N + idx);
                  }}
                  aria-label={`Go to slide ${idx + 1}`}
                  className={`h-2 rounded-full transition-all cursor-pointer ${activeDot ? "w-6 bg-[#5C7A36]" : "w-2 bg-slate-300 hover:bg-slate-400"
                    }`}
                />
              );
            })}
          </div>
        </div>
      </div>

      {/* Sample Detail Modal */}
      {selectedSample && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-xs animate-in fade-in duration-200">
          <div className="bg-white rounded-2xl shadow-xl max-w-lg w-full p-6 space-y-4 relative border border-slate-200">
            <button
              onClick={() => setSelectedSample(null)}
              className="absolute top-4 right-4 text-slate-400 hover:text-slate-600 font-bold text-xl w-8 h-8 rounded-full flex items-center justify-center hover:bg-slate-100"
            >
              ✕
            </button>

            <div className="flex items-center gap-4">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={selectedSample.avatarUrl || "/images/defaultWritter.png"}
                alt={selectedSample.name}
                className="w-14 h-14 rounded-full border-2 border-[#5C7A36] object-cover"
                onError={(e) => {
                  (e.target as HTMLImageElement).src = "/images/defaultWritter.png";
                }}
              />
              <div>
                <h3 className="font-bold text-lg text-slate-900">{selectedSample.name}</h3>
                <p className="text-xs text-slate-500 font-medium">{selectedSample.qualification} ({selectedSample.location})</p>
                <div className="flex items-center gap-1 text-xs text-amber-500 font-bold mt-0.5">
                  <Star className="w-3.5 h-3.5 fill-current" />
                  {selectedSample.rating.toFixed(1)} rating ({selectedSample.completedProjects} completed projects)
                </div>
              </div>
            </div>

            <div className="bg-slate-50 rounded-xl p-4 border border-slate-200 space-y-2">
              <h4 className="font-bold text-sm text-slate-800 flex items-center gap-1.5">
                <FileText className="w-4 h-4 text-[#5C7A36]" />
                {selectedSample.sampleTitle || "Academic Sample Overview"}
              </h4>
              <p className="text-xs text-slate-600 leading-relaxed">
                {selectedSample.sampleExcerpt || selectedSample.bio}
              </p>
            </div>

            <div className="space-y-1.5 text-xs text-slate-600">
              <div className="flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-green-600" />
                <span>Verified Native Academic Writer</span>
              </div>
              <div className="flex items-center gap-2">
                <Award className="w-4 h-4 text-[#f58e0e]" />
                <span>Top 1% Subject Expert in {selectedSample.location}</span>
              </div>
            </div>

            <div className="flex items-center justify-end gap-3 pt-2">
              <button
                onClick={() => setSelectedSample(null)}
                className="px-4 py-2 text-xs font-semibold text-slate-600 hover:text-slate-800"
              >
                Close
              </button>
              <a
                href={getCpanelOrderUrl(selectedSample.name)}
                className="bg-[#f58e0e] hover:bg-[#d77315] text-white font-bold text-xs px-5 py-2 rounded-lg shadow-sm transition-colors"
              >
                Hire {selectedSample.name.split(" ")[0]} Now
              </a>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}
