"use client";

import { useEffect, useRef, useState } from "react";
import "./solutions-stack.css";

const solutions = [
  {
    title: "Present data you can trust",
    desc: "One reliable source for every decision.",
    icon: "overlap",
  },
  {
    title: "See the complete wealth picture",
    desc: "Every asset. Every portfolio. One view.",
    icon: "orb",
  },
  {
    title: "Run more, with less manual work",
    desc: "Give your team capacity to focus on clients.",
    icon: "rings",
  },
  {
    title: "Turn data into client-ready intelligence",
    desc: "From complex portfolios to clear conversations.",
    icon: "discs",
  },
] as const;

function SolutionIcon({
  icon,
  ghost,
}: {
  icon: (typeof solutions)[number]["icon"];
  ghost?: boolean;
}) {
  return (
    <div
      className={`sol-icon sol-icon--${icon}${ghost ? " sol-icon--ghost" : ""}`}
      aria-hidden
    >
      <span className="sol-icon-a" />
      <span className="sol-icon-b" />
    </div>
  );
}

function cardTransform(index: number, progress: number, count: number) {
  const p = progress * (count - 1);
  const d = p - index;
  // d < 0: the card has not arrived yet. Park it 140% down - far enough to sit
  // fully outside the clipped panel - and slide it up opaque, so it covers the
  // card below instead of cross-fading into a double-exposed title.
  const y = d < 0 ? Math.min(1, -d) * 140 : 0;
  const scale = 1 - Math.max(0, Math.min(d, count - 1)) * 0.06;
  return {
    transform: `translate3d(0, ${y}%, 0) scale(${scale})`,
    zIndex: index + 1,
  };
}

export function SolutionsStack() {
  const pinRef = useRef<HTMLDivElement>(null);
  const [progress, setProgress] = useState(0);
  const [pinned, setPinned] = useState(true);

  useEffect(() => {
    const media = window.matchMedia("(max-width: 992px)");
    const syncMode = () => setPinned(!media.matches);
    syncMode();
    media.addEventListener("change", syncMode);

    const update = () => {
      const pin = pinRef.current;
      if (!pin || media.matches) {
        setProgress(0);
        return;
      }
      const rect = pin.getBoundingClientRect();
      const total = pin.offsetHeight - window.innerHeight;
      if (total <= 0) {
        setProgress(0);
        return;
      }
      setProgress(Math.min(1, Math.max(0, -rect.top / total)));
    };

    update();
    window.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update);
    return () => {
      media.removeEventListener("change", syncMode);
      window.removeEventListener("scroll", update);
      window.removeEventListener("resize", update);
    };
  }, []);

  const step = Math.min(
    solutions.length - 1,
    Math.round(progress * (solutions.length - 1)),
  );

  return (
    <section className="sol-section" id="solutions-scroll">
      <div className="sol-pin" ref={pinRef}>
        <div className="sol-sticky">
          <div className="sol-panel">
            <div className="sol-left">
              <div className="sol-stack">
                {solutions.map((item, i) => (
                  <article
                    className="sol-card"
                    key={item.title}
                    style={pinned ? cardTransform(i, progress, solutions.length) : undefined}
                  >
                    <SolutionIcon icon={item.icon} ghost />
                    <SolutionIcon icon={item.icon} />
                    <h3 className="sol-card-title">{item.title}</h3>
                    <p className="sol-card-desc">{item.desc}</p>
                  </article>
                ))}
              </div>
            </div>

            <div className="sol-right">
              <div className="sol-progress" aria-hidden>
                <span className="sol-progress-count">
                  {String(step + 1).padStart(2, "0")}
                  <span> / {String(solutions.length).padStart(2, "0")}</span>
                </span>
                <span className="sol-progress-rail">
                  <span
                    className="sol-progress-fill"
                    style={{ transform: `scaleX(${(step + 1) / solutions.length})` }}
                  />
                </span>
              </div>

              {/* Cards are ordered back-to-front; they stack by DOM order. Each
                  step further back drifts left and rotates a little more as the
                  section scrolls, and the two deepest are smaller and hazier so
                  the fan reads as depth rather than as five equal rectangles. */}
              <div className="sol-glass" aria-hidden>
                <span className="sol-glow" />
                <div
                  className="sol-glass-card sol-glass-card--deepest"
                  style={{ transform: `translate3d(${progress * -58}px, ${progress * 18}px, 0) rotate(-37deg)` }}
                >
                <img src="/dash1.png" alt="" />
                </div>
                <div
                  className="sol-glass-card sol-glass-card--deep"
                  style={{ transform: `translate3d(${progress * -46}px, ${progress * 6}px, 0) rotate(-32deg)` }}
                >
                <img src="/dash2.png" alt="" />
                </div>
                <div
                  className="sol-glass-card sol-glass-card--rear"
                  style={{ transform: `translate3d(${progress * -34}px, ${progress * -12}px, 0) rotate(-27deg)` }}
                >
                <img src="/dash3.png" alt="" />
                </div>
                <div
                  className="sol-glass-card sol-glass-card--back"
                  style={{ transform: `translate3d(${progress * -18}px, ${progress * -24}px, 0) rotate(-18deg)` }}
                >
                <img src="/dash4.png" alt="" />
                </div>
                <div
                  className="sol-glass-card sol-glass-card--front"
                  style={{ transform: `translate3d(${progress * 10}px, ${progress * -36}px, 0) rotate(12deg)` }}
                >
                  <img src="/dash8.png" alt="" />
                </div>
              </div>

              <a className="sol-cta" href="mailto:hello@oxyfinz.com">
                Contact us
                <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden>
                  <path
                    d="M4 9h10M10 5l4 4-4 4"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="1.6"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
