'use client';

import { useEffect, useRef, useState } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { ArrowRight } from 'lucide-react';
import ASCIIBackground from '../components/ASCIIBackground';
import { PRIMARY_COLOR, PRIMARY_COLOR_HOVER, LANDING_BTN_PRIMARY_PILL } from './landing-constants';

gsap.registerPlugin(ScrollTrigger);

const phrases = [
  { first: 'Complexity', second: 'Clarity' },
  { first: 'Clarity', second: 'Insights' },
  { first: 'Insights', second: 'Decisions' },
];

export default function Hero() {
  const sectionRef = useRef<HTMLElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);
  const ctaRef = useRef<HTMLAnchorElement>(null);
  const blobRef = useRef<HTMLDivElement>(null);
  const [currentPhraseIndex, setCurrentPhraseIndex] = useState(0);
  const [mousePos, setMousePos] = useState<{ x: number; y: number } | null>(null);
  const firstWordRef = useRef<HTMLSpanElement>(null);
  const secondWordRef = useRef<HTMLSpanElement>(null);
  const isFirstRenderRef = useRef(true);

  const handleMouseMove = (e: React.MouseEvent<HTMLElement>) => {
    if (!sectionRef.current) return;
    const rect = sectionRef.current.getBoundingClientRect();
    const x = (e.clientX - rect.left) / rect.width;
    const y = (e.clientY - rect.top) / rect.height;
    setMousePos({ x, y });
  };

  const handleMouseLeave = () => {
    setMousePos(null);
  };

  useEffect(() => {
    const ctx = gsap.context(() => {
      gsap.fromTo(
        contentRef.current,
        { y: 24, opacity: 0 },
        { y: 0, opacity: 1, duration: 0.95, ease: 'power3.out' }
      );
      if (blobRef.current) {
        gsap.fromTo(blobRef.current, { scale: 0.85, opacity: 0 }, { scale: 1, opacity: 1, duration: 1.1, ease: 'power2.out', delay: 0.08 });
      }
      if (ctaRef.current) {
        const btn = ctaRef.current;
        btn.addEventListener('mouseenter', () => gsap.to(btn, { scale: 1.02, x: 3, duration: 0.2, ease: 'power2.out' }));
        btn.addEventListener('mouseleave', () => gsap.to(btn, { scale: 1, x: 0, duration: 0.2, ease: 'power2.out' }));
      }
    }, sectionRef);
    return () => ctx.revert();
  }, []);

  useEffect(() => {
    if (!firstWordRef.current || !secondWordRef.current) return;
    const first = firstWordRef.current;
    const second = secondWordRef.current;

    if (isFirstRenderRef.current) {
      isFirstRenderRef.current = false;
      gsap.set([first, second], { opacity: 1 });
      return;
    }

    gsap.to([first, second], {
      opacity: 1,
      duration: 0.4,
      ease: 'power2.out',
      stagger: 0.06,
    });
  }, [currentPhraseIndex]);

  useEffect(() => {
    const interval = setInterval(() => {
      if (!firstWordRef.current || !secondWordRef.current) return;
      const first = firstWordRef.current;
      const second = secondWordRef.current;

      gsap.to([first, second], {
        opacity: 0,
        duration: 0.3,
        ease: 'power2.in',
        onComplete: () => {
          setCurrentPhraseIndex((prev) => (prev + 1) % phrases.length);
        },
      });
    }, 3200);
    return () => clearInterval(interval);
  }, []);

  return (
    <section
      ref={sectionRef}
      className="relative h-[100vh] min-h-[360px] sm:min-h-[400px] md:min-h-[420px] bg-[#f8faf9] overflow-hidden flex flex-col pt-16 sm:pt-20 border-b border-slate-200/60"
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
    >
      <ASCIIBackground mouseX={mousePos?.x} mouseY={mousePos?.y} />

      {/* Softer overlays so background stays visible */}
      <div
        className="absolute inset-0 pointer-events-none"
        style={{
          background: `
            radial-gradient(ellipse 120% 80% at 50% -5%, rgba(66, 139, 77, 0.06) 0%, transparent 50%),
            radial-gradient(ellipse 80% 60% at 90% 50%, rgba(66, 139, 77, 0.04) 0%, transparent 55%),
            radial-gradient(ellipse 60% 50% at 10% 60%, rgba(66, 139, 77, 0.03) 0%, transparent 50%),
            linear-gradient(180deg, transparent 0%, rgba(248, 250, 249, 0.6) 100%)
          `,
        }}
      />
      <div
        ref={blobRef}
        className="absolute top-1/3 -right-[12%] w-[50%] max-w-[580px] aspect-square rounded-full pointer-events-none"
        style={{
          background: 'radial-gradient(circle, rgba(66, 139, 77, 0.12) 0%, rgba(66, 139, 77, 0.03) 50%, transparent 70%)',
          filter: 'blur(56px)',
        }}
      />
      <div
        className="absolute bottom-1/4 -left-[8%] w-[40%] max-w-[400px] aspect-square rounded-full pointer-events-none"
        style={{
          background: 'radial-gradient(circle, rgba(66, 139, 77, 0.06) 0%, transparent 60%)',
          filter: 'blur(40px)',
        }}
      />

      {/* Lighter dot grid so ASCII background reads better */}
      <div
        className="absolute inset-0 pointer-events-none opacity-[0.35]"
        style={{
          backgroundImage: 'radial-gradient(circle at 1px 1px, rgba(66, 139, 77, 0.08) 1px, transparent 0)',
          backgroundSize: '24px 24px',
        }}
      />

      {/* Content: centered in viewport, responsive padding and spacing */}
      <div className="relative z-10 flex-1 flex flex-col items-center justify-center w-full px-6 py-10 sm:py-14 lg:py-16">
        <div
          ref={contentRef}
          className="mx-auto w-full max-w-4xl text-center flex flex-col items-center"
        >
          {/* Eyebrow */}
          <div className="flex items-center justify-center gap-2 sm:gap-3 mb-4 sm:mb-6 flex-wrap">
            <span className="h-px w-6 sm:w-8 bg-[#428B4D]/4 rounded-full shrink-0" aria-hidden="true" />
            <p className="font-mono text-[10px] sm:text-xs tracking-[0.2em] sm:tracking-[0.28em] text-[#428B4D]/90 font-medium uppercase text-center">
              Oxygen Financial Intelligence Systems
            </p>
            <span className="h-px w-6 sm:w-8 bg-[#428B4D]/4 rounded-full shrink-0" aria-hidden="true" />
          </div>

          {/* Headline — "Turn" / "into" fixed column, each line block so no overlap */}
          <div className="space-y-3 sm:space-y-4 mb-6 sm:mb-0 text-left w-max max-w-full mx-auto px-0.5">
            <h1 className="font-heading text-3xl sm:text-4xl md:text-5xl lg:text-6xl xl:text-7xl 2xl:text-[4rem] font-extrabold leading-[1.15] sm:leading-[1.12] tracking-[-0.03em] text-[#0c0c0c]">
              <span className="flex items-baseline gap-2 sm:gap-3 flex-nowrap block">
                <span className="w-[4rem] sm:w-[4rem] md:w-[9rem] shrink-0 text-[#0c0c0c]" aria-hidden="true">Turn</span>
                <span
                  ref={firstWordRef}
                  className="inline-block w-[120px] sm:w-[180px] md:w-[220px] lg:w-[240px] xl:w-[260px] font-extrabold min-w-0"
                  style={{ color: PRIMARY_COLOR }}
                >
                  {phrases[currentPhraseIndex].first}
                </span>
              </span>
              <span className="flex items-baseline gap-2 sm:gap-3 flex-nowrap block">
                <span className="w-[4rem] sm:w-[4rem] md:w-[9rem] shrink-0 text-[#0c0c0c] p-2" aria-hidden="true">Into</span>
                <span
                  ref={secondWordRef}
                  className="inline-block w-[120px] sm:w-[180px] md:w-[220px] lg:w-[240px] xl:w-[260px] font-extrabold min-w-0"
                  style={{ color: PRIMARY_COLOR }}
                >
                  {phrases[currentPhraseIndex].second}
                </span>
              </span>
            </h1>
            <div className="mt-6 sm:mt-8 h-0.5 w-14 sm:w-16 md:w-20 rounded-full bg-gradient-to-r from-transparent via-[#428B4D]/5 to-transparent mx-auto" aria-hidden="true" />
          </div>

          {/* Taglines */}
          <div className="space-y-1.5 sm:space-y-2 max-w-xl mb-6 sm:mb-8 lg:mb-10 px-1">
            <p className="text-sm sm:text-base md:text-lg text-slate-600 leading-relaxed font-medium">
              One dashboard for infinite portfolio intelligence.
            </p>
            <p className="text-xs sm:text-sm md:text-base text-slate-500 leading-relaxed">
              Consolidate, visualise and track assets in one place.
            </p>
          </div>

          {/* CTA */}
          <div>
            <a
              ref={ctaRef}
              href="/contact"
              className={`group ${LANDING_BTN_PRIMARY_PILL} px-5 py-3 sm:px-7 sm:py-3.5 text-xs sm:text-sm cursor-pointer`}
            >
              Talk to sales
              <ArrowRight className="h-3.5 w-3.5 sm:h-4 sm:w-4 transition-transform duration-200 group-hover:translate-x-0.5 shrink-0" aria-hidden />
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}
