"use client";


import React, { useRef, useState, useEffect, useCallback } from "react";
import { Target, Trophy, Zap, Globe, Handshake } from "lucide-react";

// --- Types ---
type HistoryEvent = {
  year: number;
  title: string;
  description: string;
  icon: typeof Target;
  accent: string; // e.g. "indigo-400"
};

// --- Data ---
const historyData: HistoryEvent[] = [
  { year: 2018, title: "Founding & Initial Vision", description: "The WING was established with a focus on data-driven strategic forecasting and defining core IP.", icon: Target, accent: "indigo-400" },
  { year: 2020, title: "Launch of M.E.R.A 1.0 Platform", description: "Launched the Market & Enterprise Research Analysis platform to accelerate analytics and insights.", icon: Zap, accent: "red-400" },
  { year: 2022, title: "Achieved Global Certification", description: "Received ISO 27001 certification for data security and expanded operations across regions.", icon: Globe, accent: "cyan-400" },
  { year: 2023, title: "Strategic Partnerships & Growth", description: "Formed strategic alliances with enterprise partners and rapidly scaled market presence.", icon: Handshake, accent: "green-400" },
  { year: 2025, title: "Innovation Award & Team Expansion", description: "Recognized with major innovation awards and expanded the team to support new initiatives.", icon: Trophy, accent: "yellow-400" },
];

/** map accent names to colors (tune as needed) */
const ACCENT_MAP: Record<string, string> = {
  "indigo-400": "#7c3aed",
  "red-400": "#ef4444",
  "cyan-400": "#06b6d4",
  "green-400": "#10b981",
  "yellow-400": "#f59e0b",
};

// --- Custom Breadcrumb Component (Provided by user) ---
// Note: Exporting this inline for a single file structure
const Breadcrumb = ({
  breadcrumbs,
  pageTitle,
  description,
  backgroundImageUrl = "/img/bg/breadcrumb.jpg",
}: {
  breadcrumbs: { name: string; href: string }[];
  pageTitle: string;
  description: string;
  backgroundImageUrl?: string;
}) => {
  return (
    <section className="relative w-full h-[350px] lg:h-[400px] overflow-hidden">
      <div className="absolute inset-0">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={backgroundImageUrl}
          alt="Page background"
          className="w-full h-full object-cover"
        />
        <div className="absolute inset-0 bg-gray-900 opacity-75"></div>
        <div className="absolute inset-0 bg-linear-to-t from-gray-900/10 to-transparent"></div>
      </div>

      <div className="relative max-w-5xl mx-auto h-full flex flex-col justify-center px-4 sm:px-8 lg:px-8 text-white z-10">
        <nav className="flex mb-4" aria-label="Breadcrumb">
          <ol className="inline-flex items-center space-x-2">
            {breadcrumbs.map((item, index) => {
              const isCurrent = index === breadcrumbs.length - 1;
              return (
                <li key={item.name} className="inline-flex items-center">
                  <a
                    href={item.href}
                    className={`text-sm font-medium transition-colors ${isCurrent
                      ? 'text-indigo-400'
                      : 'text-gray-300 hover:text-white'
                      }`}
                    aria-current={isCurrent ? 'page' : undefined}
                  >
                    {item.name}
                  </a>
                  {!isCurrent && (
                    <span className="mx-2 text-gray-500 text-sm" aria-hidden="true">/</span>
                  )}
                </li>
              );
            })}
          </ol>
        </nav>

        <h1 className="text-6xl sm:text-5xl lg:text-6xl font-extrabold mb-2 max-w-2xl leading-tight tracking-wide">
          {pageTitle}
        </h1>

        <p className="mt-1 text-lg text-gray-300 max-w-xl">
          {description}
        </p>
      </div>
    </section>
  );
};

const OurBrands = () => (
  <div className="py-10 bg-[#161616] text-center text-gray-500">
    OurBrands Section Placeholder
  </div>
);

/* --- Main page component --- */
export default function Overview() {

  // --- State and Logic ---
  const timelineRef = useRef<HTMLDivElement | null>(null);
  const [progressHeight, setProgressHeight] = useState<number>(0);

  const calculateProgress = useCallback(() => {
    const el = timelineRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const timelineTop = rect.top + window.scrollY;
    const timelineHeight = rect.height;
    const scrollY = window.scrollY;
    const scrolledDistance = scrollY - timelineTop + window.innerHeight / 2;
    const newHeight = Math.min(Math.max(0, scrolledDistance), timelineHeight);
    setProgressHeight(newHeight);
  }, []);

  useEffect(() => {
    calculateProgress();
    window.addEventListener("scroll", calculateProgress, { passive: true });
    window.addEventListener("resize", calculateProgress);
    return () => {
      window.removeEventListener("scroll", calculateProgress);
      window.removeEventListener("resize", calculateProgress);
    };
  }, [calculateProgress]);

  // --- Inline Helper Component (Timeline Event) ---
  function TimelineEvent({ event, index }: { event: HistoryEvent; index: number }): React.ReactElement {
    const Icon = event.icon;
    const accent = ACCENT_MAP[event.accent] || "#7c3aed";

    // Determine if the card should be on the left side (0, 2, 4...)
    const isLeft = index % 2 === 0;

    // Conditional classes for layout and text alignment
    const containerClass = isLeft ? 'md:justify-start' : 'md:justify-end';
    const cardMarginClass = isLeft ? 'md:mr-10' : 'md:ml-10';
    const textAlignmentClass = isLeft ? 'md:text-right' : 'md:text-left';

    // Icon/Year positioning classes relative to the central line (left: 50%)
    const yearPosition = isLeft ? 'md:right-full md:mr-8' : 'md:left-full md:ml-8';

    return (
      // Outer container: Uses flex to push the whole block left or right
      <div className={`mb-10 md:mb-14 flex ${containerClass}`}>

        {/* 1. Card Container (w-1/2 on desktop) */}
        <div className={`w-full md:w-1/2 ${cardMarginClass} ${textAlignmentClass}`}>
          <div
            className="rounded-xl p-6 shadow-lg bg-white/5 h-full transition-all duration-300 hover:scale-[1.02]"
            style={{
              [isLeft ? 'borderLeft' : 'borderRight']: `4px solid ${accent}`,
              background: "rgba(255,255,255,0.03)",
            }}
          >
            <h3 className="text-lg font-semibold" style={{ color: accent }}>
              {event.title}
            </h3>
            <p className="mt-2 text-sm text-gray-300 leading-relaxed">{event.description}</p>
          </div>
        </div>

        {/* 2. Central Separator Column (Only visible on desktop) */}
        <div className="hidden md:flex w-0 relative justify-center">

          {/* Icon Circle (Positioned absolutely over the line) */}
          <div
            className={`absolute w-12 h-12 rounded-full flex items-center justify-center shadow-md border-4 border-[#080216] z-10 transition-all duration-300 transform -translate-y-1/2 top-1/2`}
            style={{ backgroundColor: accent }}
            aria-hidden
          >
            <Icon size={18} className="text-white" />
          </div>

          {/* Year Label (Positioned absolutely next to the circle) */}
          <div
            className={`absolute py-1 px-3 rounded-full text-sm font-bold bg-white text-gray-900 shadow-md transform -translate-y-1/2 top-1/2 ${yearPosition}`}
            aria-hidden
          >
            {event.year}
          </div>
        </div>

        {/* Mobile fallback: small header / year above card */}
        <div className="md:hidden mt-2 pl-2">
          <div className="text-sm font-bold" style={{ color: accent }}>
            {event.year}
          </div>
        </div>
      </div>
    );
  }

  // --- Main Render ---
  const breadcrumbData = [
    { name: 'Who We Are', href: '/' },
    { name: 'Our-History', href: '/our-history' },
  ];

  // Data to pass to the Breadcrumb component
  const pageTitle = "The WING Timeline";
  const description = "A chronological journey through the pivotal milestones and achievements that define our history and shape our future commitment to excellence.";

  return (
    <main className="min-h-screen bg-[#080216] text-white">
      {/* 1. Breadcrumb Header (Using Custom Component) */}
      <Breadcrumb breadcrumbs={breadcrumbData} pageTitle={pageTitle} description={description} />

      {/* 2. Timeline Section */}
      <section className="py-20">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <div className="relative" ref={timelineRef}>

            {/* Central Vertical STATIC Line (Background) */}
            <div className="hidden md:block absolute left-1/2 top-0 h-full w-1 bg-gray-700 transform translate-x-1/2" />

            {/* Central Vertical PROGRESS Line (Foreground) */}
            <div
              className="hidden md:block absolute left-1/2 top-0 w-1 bg-indigo-500 transition-all duration-100 transform translate-x-1/2"
              style={{ height: `${progressHeight}px` }}
            />

            {/* Events */}
            <div className="space-y-8 md:space-y-12">
              {historyData.map((evt, idx) => (
                <TimelineEvent key={evt.year} event={evt} index={idx} />
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* 3. OurBrands (Placeholder) */}
      <OurBrands />
    </main>
  );
}