'use client';

import React from 'react';
import { m, AnimatePresence } from 'framer-motion';
import { MapPin, CheckCircle2, ArrowUpRight } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { Location } from '@/lib/map-data';

const MinorNode = React.memo(({ loc, isActive, onEnter, onLeave }: { loc: Location, isActive: boolean, onEnter: (loc: Location) => void, onLeave: () => void }) => (
  <div
    className={`absolute group/minor cursor-pointer w-8 h-8 md:w-5 md:h-5 flex items-center justify-center ${isActive ? 'z-[60]' : 'z-10 hover:z-30'}`}
    style={{
      left: `${loc.x}%`,
      top: `${loc.y}%`,
      transform: 'translate(-50%, -50%)',
    }}
    onMouseEnter={() => onEnter(loc)}
    onMouseLeave={onLeave}
    onTouchStart={() => onEnter(loc)}
    onClick={() => onEnter(loc)}
  >
    <div className={`w-1.5 h-1.5 rounded-full transition-all duration-300 ${isActive ? 'bg-white scale-150 shadow-[0_0_10px_rgba(130,237,32,1)]' : 'bg-primary/80 group-hover/minor:bg-white group-hover/minor:scale-150'}`} />
    <div className="absolute inset-0 m-auto w-2 h-2 bg-primary rounded-full opacity-0 group-hover/minor:animate-ping" />
  </div>
));
MinorNode.displayName = 'MinorNode';

const MajorNode = React.memo(({ loc, isActive, idx, onEnter, onLeave }: { loc: Location, isActive: boolean, idx: number, onEnter: (loc: Location) => void, onLeave: () => void }) => {
  const isHQ = loc.type === 'hq';
  const isBranch = loc.type === 'branch';
  return (
    <div
      className={`absolute transform -translate-x-1/2 -translate-y-1/2 group/pin cursor-pointer w-16 h-16 flex items-center justify-center ${isActive ? 'z-[60]' : 'z-20 hover:z-40'}`}
      style={{ left: `${loc.x}%`, top: `${loc.y}%` }}
      onMouseEnter={() => onEnter(loc)}
      onMouseLeave={onLeave}
      onTouchStart={() => onEnter(loc)}
      onClick={() => onEnter(loc)}
    >
      {(isHQ || isBranch) && (
        <div className="absolute inset-0 m-auto w-6 h-6 rounded-full animate-ping bg-primary/50 scale-150" />
      )}
      <m.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.6)] transition-transform duration-300 ${
          isActive ? 'scale-125 z-30 ring-4 ring-primary/40' : 'scale-100 group-hover/pin:scale-110'
        } ${
          isHQ || isBranch
            ? 'w-7 h-7 bg-primary text-[#050B14]'
            : 'w-4 h-4 bg-white ring-[3px] ring-primary'
        }`}
      >
        {(isHQ || isBranch) && <MapPin className="w-4 h-4" />}
      </m.div>
    </div>
  );
});
MajorNode.displayName = 'MajorNode';

export default function InteractiveMapPins({
  locations,
  locale,
  t,
  activeLocation,
  handleMouseEnter,
  handleMouseLeave
}: {
  locations: Location[],
  locale: string,
  t: any,
  activeLocation: Location | null,
  handleMouseEnter: (loc: Location) => void,
  handleMouseLeave: () => void
}) {
  return (
    <>
      {locations.filter(l => l.type === 'minor_node').map((loc, idx) => (
        <MinorNode
          key={`minor-${loc.id || idx}`}
          loc={loc}
          isActive={activeLocation === loc}
          onEnter={handleMouseEnter}
          onLeave={handleMouseLeave}
        />
      ))}

      {locations.filter(l => l.type !== 'minor_node').map((loc, idx) => (
        <MajorNode
          key={loc.id}
          loc={loc}
          idx={idx}
          isActive={activeLocation?.id === loc.id}
          onEnter={handleMouseEnter}
          onLeave={handleMouseLeave}
        />
      ))}

      <AnimatePresence>
        {activeLocation && (
          <m.div
            key="tooltip"
            initial={{ opacity: 0, y: 10, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 10, scale: 0.95 }}
            transition={{ duration: 0.2 }}
            className="absolute z-[9999] pointer-events-auto bottom-[-60px] left-1/2 -translate-x-1/2 w-[calc(100vw_-_2rem)] max-w-[320px] md:w-max md:bottom-auto md:left-[var(--md-left)] md:top-[var(--md-top)] md:[transform:var(--md-transform)]"
            style={{
              '--md-left': `${activeLocation.x}%`,
              '--md-top': `${activeLocation.y}%`,
              '--md-transform': activeLocation.x < 50 ? 'translate(20px, -50%)' : 'translate(calc(-100% - 20px), -50%)',
            } as React.CSSProperties}
            onMouseEnter={() => handleMouseEnter(activeLocation)}
            onMouseLeave={handleMouseLeave}
          >
            <div className="bg-[#050B14]/95 backdrop-blur-xl border border-white/10 rounded-2xl shadow-2xl w-full text-white overflow-hidden">
              {activeLocation.featuredImage && (
                <div className="relative w-full h-32 bg-neutral-900">
                  <Image
                    src={activeLocation.featuredImage}
                    alt={activeLocation.name}
                    fill
                    className="object-cover"
                    sizes="(max-width: 768px) 100vw, 320px"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-[#050B14] to-transparent opacity-90" />
                </div>
              )}

              <div className="p-4">
                <div className="flex items-center gap-2 mb-1">
                  <MapPin className="w-3.5 h-3.5 text-primary" />
                  <span className="text-xs font-bold text-primary uppercase tracking-wider">
                    {t(`types.${activeLocation.type === 'minor_node' ? 'project' : activeLocation.type}`)}
                  </span>
                </div>
                <div className="font-heading font-bold text-lg leading-tight mb-2">
                  {activeLocation.name}
                </div>
                {activeLocation.type !== 'minor_node' ? (
                  <div className="text-white/60 text-sm line-clamp-3 mb-3">
                    {activeLocation.description}
                  </div>
                ) : (
                  <div className="text-white/60 text-xs mb-3">
                    {t(`descriptions.${['wind','pv','fiber','power','battery'].includes(activeLocation.description || '') ? activeLocation.description : 'default'}`)}
                  </div>
                )}
                
                {(activeLocation.details || activeLocation.type === 'minor_node') && (
                  <ul className="mb-3 space-y-1.5 border-t border-white/10 pt-3">
                    {activeLocation.type === 'minor_node' ? (
                      <>
                        <li className="text-[11px] text-white/80 flex items-start gap-2 font-medium">
                          <CheckCircle2 className="w-3 h-3 text-primary shrink-0 mt-0.5" />
                          <span>{t(`features.${['wind','pv','fiber','power','battery'].includes(activeLocation.description || '') ? activeLocation.description : 'default'}`)}</span>
                        </li>
                        <li className="text-[11px] text-white/80 flex items-start gap-2 font-medium">
                          <CheckCircle2 className="w-3 h-3 text-primary shrink-0 mt-0.5" />
                          <span>{t('features.method')}</span>
                        </li>
                      </>
                    ) : (
                      activeLocation.details?.map((detail, i) => (
                        <li key={i} className="text-[11px] text-white/80 flex items-start gap-2 font-medium">
                          <CheckCircle2 className="w-3 h-3 text-primary shrink-0 mt-0.5" />
                          <span>{detail}</span>
                        </li>
                      ))
                    )}
                  </ul>
                )}

                {activeLocation.href && (activeLocation.type === 'hq' || activeLocation.type === 'branch') && (
                  <Link 
                    href={activeLocation.href.startsWith('/') ? `/${locale}${activeLocation.href}` : activeLocation.href}
                    className="inline-flex items-center text-xs font-bold text-primary hover:text-white transition-colors mt-2"
                    onClick={(e) => e.stopPropagation()}
                  >
                    {t('learnMore')}
                    <ArrowUpRight className="w-3.5 h-3.5 ml-1" />
                  </Link>
                )}
              </div>
            </div>
          </m.div>
        )}
      </AnimatePresence>
    </>
  );
}
