'use client';

import Image from 'next/image';
import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { PremiumButton } from '@/components/ui/PremiumButton';
import { CursorSpotlight } from '@/components/ui/CursorSpotlight';
import { FEATURED_ROBOTS } from '@/data/robots';

const HERO_STATS = [
  { value: 'UAE', label: 'Access' },
  { value: 'Unitree + Pudu', label: 'Premier brands' },
  { value: 'Dubai', label: 'Showroom & Demo' },
];

type LabelPos = {
  text: string;
  delay: number;
  top?: string;
  bottom?: string;
  left?: string;
  right?: string;
};

/* Labels keyed to active robot brand/category for accuracy */
function getLabelsFor(brand: string, category: string): LabelPos[] {
  const brandLabel = brand === 'unitree' ? 'Unitree Robotics' : brand === 'agibot' ? 'AgiBot' : 'Pudu Robotics';
  const categoryLabel =
    category === 'humanoid'
      ? 'Humanoid Platform'
      : category === 'quadruped'
        ? 'Quadruped Patrol'
        : category === 'delivery'
          ? 'Delivery Automation'
          : category === 'service'
            ? 'Service Robotics'
            : category === 'cleaning'
              ? 'Cleaning Automation'
              : 'Advanced Robotics';
  return [
    { text: brandLabel, top: '11%', right: '4%', delay: 0.15 },
    { text: categoryLabel, bottom: '32%', left: '4%', delay: 0.4 },
    { text: 'Demo & Sales · Dubai', bottom: '11%', right: '6%', delay: 0.65 },
  ];
}

export function Hero3DRobotics() {
  const wrapRef = useRef<HTMLDivElement | null>(null);
  const [tilt, setTilt] = useState({ rx: 0, ry: 0 });
  const [activeIdx, setActiveIdx] = useState(0);

  useEffect(() => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) return;
    const el = wrapRef.current;
    if (!el) return;
    const onMove = (e: MouseEvent) => {
      const rect = el.getBoundingClientRect();
      const x = (e.clientX - rect.left) / rect.width - 0.5;
      const y = (e.clientY - rect.top) / rect.height - 0.5;
      setTilt({ rx: -y * 8, ry: x * 12 });
    };
    const onLeave = () => setTilt({ rx: 0, ry: 0 });
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    return () => {
      el.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
    };
  }, []);

  useEffect(() => {
    const t = setInterval(() => setActiveIdx((i) => (i + 1) % FEATURED_ROBOTS.length), 5600);
    return () => clearInterval(t);
  }, []);

  const robot = FEATURED_ROBOTS[activeIdx];
  const labels = getLabelsFor(robot.brand, robot.category);

  return (
    <section
      style={{
        position: 'relative',
        minHeight: 'min(960px, 100svh)',
        display: 'flex',
        alignItems: 'center',
        overflow: 'hidden',
        paddingTop: 'clamp(6rem, 12vw, 9rem)',
        paddingBottom: 'clamp(4rem, 8vw, 6rem)',
      }}
    >
      <div className="hero-gradient" />
      <div className="grid-overlay" />
      <div className="light-sweep" />
      <CursorSpotlight color="rgba(127, 127, 127, 0.28)" size={640} />

      {/* Royal-blue beams */}
      <div
        aria-hidden
        style={{
          position: 'absolute',
          inset: 0,
          background:
            'conic-gradient(from 220deg at 60% 50%, transparent 0deg, rgba(94, 94, 94, 0.10) 25deg, transparent 50deg, rgba(231, 231, 231, 0.06) 180deg, transparent 220deg, rgba(127, 127, 127, 0.10) 320deg, transparent 360deg)',
          mixBlendMode: 'screen',
          pointerEvents: 'none',
        }}
      />

      <div className="container-wide" style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1fr', gap: 'clamp(2rem, 5vw, 4rem)', alignItems: 'center', width: '100%' }}>
        <div className="hero-grid" style={{ display: 'grid', gap: 'clamp(2rem, 6vw, 4rem)', alignItems: 'center' }}>
          <div className="fade-in-up" style={{ display: 'flex', flexDirection: 'column', gap: '1.75rem' }}>
            <span
              className="eyebrow"
              style={{
                color: '#e7e7e7',
                border: '1px solid rgba(168, 168, 168, 0.45)',
                background: 'rgba(94, 94, 94, 0.10)',
                padding: '0.5rem 0.9rem',
                borderRadius: 999,
                alignSelf: 'flex-start',
                gap: '0.625rem',
              }}
            >
              <span aria-hidden style={{ width: 6, height: 6, borderRadius: 999, background: '#e7e7e7', boxShadow: '0 0 12px rgba(231, 231, 231, 0.9)' }} />
              UAE Access · Dubai
            </span>

            <h1
              style={{
                margin: 0,
                fontSize: 'clamp(2.6rem, 6.4vw, 4.6rem)',
                lineHeight: 1.02,
                letterSpacing: '-0.035em',
                fontWeight: 300,
              }}
            >
              <span style={{ display: 'block', color: '#fcfcfc', fontWeight: 200 }}>Advanced robotics.</span>
              <span
                style={{
                  display: 'block',
                  fontWeight: 600,
                  background:
                    'linear-gradient(110deg, #FFFFFF 0%, #e7e7e7 50%, #a8a8a8 100%)',
                  WebkitBackgroundClip: 'text',
                  backgroundClip: 'text',
                  WebkitTextFillColor: 'transparent',
                  color: 'transparent',
                  filter:
                    'drop-shadow(0 2px 12px rgba(231, 231, 231, 0.18)) drop-shadow(0 6px 28px rgba(127, 127, 127, 0.32))',
                }}
              >
                UAE access.
              </span>
            </h1>

            <p style={{ margin: 0, color: '#e7e7e7', fontSize: 'clamp(1rem, 2vw, 1.18rem)', lineHeight: 1.7, maxWidth: 600, fontWeight: 300 }}>
              YS Lootah Robotics is the UAE sales destination for selected Unitree and Pudu Robotics solutions helping businesses explore, configure, book demos, and deploy advanced robots across Dubai and the UAE.
            </p>
            <p style={{ margin: 0, color: '#e1e1e1', fontSize: '0.78rem', letterSpacing: '0.32em', textTransform: 'uppercase', fontWeight: 600 }}>
              In Tech We Innovate · In Trust We Lead
            </p>

            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.75rem', marginTop: '0.5rem' }}>
              <PremiumButton href="/robots/">Explore robots</PremiumButton>
              <PremiumButton href="/book-demo/" variant="ghost">Book a demo</PremiumButton>
              <PremiumButton href="/configure/" variant="outline">Configure your solution</PremiumButton>
            </div>

            <div
              style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
                gap: 'clamp(0.75rem, 2.4vw, 1.75rem)',
                paddingTop: '1.75rem',
                paddingBottom: '0.5rem',
                marginTop: '0.75rem',
                marginBottom: 'clamp(0.5rem, 2vw, 1.5rem)',
                borderTop: '1px solid rgba(168, 168, 168, 0.22)',
              }}
            >
              {HERO_STATS.map((s) => (
                <div key={s.label} style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem' }}>
                  <span
                    className="text-gradient-accent"
                    style={{
                      fontSize: 'clamp(1.1rem, 2.2vw, 1.5rem)',
                      fontWeight: 700,
                      letterSpacing: '-0.01em',
                      lineHeight: 1.1,
                    }}
                  >
                    {s.value}
                  </span>
                  <span style={{ fontSize: '0.66rem', color: '#a8a8a8', letterSpacing: '0.24em', textTransform: 'uppercase', fontWeight: 600 }}>
                    {s.label}
                  </span>
                </div>
              ))}
            </div>
          </div>

          <div
            ref={wrapRef}
            style={{
              position: 'relative',
              perspective: '1600px',
              minHeight: 'clamp(440px, 58vw, 660px)',
              width: '100%',
            }}
          >
            {/* Outer blue glow */}
            <div
              aria-hidden
              style={{
                position: 'absolute',
                inset: '-3rem',
                background:
                  `radial-gradient(ellipse 60% 50% at 50% 45%, ${robot.accent}55 0%, transparent 65%)`,
                filter: 'blur(34px)',
                pointerEvents: 'none',
              }}
            />

            {/* Floor halo */}
            <div
              aria-hidden
              style={{
                position: 'absolute',
                bottom: '-2rem',
                left: '8%',
                right: '8%',
                height: '8%',
                background:
                  'radial-gradient(ellipse 50% 100% at 50% 100%, rgba(127, 127, 127, 0.5), transparent 75%)',
                filter: 'blur(18px)',
                pointerEvents: 'none',
              }}
            />

            <div
              className="float-y"
              style={{
                position: 'relative',
                width: '100%',
                height: '100%',
                minHeight: 'clamp(440px, 58vw, 660px)',
                borderRadius: '1.75rem',
                background:
                  'linear-gradient(180deg, rgba(30, 30, 30, 0.78) 0%, rgba(11, 11, 11, 0.95) 100%)',
                border: '1px solid rgba(168, 168, 168, 0.32)',
                backdropFilter: 'blur(20px)',
                boxShadow:
                  '0 30px 100px rgba(0,0,0,0.8), inset 0 1px 0 rgba(231, 231, 231, 0.1), 0 0 70px rgba(94, 94, 94, 0.22)',
                transform: `rotateX(${tilt.rx}deg) rotateY(${tilt.ry}deg)`,
                transition: 'transform 0.3s cubic-bezier(0.16,1,0.3,1)',
                overflow: 'hidden',
                transformStyle: 'preserve-3d',
              }}
            >
              {/* Grid floor */}
              <div
                aria-hidden
                style={{
                  position: 'absolute',
                  inset: 0,
                  background:
                    'linear-gradient(rgba(168, 168, 168, 0.07) 1px, transparent 1px), linear-gradient(90deg, rgba(168, 168, 168, 0.07) 1px, transparent 1px)',
                  backgroundSize: '40px 40px',
                  maskImage: 'radial-gradient(ellipse 70% 70% at 50% 50%, #000 30%, transparent 80%)',
                  WebkitMaskImage: 'radial-gradient(ellipse 70% 70% at 50% 50%, #000 30%, transparent 80%)',
                  pointerEvents: 'none',
                }}
              />

              {/* Royal-blue stage spotlight behind robot */}
              <div
                aria-hidden
                style={{
                  position: 'absolute',
                  top: '12%',
                  left: '50%',
                  transform: 'translateX(-50%)',
                  width: '70%',
                  height: '70%',
                  background:
                    'radial-gradient(ellipse 60% 70% at 50% 35%, rgba(127, 127, 127, 0.45) 0%, rgba(94, 94, 94, 0.25) 35%, transparent 70%)',
                  filter: 'blur(14px)',
                  pointerEvents: 'none',
                }}
              />

              {/* Light beam from top */}
              <div
                aria-hidden
                style={{
                  position: 'absolute',
                  top: 0,
                  left: '50%',
                  transform: 'translateX(-50%)',
                  width: '60%',
                  height: '60%',
                  background:
                    'linear-gradient(180deg, rgba(231, 231, 231, 0.18) 0%, rgba(127, 127, 127, 0.12) 35%, transparent 75%)',
                  clipPath: 'polygon(35% 0, 65% 0, 90% 100%, 10% 100%)',
                  filter: 'blur(8px)',
                  mixBlendMode: 'screen',
                  pointerEvents: 'none',
                }}
              />

              {/* Robot image main */}
              {FEATURED_ROBOTS.map((r, idx) => (
                <div
                  key={r.id}
                  style={{
                    position: 'absolute',
                    inset: 0,
                    display: 'flex',
                    alignItems: 'flex-end',
                    justifyContent: 'center',
                    paddingTop: 'clamp(2rem, 5vw, 3rem)',
                    paddingBottom: '36%',
                    paddingLeft: 'clamp(1rem, 4vw, 2rem)',
                    paddingRight: 'clamp(1rem, 4vw, 2rem)',
                    opacity: idx === activeIdx ? 1 : 0,
                    transform:
                      idx === activeIdx
                        ? `translateY(0) translateX(${tilt.ry * 0.4}px) scale(1)`
                        : 'translateY(18px) scale(0.96)',
                    transformOrigin: 'center bottom',
                    transition: 'opacity 1s ease, transform 0.9s cubic-bezier(0.16,1,0.3,1)',
                    filter:
                      idx === activeIdx
                        ? 'drop-shadow(0 26px 42px rgba(0,0,0,0.78)) drop-shadow(0 14px 22px rgba(0,0,0,0.55)) drop-shadow(0 0 30px rgba(127, 127, 127, 0.45))'
                        : 'none',
                    willChange: 'transform',
                  }}
                  aria-hidden={idx !== activeIdx}
                >
                  <div style={{ position: 'relative', width: '100%', height: '100%' }}>
                    <Image
                      src={r.image}
                      alt={`${r.brandLabel} ${r.name}`}
                      fill
                      sizes="(max-width: 768px) 90vw, 620px"
                      style={{ objectFit: 'contain', objectPosition: 'center bottom' }}
                      priority={idx === 0}
                    />
                  </div>
                </div>
              ))}

              {/* Stronger drop-shadow ellipse under robot */}
              <div
                aria-hidden
                style={{
                  position: 'absolute',
                  left: '20%',
                  right: '20%',
                  bottom: '24%',
                  height: '5%',
                  background:
                    'radial-gradient(ellipse 60% 100% at 50% 100%, rgba(0,0,0,0.85), transparent 70%)',
                  filter: 'blur(10px)',
                  pointerEvents: 'none',
                }}
              />

              {/* Floor reflection (mirror image, faded) */}
              {FEATURED_ROBOTS.map((r, idx) => (
                <div
                  key={`reflect-${r.id}`}
                  aria-hidden
                  style={{
                    position: 'absolute',
                    left: 'clamp(1rem, 4vw, 2rem)',
                    right: 'clamp(1rem, 4vw, 2rem)',
                    bottom: '6%',
                    height: '22%',
                    opacity: idx === activeIdx ? 0.28 : 0,
                    transform: `scaleY(-1) translateX(${tilt.ry * 0.4}px)`,
                    transformOrigin: 'center top',
                    maskImage:
                      'linear-gradient(to bottom, rgba(0,0,0,0.8), transparent 78%)',
                    WebkitMaskImage:
                      'linear-gradient(to bottom, rgba(0,0,0,0.8), transparent 78%)',
                    transition: 'opacity 1s ease, transform 0.9s cubic-bezier(0.16,1,0.3,1)',
                    pointerEvents: 'none',
                    filter: 'blur(1.2px)',
                  }}
                >
                  <Image
                    src={r.image}
                    alt=""
                    fill
                    sizes="(max-width: 768px) 90vw, 620px"
                    style={{ objectFit: 'contain', objectPosition: 'center top' }}
                  />
                </div>
              ))}

              {/* Floor line */}
              <div
                aria-hidden
                style={{
                  position: 'absolute',
                  left: '5%',
                  right: '5%',
                  bottom: '28%',
                  height: 1,
                  background:
                    'linear-gradient(90deg, transparent, rgba(231, 231, 231, 0.6), transparent)',
                  pointerEvents: 'none',
                  filter: 'blur(0.3px)',
                }}
              />

              {/* Edge glass glare silver/blue rim light */}
              <div
                aria-hidden
                style={{
                  position: 'absolute',
                  inset: 0,
                  borderRadius: '1.75rem',
                  background:
                    'linear-gradient(135deg, rgba(231, 231, 231, 0.18) 0%, transparent 18%, transparent 80%, rgba(127, 127, 127, 0.22) 100%)',
                  mixBlendMode: 'screen',
                  pointerEvents: 'none',
                }}
              />
              <div
                aria-hidden
                style={{
                  position: 'absolute',
                  top: 0,
                  left: '10%',
                  right: '10%',
                  height: '2px',
                  background:
                    'linear-gradient(90deg, transparent, rgba(231, 231, 231, 0.5), transparent)',
                  pointerEvents: 'none',
                  filter: 'blur(0.4px)',
                }}
              />

              {/* Floating labels keyed to active robot + parallax */}
              <div className="hero-labels" aria-hidden>
                {labels.map((l, i) => {
                  /* labels drift opposite to tilt for parallax depth */
                  const depth = (i + 1) * 0.6;
                  const dx = tilt.ry * depth;
                  const dy = tilt.rx * depth;
                  return (
                    <span
                      key={`${activeIdx}-${l.text}`}
                      style={{
                        position: 'absolute',
                        top: l.top,
                        bottom: l.bottom,
                        left: l.left,
                        right: l.right,
                        padding: '0.45rem 0.8rem',
                        borderRadius: 999,
                        background: 'rgba(16, 16, 16, 0.78)',
                        border: '1px solid rgba(168, 168, 168, 0.45)',
                        color: '#e7e7e7',
                        fontSize: '0.66rem',
                        letterSpacing: '0.22em',
                        textTransform: 'uppercase',
                        fontWeight: 600,
                        backdropFilter: 'blur(10px)',
                        animation: `floatY 6s ease-in-out ${l.delay}s infinite, fadeInUp 0.9s cubic-bezier(0.16,1,0.3,1) ${l.delay}s both`,
                        whiteSpace: 'nowrap',
                        boxShadow:
                          '0 10px 28px rgba(0,0,0,0.55), 0 0 18px rgba(127, 127, 127, 0.18), inset 0 1px 0 rgba(231, 231, 231, 0.08)',
                        transform: `translate3d(${dx}px, ${dy}px, 0)`,
                        transition: 'transform 0.35s cubic-bezier(0.16,1,0.3,1)',
                        willChange: 'transform',
                      }}
                    >
                      {l.text}
                    </span>
                  );
                })}
              </div>

              {/* Featured card + dot nav */}
              <div
                style={{
                  position: 'absolute',
                  bottom: '1.25rem',
                  left: '1.25rem',
                  right: '1.25rem',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  gap: '1rem',
                  flexWrap: 'wrap',
                  zIndex: 5,
                }}
              >
                <Link
                  href={`/robots/${robot.slug}/`}
                  style={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: '0.75rem',
                    padding: '0.7rem 1.1rem',
                    borderRadius: 14,
                    background: 'rgba(16, 16, 16, 0.72)',
                    border: '1px solid rgba(168, 168, 168, 0.45)',
                    backdropFilter: 'blur(12px)',
                    color: '#fcfcfc',
                    textDecoration: 'none',
                    boxShadow: '0 10px 30px rgba(0,0,0,0.5)',
                  }}
                >
                  <span style={{ display: 'flex', flexDirection: 'column' }}>
                    <span style={{ fontSize: '0.62rem', color: '#a8a8a8', letterSpacing: '0.24em', textTransform: 'uppercase' }}>
                      Featured · {robot.brandLabel}
                    </span>
                    <span style={{ fontSize: '0.95rem', fontWeight: 600 }}>{robot.name}</span>
                  </span>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#e7e7e7" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <line x1="5" y1="12" x2="19" y2="12" />
                    <polyline points="12 5 19 12 12 19" />
                  </svg>
                </Link>
                <div style={{ display: 'flex', gap: '0.4rem' }}>
                  {FEATURED_ROBOTS.map((r, idx) => (
                    <button
                      key={r.id}
                      type="button"
                      onClick={() => setActiveIdx(idx)}
                      aria-label={`Show ${r.name}`}
                      style={{
                        width: idx === activeIdx ? 26 : 8,
                        height: 8,
                        borderRadius: 999,
                        border: 'none',
                        background: idx === activeIdx
                          ? 'linear-gradient(90deg, #e7e7e7, #7f7f7f)'
                          : 'rgba(168, 168, 168, 0.4)',
                        cursor: 'pointer',
                        transition: 'all 0.4s ease',
                      }}
                    />
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <style jsx>{`
        @media (min-width: 1024px) {
          .hero-grid {
            grid-template-columns: 1.05fr 1fr !important;
          }
        }
        .hero-labels { display: none; }
        @media (min-width: 768px) {
          .hero-labels { display: block; }
        }
      `}</style>
    </section>
  );
}
