'use client';

import { useEffect, useRef } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import {
  BarChart3,
  Settings,
  Globe,
  ArrowRight,
  FileBarChart,
  Sparkles,
} from 'lucide-react';
import { LANDING_BTN_PRIMARY_PILL, LANDING_ICON_WRAPPER, LANDING_ICON_PRIMARY } from './landing-constants';

gsap.registerPlugin(ScrollTrigger);

const SLOT_MIN_HEIGHT = '80vh';
const SECTION_TOP_MARGIN = 'min(10vh, 100px)';

const features = [
  {
    number: '01',
    title: 'Manage your investment with ease',
    description:
      'Oxyfinz supports 17 different transactions and automatically calculates fund performance metrics, within one fund or across different funds.',
    subDescription:
      'Oxyfinz dashboards are constantly updated and provide you with a comprehensive snapshot of your fund investments in real-time.',
    subTitle: 'See how Oxyfinz assists you in measuring fund performance',
    image: '/feature-1.png',
    icon: BarChart3,
  },
  {
    number: '02',
    title: 'Customize Metrics and KPIs template for each Portfolio Company',
    description:
      'Choose from the extensive list of metrics or create your own! Be it financials, balance sheet items, marketing metrics or ESG metrics, Oxyfinz has you covered.',
    subDescription:
      "Plus, you're able to predict growth patterns of your portfolio companies with the forecasted and actual value of any KPIs that matter to you.",
    subTitle: 'Explore our features',
    image: '/feature-2.png',
    icon: Settings,
  },
  {
    number: '03',
    title: 'Evaluate your investment in multiple currencies',
    description:
      'See how much your investments are affected by FX fluctuations with just a few clicks.',
    subDescription: '',
    subTitle: 'See how Multi-currency Investment works',
    image: '/feature-3.png',
    icon: Globe,
  },
  {
    number: '04',
    title: 'Reporting and analytics tailored to you',
    description:
      'Generate polished reports and dashboards for clients and stakeholders. Track performance, allocation, and risk with metrics that matter to your business.',
    subDescription:
      'Customize layouts and delivery so every report is clear, relevant, and ready to share.',
    subTitle: 'Discover reporting capabilities',
    image: '/feature-1.png',
    icon: FileBarChart,
  },
];

const zIndexClasses = ['z-0', 'z-10', 'z-20', 'z-30'];

export default function Product() {
  const sectionRef = useRef<HTMLElement>(null);
  const leftRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const ctx = gsap.context(() => {
      if (leftRef.current && sectionRef.current) {
        gsap.fromTo(
          leftRef.current,
          { x: -16, opacity: 0 },
          {
            x: 0,
            opacity: 1,
            duration: 1,
            ease: 'power2.out',
            overwrite: 'auto',
            scrollTrigger: {
              trigger: sectionRef.current,
              start: 'top 85%',
            },
          }
        );

        ScrollTrigger.create({
          trigger: sectionRef.current,
          start: 'top 6rem',
          end: 'bottom top',
          pin: leftRef.current,
          pinSpacing: true,
          invalidateOnRefresh: true,
        });
      }

      gsap.utils.toArray('.feature-item').forEach((el: unknown, i: number) => {
        const item = el as HTMLElement;
        gsap.fromTo(
          item,
          { y: 40, opacity: 0 },
          {
            y: 0,
            opacity: 1,
            duration: 0.9,
            ease: 'power2.out',
            overwrite: 'auto',
            scrollTrigger: {
              trigger: item,
              start: 'top 88%',
              end: 'top 50%',
              toggleActions: 'play none none reverse',
            },
            delay: i * 0.06,
          }
        );
      });
    }, sectionRef);

    return () => ctx.revert();
  }, []);

  return (
    <section
      id="product"
      ref={sectionRef}
      className="relative py-14 lg:py-20 overflow-visible scroll-smooth border-t border-slate-200/60"
      style={{
        background: 'linear-gradient(180deg, #fefefe 0%, #fafbf9 45%, #f8faf8 100%)',
      }}
    >
      {/* Soft grid — gentle, paper-like */}
      <div
        className="absolute inset-0 pointer-events-none opacity-50"
        style={{
          backgroundImage: `
            linear-gradient(rgba(66,139,77,0.025) 1px, transparent 1px),
            linear-gradient(90deg, rgba(66,139,77,0.025) 1px, transparent 1px)
          `,
          backgroundSize: '40px 40px',
        }}
        aria-hidden
      />
      <div
        className="absolute top-0 left-0 right-0 h-1/2 pointer-events-none"
        style={{
          background: 'radial-gradient(ellipse 80% 50% at 50% -10%, rgba(66,139,77,0.06), transparent 55%)',
        }}
        aria-hidden
      />

      <div className="landing-container relative z-10 overflow-visible">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-10 lg:gap-14 xl:gap-16">
          {/* Left: pinned panel — warm, inviting */}
          <div className="lg:col-span-4 lg:self-start order-1 overflow-visible">
            <div
              ref={leftRef}
              className="text-center lg:text-left lg:pr-8 lg:z-20"
            >
              <div className="flex items-center justify-center lg:justify-start gap-2 mb-5">
                <Sparkles size={18} className={LANDING_ICON_PRIMARY} aria-hidden />
                <p className="landing-section-eyebrow">[ Features ]</p>
              </div>
              <h2 className="landing-section-title mb-4 max-w-md lg:max-w-none mx-auto lg:mx-0">
                Your Source For Portfolio Analysis, Reporting And Data
              </h2>
              <p className="text-slate-600 text-base lg:text-lg leading-relaxed max-w-sm mx-auto lg:mx-0 mb-8">
                Everything you need to understand, present, and grow your portfolio—in one place.
              </p>
              <a
                href="#contact"
                className={`group ${LANDING_BTN_PRIMARY_PILL} inline-flex justify-center lg:justify-start gap-2.5 px-7 py-3.5 text-sm hover:-translate-y-0.5 active:translate-y-0 transition-all duration-300 ease-out`}
              >
                <span>See it in action</span>
                <ArrowRight size={18} className="transition-transform duration-300 ease-out group-hover:translate-x-0.5" aria-hidden />
              </a>
            </div>
          </div>

          {/* Right: stacked feature cards — soft, tactile */}
          <div className="lg:col-span-8 order-2 overflow-visible">
            <div className="flex flex-col">
              {features.map((feature, index) => {
                const Icon = feature.icon;
                const zClass = zIndexClasses[index] ?? 'z-0';
                const isLast = index === features.length - 1;
                return (
                  <div
                    key={index}
                    className="mb-8 sm:mb-12 lg:mb-0"
                    style={{ marginTop: index === 0 ? 0 : SECTION_TOP_MARGIN }}
                  >
                    <article
                      id={`feature-${index}`}
                      className={`feature-item group relative rounded-2xl overflow-hidden bg-white/95 backdrop-blur-sm scroll-mt-24 sm:scroll-mt-28 lg:sticky lg:top-24 border border-slate-200/70 shadow-[0_1px_3px_rgba(0,0,0,0.04)] hover:shadow-[0_24px_48px_-12px_rgba(0,0,0,0.08),0_0_0_1px_rgba(66,139,77,0.08)] hover:border-[#428B4D]/25 hover:-translate-y-1 transition-all duration-400 ease-out ${zClass}`}
                    >
                      <div className="grid grid-cols-1 md:grid-cols-5 gap-0 min-h-0">
                        {/* Content */}
                        <div className="md:col-span-2 flex flex-col justify-center py-7 px-6 sm:py-8 sm:px-7 lg:py-9 lg:px-8 order-2 md:order-1 relative pl-7 md:pl-9">
                          <div className="absolute left-0 top-10 bottom-10 w-0.5 rounded-full bg-gradient-to-b from-[#428b4d]/20 via-[#428b4d]/10 to-[#428b4d]/5 hidden md:block" aria-hidden />
                          <div className="flex items-center gap-3 mb-5">
                            <span
                              className={`flex items-center justify-center w-11 h-11 rounded-2xl font-heading font-bold text-sm tabular-nums border border-[#428B4D]/12 bg-[#428B4D]/5 ${LANDING_ICON_PRIMARY}`}
                              aria-hidden
                            >
                              {feature.number}
                            </span>
                            <div className={`w-11 h-11 rounded-2xl ${LANDING_ICON_WRAPPER} shrink-0 transition-colors duration-300 group-hover:bg-[#428B4D]/15`}>
                              <Icon size={22} className={LANDING_ICON_PRIMARY} aria-hidden />
                            </div>
                          </div>
                          <h3 className="font-heading font-bold text-lg sm:text-xl text-[#0a0a0a] mb-3 leading-snug">
                            <a
                              href="#contact"
                              className="hover:text-[#428B4D] transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-[#428B4D]/30 focus-visible:ring-offset-2 rounded"
                            >
                              {feature.title}
                            </a>
                          </h3>
                          <p className="text-slate-600/95 text-[15px] sm:text-base leading-relaxed line-clamp-3 mb-5">
                            {feature.description}
                          </p>
                          {feature.subTitle && (
                            <p className="text-slate-500 text-sm font-medium mb-6">
                              {feature.subTitle}
                            </p>
                          )}
                          <a
                            href="#contact"
                            className="inline-flex items-center justify-center w-11 h-11 rounded-full border border-slate-200/90 bg-slate-50/80 text-slate-500 hover:border-[#428B4D] hover:text-[#428B4D] hover:bg-[#428B4D]/10 transition-all duration-300 ease-out focus:outline-none focus-visible:ring-2 focus-visible:ring-[#428B4D]/30 focus-visible:ring-offset-2"
                            aria-label={`Learn more: ${feature.title}`}
                          >
                            <ArrowRight size={18} aria-hidden />
                          </a>
                        </div>

                        {/* Image */}
                        <div className="md:col-span-3 order-1 md:order-2 relative overflow-hidden md:rounded-r-2xl">
                          <div className="relative aspect-[4/3] md:aspect-auto md:min-h-[220px] lg:min-h-[240px]">
                            <img
                              src={feature.image}
                              alt={feature.title}
                              className="absolute inset-0 w-full h-full object-cover transition-transform duration-600 ease-out group-hover:scale-[1.04]"
                            />
                            <div
                              className="absolute inset-0 bg-gradient-to-r from-white/90 via-white/25 to-transparent md:from-white/75 md:via-white/10 md:to-transparent pointer-events-none"
                              aria-hidden
                            />
                          </div>
                        </div>
                      </div>
                    </article>
                    <div
                      className="hidden lg:block flex-shrink-0"
                      style={{
                        minHeight: isLast ? '32vh' : SLOT_MIN_HEIGHT,
                      }}
                      aria-hidden
                    />
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
