/**
 * ThinkSchool Public Website — Interactive Product Showcase Component
 * Demonstrates real ERP interfaces with category switching, smooth cross-fading, and deep-dive points.
 */
function ProductShowcase() {
  const assetsConfig = window.ASSETS_CONFIG || {};
  const screenshots = assetsConfig.screenshots || {};

  const tabs = [
    {
      id: "overview",
      title: "Organization Command",
      eyebrow: "Multi-Campus Governance",
      subtitle: "Unified oversight of campuses, active student counts, and immediate role launchers.",
      screenshot: screenshots.adminOverview || {
        src: "/ASSETS/admin-overview.png",
        title: "Organization Overview",
        caption: "Switch authorized campuses and launch workspace tools from one overview.",
      },
      points: [
        "Campus switching with localized permission scopes",
        "Executive quick launchers for Office, Collections, Library, and Transport",
        "Student desk and admissions pipeline views",
      ],
    },
    {
      id: "analytics",
      title: "Decision-Ready Analytics",
      eyebrow: "Operational Intelligence",
      subtitle: "Attendance rates, fee collection percentages, and admissions queues in one reporting workspace.",
      screenshot: screenshots.analytics || {
        src: "/ASSETS/analytics-dashboard.png",
        title: "Analytics Dashboard",
        caption: "Cross-campus KPIs from the reporting workspace without end-of-month manual tallying.",
      },
      points: [
        "Aggregate student and staff attendance percentages across 30-day windows",
        "Fee collection tracking against outstanding receivables",
        "Automated attendance status distribution: Present, Absent, Late, Excused",
      ],
    },
    {
      id: "attendance-fees",
      title: "Attendance & Fee Trends",
      eyebrow: "Integrity & Trends",
      subtitle: "Calendar heatmaps pinpointing low-attendance days paired with expected vs collected fee lines.",
      screenshot: screenshots.attendanceFees || {
        src: "/ASSETS/attendance-fees.png",
        title: "Attendance Heatmap & Fee Trends",
        caption: "Calendar matrix revealing daily attendance variations alongside fee ledger runs.",
      },
      points: [
        "Day-by-day attendance heat grid highlighting unusual pattern drops",
        "Financial trend comparison: Expected vs Collected vs Refunded amounts",
        "Strict 24-hour edit windows preventing unauthorized historical record changes",
      ],
    },
    {
      id: "campus-collections",
      title: "Campus Collection Gaps",
      eyebrow: "Finance & Recovery",
      subtitle: "Identify which branches or campuses have fee collection shortfalls at a glance.",
      screenshot: screenshots.campusCollections || {
        src: "/ASSETS/campus-collections.png",
        title: "Campus Collection Gap Analysis",
        caption: "Branch-level collection comparison and donut chart position summary.",
      },
      points: [
        "Side-by-side fee realization by campus (Main Campus, Branch Campuses)",
        "Visual donut chart breakdown of collected versus outstanding dues",
        "Export-ready audit tables in CSV, XLSX, and HTML formats",
      ],
    },
  ];

  const [activeTab, setActiveTab] = React.useState(0);
  const sectionRef = React.useRef(null);
  const activeTabRef = React.useRef(0);
  const currentTab = tabs[activeTab];

  const selectTab = (index) => {
    activeTabRef.current = index;
    setActiveTab(index);
  };

  React.useEffect(() => {
    const section = sectionRef.current;

    if (
      !section ||
      typeof window.gsap === "undefined" ||
      typeof window.gsap.matchMedia !== "function" ||
      typeof window.ScrollTrigger === "undefined"
    ) {
      return undefined;
    }

    const mm = window.gsap.matchMedia();
    let refreshTimeout = null;
    const ctx = window.gsap.context(() => {
      mm.add("(min-width: 1024px) and (prefers-reduced-motion: no-preference)", () => {
        const display = section.querySelector("[data-showcase-display]");
        const tabButtons = Array.from(section.querySelectorAll("[data-showcase-tab]"));
        const endDistance = () => `+=${Math.max(window.innerHeight * 1.8, tabs.length * 260)}`;

        window.ScrollTrigger.create({
          id: "thinkschool-showcase-story",
          trigger: section,
          start: "top top+=80",
          end: endDistance,
          pin: true,
          anticipatePin: 1,
          invalidateOnRefresh: true,
          onUpdate: (self) => {
            const nextIndex = Math.min(tabs.length - 1, Math.floor(self.progress * tabs.length));

            if (nextIndex !== activeTabRef.current) {
              selectTab(nextIndex);
            }

            tabButtons.forEach((button, index) => {
              button.setAttribute("aria-current", index === nextIndex ? "step" : "false");
            });
          },
        });

        if (display) {
          window.gsap.to(display, {
            y: -18,
            rotation: 0.35,
            scale: 1.015,
            ease: "none",
            scrollTrigger: {
              trigger: section,
              start: "top top+=80",
              end: endDistance,
              scrub: 1,
              invalidateOnRefresh: true,
            },
          });
        }

        refreshTimeout = window.setTimeout(() => window.ScrollTrigger.refresh(), 150);
      });
    }, section);

    return () => {
      if (refreshTimeout !== null) {
        window.clearTimeout(refreshTimeout);
      }
      mm.revert();
      ctx.revert();
    };
  }, []);

  return (
    <section ref={sectionRef} id="showcase" className="py-24 md:py-32 bg-zinc-950 relative border-t border-b border-white/10">
      {/* Background radial accent */}
      <div
        className="absolute top-1/2 left-0 w-96 h-96 bg-amber-500/10 rounded-full blur-3xl pointer-events-none -translate-y-1/2 -z-10"
        aria-hidden="true"
      />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <SectionHeading
          eyebrow="Interactive Product Tour"
          title="See the actual ERP in action."
          description="ThinkSchool replaces guesswork with unified dashboards. Real interfaces built for speed, transparency, and institutional scale."
          align="center"
          className="mb-16"
        />

        {/* Tab Navigation Pill Bar */}
        <div className="flex items-center justify-start md:justify-center overflow-x-auto pb-4 mb-12 scrollbar-none gap-2">
          {tabs.map((tab, index) => {
            const isSelected = activeTab === index;
            return (
              <button
                key={tab.id}
                type="button"
                onClick={() => selectTab(index)}
                aria-pressed={isSelected}
                aria-current={isSelected ? "step" : "false"}
                data-showcase-tab
                className={`px-4 sm:px-6 py-2.5 rounded-full text-xs sm:text-sm font-medium font-body transition-all whitespace-nowrap select-none flex items-center gap-2 ${
                  isSelected
                    ? "bg-amber-500 text-black font-semibold shadow-[0_0_20px_rgba(245,158,11,0.3)] scale-[1.02]"
                    : "bg-zinc-900/80 text-zinc-400 hover:text-white hover:bg-zinc-800 border border-white/10"
                }`}
              >
                <span className="w-1.5 h-1.5 rounded-full bg-current" />
                <span>{tab.title}</span>
              </button>
            );
          })}
        </div>

        {/* Showcase Grid: Details on Left, Interactive Mockup on Right */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12 items-center">
          {/* Left Column: Narrative & Key Features */}
          <div className="lg:col-span-5 flex flex-col justify-center space-y-6">
            <div>
              <Badge variant="amber" className="mb-3">
                {currentTab.eyebrow}
              </Badge>
              <h3 className="text-2xl sm:text-3xl font-heading italic text-white leading-tight">
                {currentTab.subtitle}
              </h3>
            </div>

            <ul className="space-y-3.5 pt-2">
              {currentTab.points.map((point, i) => (
                <li key={i} className="flex items-start gap-3 text-sm text-zinc-300 font-body">
                  <span className="mt-0.5 w-5 h-5 rounded-full bg-amber-500/10 border border-amber-500/30 flex items-center justify-center shrink-0 text-amber-400">
                    <Icon name="check" size={12} />
                  </span>
                  <span>{point}</span>
                </li>
              ))}
            </ul>

            <div className="pt-4 flex items-center gap-4">
              <Button href="/contact/" size="sm" variant="primary">
                Request a Walkthrough
              </Button>
              <Button href="/features/" size="sm" variant="ghost">
                View All Modules →
              </Button>
            </div>
          </div>

          {/* Right Column: Dynamic Screenshot Frame */}
          <div className="lg:col-span-7 relative" data-showcase-display>
            <ScreenshotFrame
              key={currentTab.id}
              src={currentTab.screenshot.src}
              alt={currentTab.screenshot.title}
              title={`app.thinkschool.live/${currentTab.id}`}
              roleBadge={currentTab.screenshot.role || "Executive ERP Workspace"}
              caption={currentTab.screenshot.caption}
              glow={true}
              perspective={false}
              className="animate-fade-in"
            />
          </div>
        </div>
      </div>
    </section>
  );
}

window.ProductShowcase = ProductShowcase;
