"use client";

import { useState, useEffect, useCallback } from "react";
import { SectionHeading } from "@/components/ui/SectionHeading";
import { Reveal } from "@/components/ui/Reveal";
import { TeamCarousel } from "@/components/sections/team/TeamCarousel";
import { TeamMemberInfo } from "@/components/sections/team/TeamMemberInfo";
import { TeamProfile } from "@/components/sections/team/TeamProfile";
import type { SiteContent, ScheduleLocation } from "@/types/content";

interface TeamProps {
  data: SiteContent["team"];
  schedule?: ScheduleLocation[];
}

export function Team({ data: team, schedule }: TeamProps) {
  const [activeIndex, setActiveIndex] = useState(0);
  const [showProfile, setShowProfile] = useState(false);

  const openProfile = useCallback((index: number) => {
    setActiveIndex(index);
    setShowProfile(true);
    history.pushState({ trainerProfile: true }, "");
  }, []);

  const closeProfile = useCallback(() => {
    setShowProfile(false);
  }, []);

  const openTrainerByName = useCallback((name: string) => {
    const idx = team.members.findIndex((m) => m.name === name);
    if (idx >= 0) {
      openProfile(idx);
      setTimeout(() => {
        const el = document.getElementById("team");
        if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
      }, 50);
    }
  }, [team.members, openProfile]);

  // Handle browser back button
  useEffect(() => {
    function onPopState(e: PopStateEvent) {
      if (showProfile) {
        e.preventDefault();
        setShowProfile(false);
      }
    }
    window.addEventListener("popstate", onPopState);
    return () => window.removeEventListener("popstate", onPopState);
  }, [showProfile]);

  useEffect(() => {
    function handler(e: Event) {
      const name = (e as CustomEvent<string>).detail;
      if (name) openTrainerByName(name);
    }
    window.addEventListener("openTrainerProfile", handler);
    return () => window.removeEventListener("openTrainerProfile", handler);
  }, [openTrainerByName]);

  return (
    <section
      id="team"
      className="section-glow relative section-padding bg-neutral-50 dark:bg-[#050505] overflow-hidden"
    >
      <div className="section-divider absolute top-0 left-0 right-0" />

      {/* Stage spotlight glow */}
      <div
        className="pointer-events-none absolute inset-0"
        style={{
          background:
            "radial-gradient(ellipse 50% 70% at 50% 30%, rgba(201,169,110,0.07) 0%, transparent 70%)",
        }}
      />

      <div className="section-container">
        <Reveal>
          <SectionHeading centered>{team.title}</SectionHeading>
        </Reveal>
      </div>

      <Reveal>
        <div className="mt-10 px-4 sm:px-6">
          {!showProfile ? (
            <>
              <TeamCarousel
                members={team.members}
                activeIndex={activeIndex}
                onActiveChange={setActiveIndex}
              />

              <div className="mx-auto max-w-6xl">
                <TeamMemberInfo
                  members={team.members}
                  activeIndex={activeIndex}
                  onSelect={setActiveIndex}
                  onOpenBio={() => openProfile(activeIndex)}
                />
              </div>
            </>
          ) : (
            <TeamProfile
              member={team.members[activeIndex]}
              onBack={() => { history.back(); }}
              schedule={schedule}
            />
          )}
        </div>
      </Reveal>
    </section>
  );
}
