"use client";

import { useCallback, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import {
  ArrowRight,
  ClipboardCheck,
  FileBarChart,
  ScanLine,
  Settings2,
  TrendingUp,
  Workflow,
} from "lucide-react";
import RevealText from "@/components/immersive/RevealText";
import Reveal from "@/components/immersive/Reveal";
import { scrollToImmersiveSection } from "@/components/immersive/immersive-scroll";
import { prefersReducedMotion } from "@/components/immersive/gsap-setup";

const OUTCOMES = [
  {
    number: "01",
    title: "Present data you can trust",
    subtitle: "One reliable source for every decision.",
    module: 0,
  },
  {
    number: "02",
    title: "See the complete wealth picture",
    subtitle: "Every asset. Every portfolio. One view.",
    module: 0,
  },
  {
    number: "03",
    title: "Run more, with less manual work",
    subtitle: "Give your team capacity to focus on clients.",
    module: 1,
  },
  {
    number: "04",
    title: "Turn data into client-ready intelligence",
    subtitle: "From complex portfolios to clear conversations.",
    module: 2,
  },
];

type ModuleShot = {
  src: string;
  width: number;
  height: number;
  route: string;
  alt: string;
};

type Module = {
  number: string;
  icon: typeof TrendingUp;
  title: string;
  body: string;
  flow?: string[];
  shot?: ModuleShot;
};

const MODULES: Module[] = [
  {
    number: "01",
    icon: TrendingUp,
    title: "Portfolio Management",
    body: "Positions, transactions and cash flows reconciled into one book of record.",
    shot: {
      src: "/feature-1.png",
      width: 1727,
      height: 949,
      route: "app.oxyfinz.com/dashboard",
      alt: "Consolidated dashboard totalling every asset class against one valuation.",
    },
  },
  {
    number: "02",
    icon: Workflow,
    title: "Trade Lifecycle Management",
    body: "Order capture through settlement, without the manual handoffs.",
    flow: ["Capture", "Allocate", "Settle"],
  },
  {
    number: "03",
    icon: FileBarChart,
    title: "Reporting & Client Intelligence",
    body: "Dashboards, performance views and tailored client reporting.",
    shot: {
      src: "/feature-2.png",
      width: 1631,
      height: 865,
      route: "app.oxyfinz.com/reports/portfolio-analytics",
      alt: "Portfolio analytics with returns, holdings, liquidity and cash flows.",
    },
  },
  {
    number: "04",
    icon: ClipboardCheck,
    title: "Compliance & Regulatory",
    body: "Mandate and exposure monitoring with a complete audit trail.",
    flow: ["Mandate", "Exposure", "Audit"],
  },
  {
    number: "05",
    icon: ScanLine,
    title: "DeepDex Data Infrastructure",
    body: "Custodian feeds, market data and documents resolved into one schema.",
    shot: {
      src: "/feature-3.png",
      width: 1673,
      height: 506,
      route: "app.oxyfinz.com/reports/liquidity/cash-details",
      alt: "Cash and liquidity detail, reconciled per currency across accounts.",
    },
  },
  {
    number: "06",
    icon: Settings2,
    title: "Administration",
    body: "Users, entities, banks and role-based access, managed centrally.",
    flow: ["Users", "Entities", "Access"],
  },
];

const COUNT = MODULES.length;
const TRANSITION_MS = 520;

function ModuleFallback({
  number,
  title,
  body,
  flow,
}: {
  number: string;
  title: string;
  body: string;
  flow?: string[];
}) {
  return (
    <div className="flex size-full flex-col justify-between bg-[hsl(var(--background))] px-7 py-8 lg:px-10 lg:py-10">
      <div>
        <span className="immersive-label immersive-label-accent tabular-nums">
          {number}
        </span>
        <p className="font-heading mt-4 max-w-lg text-2xl font-medium leading-snug tracking-tight lg:text-[1.75rem]">
          {title}
        </p>
        <p className="mt-3 max-w-md text-sm leading-relaxed text-[hsl(var(--muted-foreground))]">
          {body}
        </p>
      </div>

      {flow?.length ? (
        <div className="mt-6 flex flex-wrap gap-2">
          {flow.map((step) => (
            <span
              key={step}
              className="immersive-label !text-[0.625rem] !tracking-[0.12em] rounded-full border border-[color:var(--hairline)] bg-white/[0.03] px-3 py-1.5"
            >
              {step}
            </span>
          ))}
        </div>
      ) : null}
    </div>
  );
}

/**
 * What the platform does, and what it is made of.
 *
 * Outcomes are live: they jump the explorer to the matching module.
 * Hover previews; click selects. The preview crossfades between module
 * screenshots without adding extra controls inside the frame.
 */
export default function Platform() {
  const [active, setActive] = useState(0);
  const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const explorerRef = useRef<HTMLDivElement>(null);
  const outcomesRef = useRef<HTMLOListElement>(null);
  const [hoveredOutcome, setHoveredOutcome] = useState<number | null>(null);
  const [hoverX, setHoverX] = useState<number | null>(null);
  const hoverRafRef = useRef<number | null>(null);
  const hoverPendingRef = useRef<{ idx: number; x: number } | null>(null);
  const module = MODULES[active];

  const pick = useCallback((index: number) => {
    setActive(index);
  }, []);

  const peek = useCallback((index: number) => {
    setActive(index);
  }, []);

  const jumpToModule = useCallback(
    (index: number) => {
      pick(index);
      explorerRef.current?.scrollIntoView({
        behavior: prefersReducedMotion() ? "auto" : "smooth",
        block: "center",
      });
    },
    [pick]
  );

  const clearOutcomeHover = useCallback(() => {
    hoverPendingRef.current = null;
    if (hoverRafRef.current != null) cancelAnimationFrame(hoverRafRef.current);
    hoverRafRef.current = null;
    setHoveredOutcome(null);
    setHoverX(null);
  }, []);

  const scheduleOutcomeHoverUpdate = useCallback(
    (idx: number, x: number) => {
      hoverPendingRef.current = { idx, x };
      if (hoverRafRef.current != null) return;
      hoverRafRef.current = window.requestAnimationFrame(() => {
        const pending = hoverPendingRef.current;
        if (pending) {
          setHoveredOutcome(pending.idx);
          setHoverX(pending.x);
          // Hovering the outcomes strip should preview the matching module.
          peek(OUTCOMES[pending.idx].module);
        }
        hoverRafRef.current = null;
      });
    },
    [peek]
  );

  const activeOutcomeIndex =
    hoveredOutcome ?? Math.max(0, OUTCOMES.findIndex((o) => o.module === active));
  const outcomesProgress =
    activeOutcomeIndex / Math.max(OUTCOMES.length - 1, 1);

  const onRailKey = useCallback(
    (e: React.KeyboardEvent, index: number) => {
      const last = COUNT - 1;
      let next: number | null = null;
      if (e.key === "ArrowDown" || e.key === "ArrowRight") next = index === last ? 0 : index + 1;
      else if (e.key === "ArrowUp" || e.key === "ArrowLeft") next = index === 0 ? last : index - 1;
      else if (e.key === "Home") next = 0;
      else if (e.key === "End") next = last;
      if (next === null) return;
      e.preventDefault();
      pick(next);
      tabRefs.current[next]?.focus();
    },
    [pick]
  );

  return (
    <section
      id="product"
      className="immersive-section scroll-mt-28 px-6 pb-20 pt-12 lg:px-12 lg:pb-28 lg:pt-16"
    >
      <div className="mx-auto w-full max-w-[88rem]">
        <div className="immersive-section-head">
          <span className="immersive-label">What we do</span>
          <span className="immersive-label">[ 02 ]</span>
        </div>

        <div className="grid gap-8 lg:grid-cols-12 lg:gap-16">
          <div className="lg:col-span-6">
            <RevealText as="h2" className="immersive-heading">
              Everything your firm runs on, in one platform.
            </RevealText>
          </div>
          <Reveal delay={0.1} className="lg:col-span-5 lg:col-start-8">
            <p className="text-base leading-relaxed text-[hsl(var(--muted-foreground))]">
              From trusted data to client-ready reporting — the operating layer behind
              every portfolio you manage.
            </p>
          </Reveal>
        </div>

        <Reveal delay={0.05} className="mt-12 lg:mt-14">
          <div className="relative">
            {/* Static “hairline strip” + hover/active fill. */}
            <span
              aria-hidden
              className="absolute left-0 top-1/2 hidden h-px w-full -translate-y-1/2 bg-[color:var(--hairline)] sm:block"
            />
            <span
              aria-hidden
              className="absolute left-0 top-1/2 hidden h-px w-full -translate-y-1/2 origin-left bg-[hsl(var(--primary))]/[0.35] sm:block"
              style={{ transform: `scaleX(${outcomesProgress})` }}
            />
            {hoverX != null && (
              <span
                aria-hidden
                className="pointer-events-none absolute top-1/2 z-20 hidden size-3 -translate-x-1/2 -translate-y-1/2 rounded-full bg-[hsl(var(--primary))] shadow-[0_0_0_6px_hsl(var(--primary)/0.12)] sm:block"
                style={{ left: hoverX }}
              />
            )}

            <ol
              ref={outcomesRef}
              onPointerMove={(e) => {
                const el = outcomesRef.current;
                if (!el) return;
                const rect = el.getBoundingClientRect();
                const rawX = e.clientX - rect.left;
                const clampedX = Math.min(Math.max(rawX, 0), rect.width);
                const t = clampedX / Math.max(rect.width, 1);
                const idx = Math.min(OUTCOMES.length - 1, Math.max(0, Math.floor(t * OUTCOMES.length)));
                scheduleOutcomeHoverUpdate(idx, clampedX);
              }}
              onPointerLeave={clearOutcomeHover}
              className="relative z-10 grid grid-cols-1 gap-px border-y border-[color:var(--hairline)] bg-[color:var(--hairline)] sm:grid-cols-2 lg:grid-cols-4"
            >
              {OUTCOMES.map((item, idx) => {
                const isHot = idx === activeOutcomeIndex;
                return (
                  <li key={item.number} className="bg-[hsl(var(--background))]">
                    <button
                      type="button"
                      onClick={() => jumpToModule(item.module)}
                      onPointerEnter={() => {
                        setHoveredOutcome(idx);
                        peek(item.module);
                      }}
                      className="group h-full w-full px-0 py-6 text-left transition-colors hover:bg-[hsl(var(--primary))]/[0.04] sm:px-6 lg:py-7"
                    >
                      <span
                        className={`immersive-label tabular-nums transition-colors ${
                          isHot ? "immersive-label-accent" : ""
                        }`}
                      >
                        {item.number}
                      </span>
                      <h3
                        className={`font-heading mt-3 text-[0.9375rem] font-medium leading-snug tracking-tight transition-colors ${
                          isHot
                            ? "text-[hsl(var(--primary))]"
                            : "text-[hsl(var(--foreground))] group-hover:text-[hsl(var(--primary))]"
                        }`}
                      >
                        {item.title}
                      </h3>
                      <p
                        className={`mt-1.5 text-[0.8125rem] leading-snug text-[hsl(var(--muted-foreground))] transition-opacity ${
                          isHot ? "opacity-100" : "opacity-75 group-hover:opacity-90"
                        }`}
                      >
                        {item.subtitle}
                      </p>
                    </button>
                  </li>
                );
              })}
            </ol>
          </div>
        </Reveal>

        <div ref={explorerRef} className="mt-20 lg:mt-24">
          <div className="mb-10 flex flex-col gap-4 border-b border-[color:var(--hairline)] pb-6 sm:flex-row sm:items-end sm:justify-between">
            <div>
              <span className="immersive-label immersive-label-accent">
                Platform modules
              </span>
              <h3 className="font-heading mt-3 text-2xl font-medium tracking-tight lg:text-[2rem]">
                Six modules, working as one.
              </h3>
            </div>
            <p className="max-w-sm text-sm leading-relaxed text-[hsl(var(--muted-foreground))]">
              Each one runs against the same validated book of record, so the
              numbers never diverge between them. Hover to preview; click to select.
            </p>
          </div>

          <Reveal delay={0.05}>
            <div
              className="grid gap-10 lg:grid-cols-12 lg:gap-14"
            >
              <div className="order-2 lg:order-1 lg:col-span-4">
                <div
                  role="tablist"
                  aria-orientation="vertical"
                  aria-label="Platform modules"
                  className="relative"
                >
                  <span
                    aria-hidden
                    className="absolute inset-y-0 left-0 w-px bg-[var(--hairline)]"
                  />
                  {MODULES.map((item, index) => {
                    const isActive = index === active;
                    const Icon = item.icon;
                    return (
                      <button
                        key={item.title}
                        ref={(node) => {
                          tabRefs.current[index] = node;
                        }}
                        type="button"
                        role="tab"
                        id={`platform-tab-${item.number}`}
                        aria-selected={isActive}
                        aria-controls="platform-module-panel"
                        tabIndex={isActive ? 0 : -1}
                        onClick={() => pick(index)}
                        onPointerEnter={() => peek(index)}
                        onKeyDown={(e) => onRailKey(e, index)}
                        className={`group relative block w-full rounded-lg py-3.5 pl-7 pr-3 text-left transition-colors first:mt-0 ${
                          isActive
                            ? "bg-[hsl(var(--primary))]/[0.07]"
                            : "hover:bg-white/[0.03]"
                        }`}
                      >
                        <span className="flex items-center gap-3">
                          <span
                            className={`flex size-8 shrink-0 items-center justify-center rounded-md transition-colors duration-300 ${
                              isActive
                                ? "bg-[hsl(var(--primary))]/15 text-[hsl(var(--primary))]"
                                : "bg-white/[0.04] text-[hsl(var(--muted-foreground))] group-hover:text-[hsl(var(--foreground))]"
                            }`}
                          >
                            <Icon className="size-4" aria-hidden />
                          </span>
                          <span className="min-w-0">
                            <span className="flex items-baseline gap-2.5">
                              <span
                                className={`immersive-label tabular-nums transition-colors duration-300 ${
                                  isActive ? "immersive-label-accent" : ""
                                }`}
                              >
                                {item.number}
                              </span>
                              <span
                                className={`font-heading text-[15px] font-medium tracking-tight transition-colors duration-300 lg:text-base ${
                                  isActive
                                    ? "text-[hsl(var(--foreground))]"
                                    : "text-[hsl(var(--foreground))]/55 group-hover:text-[hsl(var(--foreground))]/85"
                                }`}
                              >
                                {item.title}
                              </span>
                            </span>
                            <span
                              className={`grid transition-[grid-template-rows] ease-[cubic-bezier(0.22,1,0.36,1)] ${
                                isActive ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
                              }`}
                              style={{ transitionDuration: `${TRANSITION_MS}ms` }}
                            >
                              <span className="overflow-hidden">
                                <span className="block pt-1.5 text-[13px] leading-relaxed text-[hsl(var(--muted-foreground))]">
                                  {item.body}
                                </span>
                              </span>
                            </span>
                          </span>
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="order-1 min-w-0 lg:order-2 lg:col-span-8">
                <div
                  id="platform-module-panel"
                  role="tabpanel"
                  aria-labelledby={`platform-tab-${module.number}`}
                >
                  <figure
                    className="immersive-tour-frame relative overflow-hidden rounded-xl border border-white/10 bg-[hsl(var(--card))]"
                  >
                    <div className="flex items-center gap-4 border-b border-white/10 bg-white/[0.04] px-4 py-2.5">
                      <span className="flex shrink-0 gap-1.5" aria-hidden>
                        <span className="size-2 rounded-full bg-white/25" />
                        <span className="size-2 rounded-full bg-white/25" />
                        <span className="size-2 rounded-full bg-white/25" />
                      </span>
                      <span className="flex min-w-0 flex-1 items-center justify-center">
                        <span className="immersive-label immersive-tour-route truncate text-[0.6875rem]">
                          {module.shot?.route ?? "app.oxyfinz.com"}
                        </span>
                      </span>
                    </div>
                    <div className="relative aspect-[16/10] overflow-hidden bg-[hsl(var(--background))]">
                      {MODULES.map((item, index) => (
                        <div
                          key={item.number}
                          className="absolute inset-0 transition-opacity"
                          style={{
                            opacity: index === active ? 1 : 0,
                            transitionDuration: `${TRANSITION_MS}ms`,
                            pointerEvents: index === active ? "auto" : "none",
                          }}
                          aria-hidden={index !== active}
                        >
                          {item.shot ? (
                            <Image
                              src={item.shot.src}
                              alt={index === active ? item.shot.alt : ""}
                              width={item.shot.width}
                              height={item.shot.height}
                              sizes="(min-width: 1024px) 58vw, 100vw"
                              className="size-full object-cover object-top"
                            />
                          ) : (
                            <ModuleFallback
                              number={item.number}
                              title={item.title}
                              body={item.body}
                              flow={item.flow}
                            />
                          )}
                        </div>
                      ))}
                    </div>
                  </figure>
                  <div className="mt-5 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
                    <p
                      key={module.number}
                      className="max-w-lg text-sm leading-relaxed text-[hsl(var(--muted-foreground))] animate-fade-up"
                    >
                      {module.body}
                    </p>
                    <Link
                      href="#product-tour"
                      scroll={false}
                      onClick={(e) => {
                        if (scrollToImmersiveSection("product-tour")) e.preventDefault();
                      }}
                      className="group inline-flex shrink-0 items-center gap-2 text-sm font-semibold text-[hsl(var(--primary))]"
                    >
                      Open the product tour
                      <ArrowRight className="size-4 transition-transform group-hover:translate-x-0.5" />
                    </Link>
                  </div>
                </div>
              </div>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}
