'use client';

import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { MapPin, Factory, Zap, CheckCircle2, ArrowUpRight } from 'lucide-react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { AnimatedGlossyBorder } from '@/components/ui/AnimatedGlossyBorder';
import { Location, defaultLocations } from '@/lib/map-data';

interface Stat {
  value: string;
  suffix?: string;
  label: string;
}

interface InteractiveGermanyMapProps {
  badge?: string;
  title?: React.ReactNode;
  description?: string;
  stats?: Stat[];
  locations?: Location[];
  isHero?: boolean;
}

export function InteractiveGermanyMap({
  badge = 'Einsatzgebiete',
  title = <>Deutschlandweit<br/>für Sie im Einsatz.</>,
  description = 'Von unseren strategischen Standorten in Guben und Bülstedt steuern und realisieren wir komplexe Infrastrukturprojekte im gesamten Bundesgebiet.',
  stats = [
    { value: '100', suffix: '%', label: 'Überregionale Reichweite' },
    { value: '2', suffix: '+', label: 'Operative Standorte' },
  ],
  locations = defaultLocations,
  isHero = false
}: InteractiveGermanyMapProps) {
  const [activeLocation, setActiveLocation] = useState<Location | null>(null);
  const router = useRouter();

  const hq = locations.find((l) => l.type === 'hq');
  const branch = locations.find((l) => l.type === 'branch');
  const projects = locations.filter((l) => l.type === 'project');

  return (
    <div className={isHero ? "relative w-full" : "relative w-full max-w-7xl mx-auto py-16 md:py-24 px-4 sm:px-6 mt-16 md:mt-20"}>
      <div className={`bg-[#050B14] ${isHero ? 'pt-32 pb-16 md:pt-40 md:pb-24' : 'rounded-[2.5rem] md:rounded-[3.5rem] shadow-2xl border border-white/5'} overflow-visible relative group/map`}>
        {/* Animated Border Glow */}
        {!isHero && <AnimatedGlossyBorder opacity={0.7} className="z-30" />}
        
        {/* Background Effects */}
        <div className={`absolute inset-0 bg-gradient-to-br from-[#050B14] via-[#0A1322] to-[#050B14] ${!isHero && 'rounded-[2.5rem] md:rounded-[3.5rem]'} overflow-hidden`} />
        <div className="absolute top-0 right-0 w-[800px] h-[800px] bg-primary/5 rounded-full blur-[120px] pointer-events-none translate-x-1/3 -translate-y-1/3 overflow-hidden" />
        
        <div className={`relative z-10 grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-12 gap-12 items-center min-h-[600px] ${isHero ? 'max-w-7xl mx-auto px-4 sm:px-6' : 'p-8 md:p-12 lg:p-16'}`}>
          
          {/* Content Left */}
          <div className="xl:col-span-5 text-white z-20">
            <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-primary/10 border border-primary/20 text-primary text-xs font-bold uppercase tracking-wider mb-8">
              <MapPin className="w-4 h-4" />
              <span>{badge}</span>
            </div>
            
            {isHero ? (
              <h1 className="font-heading text-4xl lg:text-5xl xl:text-6xl font-extrabold mb-6 leading-[1.1] text-transparent bg-clip-text bg-gradient-to-r from-white to-white/70 break-words [hyphens:auto]">
                {title}
              </h1>
            ) : (
              <h3 className="font-heading text-4xl lg:text-5xl xl:text-6xl font-extrabold mb-6 leading-[1.1] text-transparent bg-clip-text bg-gradient-to-r from-white to-white/70 break-words [hyphens:auto]">
                {title}
              </h3>
            )}
            
            <p className="text-white/60 text-lg mb-12 leading-relaxed">
              {description}
            </p>

            {/* Industrial Stats Grid */}
            <div className="grid grid-cols-2 gap-4">
              {stats.map((stat, i) => (
                <div key={i} className="bg-white/5 border border-white/10 rounded-2xl p-6 backdrop-blur-md relative overflow-hidden group">
                  <div className="absolute inset-0 bg-gradient-to-br from-primary/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
                  <div className="relative z-10">
                    <div className="text-4xl font-extrabold text-white mb-1 flex items-baseline gap-1">
                      {stat.value}<span className="text-xl text-primary">{stat.suffix}</span>
                    </div>
                    <div className="text-sm text-white/50 font-medium">{stat.label}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Map Right */}
          <div className="xl:col-span-7 relative flex items-center justify-center lg:justify-end mt-8 lg:mt-0 z-10">
            {/* Map Container - Enforce strict aspect ratio matching the SVG (1024x1024) */}
            <div className="relative w-full max-w-[600px] aspect-square z-10">
              {/* Map SVG */}
              <div className="absolute inset-0 opacity-[0.25] mix-blend-screen drop-shadow-2xl brightness-200">
                <Image
                  src="/germany-map.svg"
                  alt="Deutschlandkarte"
                  fill
                  className="object-cover"
                  priority
                />
              </div>

              {/* Connections (Lines) */}
              <svg className="absolute inset-0 w-full h-full pointer-events-none z-10">
                {hq && branch && (
                  <motion.line
                    x1={`${hq.x}%`}
                    y1={`${hq.y}%`}
                    x2={`${branch.x}%`}
                    y2={`${branch.y}%`}
                    stroke="rgba(130,237,32,0.6)"
                    strokeWidth="2"
                    strokeDasharray="6 6"
                    initial={{ pathLength: 0, opacity: 0 }}
                    animate={{ pathLength: 1, opacity: 1 }}
                    transition={{ duration: 2, ease: "easeOut" }}
                  />
                )}
                {hq && projects.map((proj, idx) => (
                  <motion.line
                    key={proj.id}
                    x1={`${hq.x}%`}
                    y1={`${hq.y}%`}
                    x2={`${proj.x}%`}
                    y2={`${proj.y}%`}
                    stroke="rgba(130,237,32,0.3)"
                    strokeWidth="1.5"
                    initial={{ pathLength: 0, opacity: 0 }}
                    animate={{ pathLength: 1, opacity: 1 }}
                    transition={{ duration: 1.5, delay: 0.5 + idx * 0.2 }}
                  />
                ))}
              </svg>

              {/* Location Pins */}
              {locations.map((loc, idx) => {
                const isHQ = loc.type === 'hq';
                const isBranch = loc.type === 'branch';
                const isActive = activeLocation?.id === loc.id;

                const isNearLeft = loc.x < 50;
                const isNearRight = loc.x >= 50;
                const isNearTop = loc.y < 55; // 55% threshold to strongly avoid the top header

                const tooltipClasses = [
                  'absolute w-[280px] sm:w-64 bg-white text-neutral-dark p-5 rounded-2xl shadow-2xl z-[9999] border border-neutral-100',
                  isNearLeft ? 'left-1/2 sm:left-0 -translate-x-1/2 sm:translate-x-0' : 'left-1/2 sm:left-auto sm:right-0 -translate-x-1/2 sm:translate-x-0',
                  isNearTop 
                    ? 'top-full mt-4 before:absolute before:-top-6 before:left-0 before:w-full before:h-6' 
                    : 'bottom-full mb-4 before:absolute before:-bottom-6 before:left-0 before:w-full before:h-6'
                ].join(' ');

                const arrowClasses = [
                  'absolute border-8 border-transparent drop-shadow-sm hidden sm:block',
                  isNearLeft ? 'left-6' : 'right-6',
                  isNearTop ? '-top-4 border-b-white border-t-0' : '-bottom-4 border-t-white border-b-0'
                ].join(' ');

                return (
                  <div
                    key={loc.id}
                    className={`absolute transform -translate-x-1/2 -translate-y-1/2 group cursor-pointer w-16 h-16 flex items-center justify-center ${isActive ? 'z-[60]' : 'z-20'}`}
                    style={{ left: `${loc.x}%`, top: `${loc.y}%` }}
                    onMouseEnter={() => setActiveLocation(loc)}
                    onMouseLeave={() => setActiveLocation(null)}
                    onClick={() => {
                      if (loc.href) router.push(loc.href);
                    }}
                  >
                    {/* Ping Animation for HQ / Branch */}
                    {(isHQ || isBranch) && (
                      <div className="absolute inset-0 m-auto w-6 h-6 rounded-full animate-ping bg-primary/50 scale-150" />
                    )}

                    {/* Marker Dot */}
                    <motion.div
                      initial={{ scale: 0 }}
                      animate={{ scale: 1 }}
                      transition={{ type: 'spring', delay: idx * 0.1 }}
                      className={`relative flex items-center justify-center rounded-full shadow-[0_0_20px_rgba(130,237,32,0.4)] transition-transform duration-300 ${
                        isActive ? 'scale-125 z-30 ring-4 ring-primary/30' : 'scale-100'
                      } ${
                        isHQ || isBranch
                          ? 'w-6 h-6 bg-primary text-[#050B14]'
                          : 'w-4 h-4 bg-white ring-[3px] ring-primary'
                      }`}
                    >
                      {(isHQ || isBranch) && <MapPin className="w-3.5 h-3.5" />}
                    </motion.div>

                    {/* Tooltip */}
                    <AnimatePresence>
                      {isActive && (
                        <motion.div
                          variants={{
                            hidden: { opacity: 0, y: isNearTop ? -15 : 15, scale: 0.9 },
                            visible: { 
                              opacity: 1, y: 0, scale: 1,
                              transition: { 
                                type: "spring", stiffness: 350, damping: 25,
                                staggerChildren: 0.05, delayChildren: 0.05
                              }
                            },
                            exit: { 
                              opacity: 0, y: isNearTop ? -10 : 10, scale: 0.95, 
                              transition: { duration: 0.15, ease: "easeIn" } 
                            }
                          }}
                          initial="hidden"
                          animate="visible"
                          exit="exit"
                          className={`${tooltipClasses} overflow-hidden p-0`}
                        >
                          {loc.featuredImage && (
                            <motion.div 
                              variants={{ hidden: { opacity: 0 }, visible: { opacity: 1 } }}
                              className="relative w-full h-32 bg-neutral-100 overflow-hidden"
                            >
                              <Image
                                src={loc.featuredImage}
                                alt={loc.name}
                                fill
                                className="object-cover transform transition-transform duration-1000 ease-[cubic-bezier(0.16,1,0.3,1)] group-hover:scale-110"
                              />
                              <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-80" />
                              <div className="absolute bottom-3 left-4 flex items-center gap-2">
                                {isHQ ? <Factory className="w-4 h-4 text-primary drop-shadow" /> : <Zap className="w-4 h-4 text-primary drop-shadow" />}
                                <span className="font-extrabold text-sm leading-tight text-white drop-shadow-md">{loc.name}</span>
                              </div>
                            </motion.div>
                          )}
                          
                          <div className={loc.featuredImage ? "p-5 pt-4" : "p-5"}>
                            {!loc.featuredImage && (
                              <motion.div 
                                variants={{ hidden: { opacity: 0, x: -5 }, visible: { opacity: 1, x: 0 } }}
                                className="flex items-center gap-2 mb-2"
                              >
                                {isHQ ? <Factory className="w-4 h-4 text-primary" /> : <Zap className="w-4 h-4 text-primary" />}
                                <span className="font-extrabold text-sm leading-tight text-neutral-dark">{loc.name}</span>
                              </motion.div>
                            )}
                            
                            <motion.p 
                              variants={{ hidden: { opacity: 0, y: 5 }, visible: { opacity: 1, y: 0 } }}
                              className="text-xs text-neutral-500 font-medium"
                            >
                              {loc.description}
                            </motion.p>
                          
                          {loc.details && (
                            <ul className="mt-4 space-y-2">
                              {loc.details.map((detail, i) => (
                                <motion.li 
                                  key={i} 
                                  variants={{ hidden: { opacity: 0, x: -5 }, visible: { opacity: 1, x: 0 } }}
                                  className="text-[11px] text-neutral-dark flex items-center gap-2 font-semibold"
                                >
                                  <div className="w-4 h-4 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
                                    <CheckCircle2 className="w-3 h-3 text-primary" />
                                  </div>
                                  {detail}
                                </motion.li>
                              ))}
                            </ul>
                          )}
                          
                          {loc.href && (
                            <motion.div 
                              variants={{ hidden: { opacity: 0, y: 5 }, visible: { opacity: 1, y: 0 } }}
                              className="mt-4 pt-3 border-t border-neutral-100 text-xs font-bold text-primary flex items-center gap-1 group/link"
                            >
                              Zum Projekt 
                              <span className="text-base leading-none translate-y-[1px] transform transition-transform duration-300 group-hover:translate-x-1.5">&rarr;</span>
                            </motion.div>
                          )}
                          </div>
                          
                          {/* Arrow Down/Up */}
                          <div className={arrowClasses} />
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>
                );
              })}
            </div>
          </div>
          
        </div>
      </div>
    </div>
  );
}
