"use client";

import Image from "next/image";
import Link from "next/link";
import { useCallback, useEffect, useRef, useState } from "react";
import { ArrowRight, ChevronLeft, ChevronRight, Maximize2 } from "lucide-react";
import Reveal from "@/components/immersive/Reveal";
import RevealText from "@/components/immersive/RevealText";
import Lightbox, { type Shot } from "@/components/immersive/Lightbox";
import { ScrollTrigger, prefersReducedMotion } from "@/components/immersive/gsap-setup";

/**
 * The screens, in the order a prospect would meet them: the consolidated
 * position first, then the analysis behind it, then the cash detail underneath.
 * `width`/`height` are the files' true pixel sizes — Next needs them to reserve
 * the box, the frame uses them to take each screen's shape, and the viewer uses
 * them to size the full-resolution render.
 */
const SHOTS: Shot[] = [
  {
    id: "dashboard",
    number: "01",
    label: "Consolidated dashboard",
    blurb:
      "Every asset class totalled the moment you land — equity, fixed income, commodities, cash and alternatives against one valuation.",
    route: "app.oxyfinz.com/dashboard",
    src: "/feature-1.png",
    width: 1727,
    height: 949,
  },
  {
    id: "analytics",
    number: "02",
    label: "Portfolio analytics",
    blurb:
      "Asset values over time, filtered by instrument type, with return analysis, holdings, liquidity, cash flows and fees a tab away.",
    route: "app.oxyfinz.com/reports/portfolio-analytics",
    src: "/feature-2.png",
    width: 1631,
    height: 865,
  },
  {
    id: "cash",
    number: "03",
    label: "Cash & liquidity detail",
    blurb:
      "Balances held per currency across every account, reconciled to the custodian and refreshed on demand.",
    route: "app.oxyfinz.com/reports/liquidity/cash-details",
    src: "/feature-3.png",
    width: 1673,
    height: 506,
  },
];

/** How long each screen holds before the tour advances itself. */
const ADVANCE_MS = 7000;
/** Frame resize + cross-fade. Kept in one place so they stay in step. */
const TRANSITION_MS = 620;

const COUNT = SHOTS.length;
const TOTAL = String(COUNT).padStart(2, "0");

/**
 * Product tour — the screens themselves.
 *
 * Everything above this section describes the platform; this is the first place
 * a visitor sees it. The window frame takes the shape of whichever screen is on
 * it, an indexed rail drives the sequence, and the tour advances on its own
 * until the visitor touches it — pointer, focus, the transport controls or the
 * viewer all stop it, and it never starts for a reduced-motion visitor.
 *
 * Screenshots are small on a phone by nature, so every route into the viewer is
 * kept open: the stage itself, and the expand control in the window chrome.
 */
export default function Showcase() {
  const [active, setActive] = useState(0);
  const [playing, setPlaying] = useState(true);
  const [held, setHeld] = useState(false);
  const [zoomed, setZoomed] = useState(false);
  const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);

  const shot = SHOTS[active];
  // The tour only runs while it is unattended: no pointer on it, no focus in
  // it, no viewer open over it, and never against an explicit motion opt-out.
  const running = playing && !held && !zoomed;

  useEffect(() => {
    if (prefersReducedMotion()) setPlaying(false);
  }, []);

  useEffect(() => {
    if (!running) return;
    const id = window.setTimeout(() => setActive((i) => (i + 1) % COUNT), ADVANCE_MS);
    return () => window.clearTimeout(id);
  }, [running, active]);

  // The frame takes each screen's own proportions, so the section's height
  // changes as the tour advances. ScrollSmoother caches the content height and
  // ScrollTrigger caches every start/end against it, so both have to be told
  // once the resize has settled — otherwise the triggers below this section
  // fire against stale positions and the page's own scroll limit is wrong.
  useEffect(() => {
    const id = window.setTimeout(() => ScrollTrigger.refresh(), TRANSITION_MS + 40);
    return () => window.clearTimeout(id);
  }, [active]);

  const pick = useCallback((index: number) => {
    setActive(index);
    // A deliberate choice ends the auto-advance for good; moving the stage on a
    // few seconds after someone picked a screen is the opposite of help.
    setPlaying(false);
  }, []);

  const step = useCallback(
    (delta: number) => pick((active + delta + COUNT) % COUNT),
    [active, pick]
  );

  /** Arrow / Home / End across the rail, per the tablist keyboard pattern. */
  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-tour"
      className="immersive-section scroll-mt-28 px-6 py-20 lg:px-12 lg:py-28"
    >
      <div className="mx-auto w-full max-w-[88rem]">
        <div className="immersive-section-head">
          <span className="immersive-label">Product tour</span>
          <span className="immersive-label">[ 03 ]</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">
              This is what your desk looks like on Oxyfinz.
            </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))]">
              Real screens from the platform — not mockups. Step through them here, or
              open any one full size.
            </p>
          </Reveal>
        </div>

        <Reveal delay={0.05} className="mt-14 lg:mt-20">
          <div
            className="grid gap-10 lg:grid-cols-12 lg:gap-14"
            onPointerEnter={() => setHeld(true)}
            onPointerLeave={() => setHeld(false)}
            onFocusCapture={() => setHeld(true)}
            onBlurCapture={() => setHeld(false)}
          >
            {/* Stage. First on a phone, where it is the thing worth seeing.
                min-w-0: the route in the chrome is `truncate`, so its min-content
                is the whole un-wrapped string. Without this the single-column
                mobile grid sizes its track to that string and the stage overflows
                the page instead of the route ellipsing. The lg:grid-cols-12
                tracks are already minmax(0,1fr). */}
            <div className="order-1 min-w-0 lg:order-2 lg:col-span-8">
              <div className="relative">
                {/* Ambient light behind the frame. Wide, weak and low — it lifts
                    the frame off the page ground without reading as a glow. */}
                <div
                  aria-hidden
                  className="pointer-events-none absolute -inset-x-10 -bottom-8 -top-6 -z-10 blur-3xl"
                  style={{
                    background:
                      "radial-gradient(58% 50% at 50% 42%, hsl(var(--primary) / 0.14), transparent 70%)",
                  }}
                />

                <figure className="immersive-tour-frame overflow-hidden rounded-xl border border-white/10 bg-[hsl(var(--card))]">
                  {/* Window chrome. Dots, route, expand — the three things a real
                      window has, at the weight of trim rather than decoration. */}
                  <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]">
                        {shot.route}
                      </span>
                    </span>
                    <button
                      type="button"
                      onClick={() => setZoomed(true)}
                      aria-label={`Open ${shot.label} full size`}
                      className="inline-flex size-7 shrink-0 items-center justify-center rounded-md text-[hsl(var(--muted-foreground))] transition-colors hover:bg-white/[0.06] hover:text-[hsl(var(--foreground))]"
                    >
                      <Maximize2 className="size-3.5" aria-hidden />
                    </button>
                  </div>

                  {/* The frame takes the active screen's proportions instead of
                      one fixed ratio, so a short report is shown as a short
                      window rather than stranded in a band of empty white. The
                      padding-top ratio box is used over `aspect-ratio` because
                      percentage padding transitions everywhere, which is what
                      makes the resize read as the window settling. */}
                  <div
                    id="product-tour-panel"
                    role="tabpanel"
                    aria-labelledby={`product-tour-tab-${shot.id}`}
                    className="immersive-tour-stage relative h-0 overflow-hidden bg-white"
                    style={{
                      paddingTop: `${(shot.height / shot.width) * 100}%`,
                      transitionDuration: `${TRANSITION_MS}ms`,
                    }}
                  >
                    {SHOTS.map((item, index) => (
                      <Image
                        key={item.id}
                        src={item.src}
                        alt={index === active ? `${item.label} — ${item.blurb}` : ""}
                        // Decorative while off-stage: three alt texts read out in
                        // a row would describe screens nobody can see.
                        aria-hidden={index !== active}
                        width={item.width}
                        height={item.height}
                        sizes="(min-width: 1024px) 62vw, 100vw"
                        style={{ transitionDuration: `${TRANSITION_MS}ms` }}
                        className={`absolute inset-0 size-full object-contain object-top transition-opacity ${
                          index === active ? "opacity-100" : "opacity-0"
                        }`}
                      />
                    ))}

                    {/* A single bright hairline along the top edge — the one
                        highlight that makes a flat screenshot read as glass. */}
                    <span
                      aria-hidden
                      className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-white/50 to-transparent"
                    />

                    {/* Sits over the stage rather than wrapping it: a <button>
                        carrying role="tabpanel" would have lost its button
                        semantics to the override. */}
                    <button
                      type="button"
                      onClick={() => setZoomed(true)}
                      aria-label={`Open ${shot.label} full size`}
                      className="absolute inset-0 cursor-zoom-in"
                    />
                  </div>
                </figure>

                {/* Transport row: what is on the stage, and the controls for it. */}
                <figcaption className="mt-5 flex items-center justify-between gap-4">
                  <div className="flex min-w-0 items-baseline gap-3">
                    <span className="immersive-label immersive-label-accent tabular-nums">
                      {shot.number} / {TOTAL}
                    </span>
                    <span className="truncate text-sm text-[hsl(var(--foreground))]">
                      {shot.label}
                    </span>
                  </div>

                  <div className="flex shrink-0 items-stretch overflow-hidden rounded-lg border border-white/10">
                    <button
                      type="button"
                      onClick={() => step(-1)}
                      aria-label="Previous screen"
                      className="inline-flex size-9 items-center justify-center text-[hsl(var(--muted-foreground))] transition-colors hover:bg-white/[0.06] hover:text-[hsl(var(--foreground))]"
                    >
                      <ChevronLeft className="size-4" aria-hidden />
                    </button>
                    <button
                      type="button"
                      onClick={() => step(1)}
                      aria-label="Next screen"
                      className="inline-flex size-9 items-center justify-center border-l border-white/10 text-[hsl(var(--muted-foreground))] transition-colors hover:bg-white/[0.06] hover:text-[hsl(var(--foreground))]"
                    >
                      <ChevronRight className="size-4" aria-hidden />
                    </button>
                  </div>
                </figcaption>
              </div>
            </div>

            {/* Rail: an index down a spine rather than a stack of cards. The
                spine segment beside the active step doubles as the countdown to
                the next one, so the progress lives in the structure instead of
                needing a bar of its own. */}
            {/* Full height + justify-between anchors the closing note to the
                foot of the frame beside it, instead of leaving the column
                trailing off into empty space halfway down the stage. */}
            <div className="order-2 flex min-w-0 flex-col justify-between lg:order-1 lg:col-span-4 lg:h-full">
              <div className="relative">
                <span
                  aria-hidden
                  className="absolute inset-y-0 left-0 w-px bg-[var(--hairline)]"
                />

                <div role="tablist" aria-orientation="vertical" aria-label="Product tour screens">
                  {SHOTS.map((item, index) => {
                    const isActive = index === active;
                    return (
                      <button
                        key={item.id}
                        ref={(node) => {
                          tabRefs.current[index] = node;
                        }}
                        type="button"
                        role="tab"
                        id={`product-tour-tab-${item.id}`}
                        aria-selected={isActive}
                        aria-controls="product-tour-panel"
                        tabIndex={isActive ? 0 : -1}
                        onClick={() => pick(index)}
                        onKeyDown={(e) => onRailKey(e, index)}
                        className="group relative block w-full py-5 pl-7 pr-1 text-left first:pt-0"
                      >
                        {/* Active segment. It fills top-down over the hold when
                            the tour is running, and simply stands lit when it is
                            paused — so the spine is a truthful read of whether
                            the stage is about to move. */}
                        <span
                          key={`${item.id}-${running ? "run" : "hold"}`}
                          aria-hidden
                          style={running ? { animationDuration: `${ADVANCE_MS}ms` } : undefined}
                          className={`absolute inset-y-0 left-0 w-px origin-top bg-[hsl(var(--primary))] transition-opacity duration-300 ${
                            isActive ? "opacity-100" : "opacity-0"
                          } ${isActive && running ? "immersive-tour-spine" : ""}`}
                        />

                        <span className="flex items-baseline gap-3">
                          <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.label}
                          </span>
                        </span>

                        {/* Only the active step carries its description. Three at
                            once is a wall of text next to the thing the section
                            is actually about. */}
                        <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 pl-9 pt-2.5 text-sm leading-relaxed text-[hsl(var(--muted-foreground))]">
                              {item.blurb}
                            </span>
                          </span>
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="mt-9 border-t border-white/10 pt-6 lg:mt-12">
                <p className="text-sm leading-relaxed text-[hsl(var(--muted-foreground))]">
                  These are demo portfolios. The walkthrough runs against yours.
                </p>
                <Link
                  href="/contact"
                  className="group mt-3 inline-flex items-center gap-2 text-sm font-semibold text-[hsl(var(--primary))]"
                >
                  Book a live walkthrough
                  <ArrowRight className="size-4 transition-transform group-hover:translate-x-0.5" />
                </Link>
              </div>
            </div>
          </div>
        </Reveal>
      </div>

      {zoomed && (
        <Lightbox
          shots={SHOTS}
          index={active}
          onIndex={setActive}
          onClose={() => setZoomed(false)}
        />
      )}
    </section>
  );
}
