'use client'

import { motion, AnimatePresence } from 'framer-motion'

type IsoNode = {
  id: string
  label: string
  emoji: string
  kind: 'shop' | 'home' | 'restaurant' | 'hub'
  x: number // X coordinate as percentage (0-100)
  y: number // Y coordinate as percentage (0-100)
}

const NODES: IsoNode[] = [
  { id: 'food-essentials', label: 'Food Essentials Store', emoji: '🛒', kind: 'shop', x: 80, y: 22 },
  { id: 'shoppers', label: 'Local Shoppers', emoji: '🛍️', kind: 'home', x: 84, y: 54 },
  { id: 'hot-food', label: 'Hot Food Partner', emoji: '🍔', kind: 'restaurant', x: 74, y: 80 },
  { id: 'community', label: 'Community Homes', emoji: '🏠', kind: 'home', x: 28, y: 78 },
  { id: 'nearle-hood', label: 'Nearle Neighbourhood', emoji: '🏘️', kind: 'hub', x: 50, y: 50 },
]

function getCurvePath(id: string): string {
  switch (id) {
    case 'food-essentials':
      return 'M 50 50 C 60 40, 70 30, 80 22'
    case 'shoppers':
      return 'M 50 50 C 62 50, 72 52, 84 54'
    case 'hot-food':
      return 'M 50 50 C 58 62, 66 70, 74 80'
    case 'community':
      return 'M 50 50 C 42 62, 36 70, 28 78'
    default:
      return ''
  }
}

export default function IsoMap3D({
  onSelect,
  selectedId,
}: {
  onSelect: (id: string, label: string) => void
  selectedId: string
}) {
  const scooterTarget = NODES.find((n) => n.id === selectedId)

  return (
    <div className="relative w-full h-full bg-[#FAF9FC] overflow-hidden select-none select-none">
      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes flow {
          to {
            stroke-dashoffset: -16;
          }
        }
      `}} />

      {/* Mesh dot pattern background */}
      <div className="absolute inset-0 bg-[radial-gradient(#E8E5EE_1.5px,transparent_1.5px)] [background-size:24px_24px] opacity-75 pointer-events-none" />

      {/* Connection street layer */}
      <div className="absolute inset-0 pointer-events-none z-0">
        <svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="none" className="overflow-visible">
          <defs>
            <linearGradient id="map-progress-grad" x1="0%" y1="0%" x2="100%" y2="0%">
              <stop offset="0%" stopColor="#683285" />
              <stop offset="100%" stopColor="#A467B7" />
            </linearGradient>
          </defs>

          {/* Background ground road tracks — always visible for ALL nodes */}
          {NODES.filter((n) => n.id !== 'nearle-hood').map((node) => {
            const path = getCurvePath(node.id)
            return (
              <g key={`road-${node.id}`}>
                {/* Thick soft background road */}
                <path
                  d={path}
                  fill="none"
                  stroke="#EDE5F2"
                  strokeWidth="2.0"
                  strokeLinecap="round"
                />
                {/* Dashed lane marker */}
                <path
                  d={path}
                  fill="none"
                  stroke="#D9CCE3"
                  strokeWidth="0.6"
                  strokeLinecap="round"
                  strokeDasharray="2 2.5"
                />
              </g>
            )
          })}

          {/* Glowing active order flow tracks */}
          {NODES.filter((n) => n.id !== 'nearle-hood').map((node) => {
            const isActive = selectedId === node.id
            const path = getCurvePath(node.id)
            if (!isActive) return null
            return (
              <g key={`active-road-${node.id}`}>
                {/* Glow back-halo */}
                <path
                  d={path}
                  fill="none"
                  stroke="#E7D3EF"
                  strokeWidth="2.4"
                  strokeLinecap="round"
                  className="opacity-45"
                />
                {/* Animated dash line */}
                <motion.path
                  d={path}
                  fill="none"
                  stroke="url(#map-progress-grad)"
                  strokeWidth="1.2"
                  strokeLinecap="round"
                  strokeDasharray="1.5 1.5"
                  className="animate-[flow_1.8s_linear_infinite]"
                />
              </g>
            )
          })}
        </svg>
      </div>

      {/* Gliding Dispatch Scooter — slowly travels FROM store TO hub, repeating */}
      {scooterTarget && selectedId !== 'nearle-hood' && (
        <motion.div
          key={selectedId}
          className="absolute w-9 h-9 rounded-full bg-white border-2 border-purple-primary shadow-[0_4px_16px_rgba(104,50,133,0.25)] flex items-center justify-center text-lg z-30 pointer-events-none"
          style={{
            x: '-50%',
            y: '-50%',
          }}
          animate={{
            left: [`${scooterTarget.x}%`, '50%'],
            top: [`${scooterTarget.y}%`, '50%'],
          }}
          transition={{
            duration: 6,
            ease: 'linear',
            repeat: Infinity,
            repeatDelay: 0.8,
          }}
        >
          🛵
        </motion.div>
      )}

      {/* Node Cards Layer */}
      <div className="absolute inset-0 z-10">
        {NODES.map((node) => {
          const isActive = selectedId === node.id
          return (
            <div
              key={node.id}
              className="absolute"
              style={{
                left: `${node.x}%`,
                top: `${node.y}%`,
                transform: 'translate(-50%, -50%)',
                zIndex: isActive ? 40 : 20,
              }}
            >
              {/* Floating Interactive Node Bubble/Card */}
              <motion.div
                onClick={() => onSelect(node.id, node.label)}
                whileHover={{ scale: 1.04 }}
                className="relative cursor-pointer flex flex-col items-center group"
              >
                {/* Icon container — relative wrapper for centering effects */}
                <div className="relative flex items-center justify-center">
                  {/* Smooth sonar ripple rings on active — no heartbeat jerk */}
                  {isActive && (
                    <>
                      <style dangerouslySetInnerHTML={{ __html: `
                        @keyframes sonar-ripple {
                          0% {
                            transform: scale(0.85);
                            opacity: 0.5;
                          }
                          100% {
                            transform: scale(1.8);
                            opacity: 0;
                          }
                        }
                      `}} />
                      <span
                        className="absolute w-12 h-12 rounded-full border border-purple-primary/60 pointer-events-none"
                        style={{ animation: 'sonar-ripple 3s ease-out infinite' }}
                      />
                      <span
                        className="absolute w-12 h-12 rounded-full border border-purple-primary/40 pointer-events-none"
                        style={{ animation: 'sonar-ripple 3s ease-out 1s infinite' }}
                      />
                      <span
                        className="absolute w-12 h-12 rounded-full border border-purple-primary/25 pointer-events-none"
                        style={{ animation: 'sonar-ripple 3s ease-out 2s infinite' }}
                      />
                    </>
                  )}

                  {/* Steady centered glow behind active icon */}
                  {isActive && (
                    <div className="absolute w-16 h-16 rounded-full bg-[#E7D3EF]/35 blur-[10px] pointer-events-none" />
                  )}

                  {/* Central Icon Circle */}
                  <div
                    className={`relative w-12 h-12 rounded-2xl flex items-center justify-center text-2xl border transition-all duration-300 ${
                      isActive
                        ? 'bg-purple-deep border-purple-deep text-white shadow-[0_6px_20px_rgba(104,50,133,0.25)]'
                        : 'bg-white border-[#E7D3EF]/85 text-nearle-dark group-hover:border-purple-primary/60 group-hover:shadow-nearle-sm'
                    }`}
                  >
                    {node.emoji}
                  </div>
                </div>

                {/* Label Badge underneath node */}
                <div
                  className={`mt-2.5 whitespace-nowrap border rounded-full px-3 py-1 font-body text-[10px] font-extrabold shadow-nearle-xs transition-all duration-300 ${
                    isActive
                      ? 'bg-purple-deep border-purple-deep text-white shadow-[0_4px_12px_rgba(104,50,133,0.18)]'
                      : 'bg-white border-[#E7D3EF] text-nearle-dark group-hover:border-purple-primary group-hover:text-purple-primary font-bold'
                  }`}
                >
                  {node.label}
                </div>
              </motion.div>
            </div>
          )
        })}
      </div>

      {/* Helper hint badge */}
      <div className="absolute bottom-4 right-4 flex items-center gap-2 bg-white border border-[#E7D3EF] rounded-full px-3.5 py-1.5 shadow-[0_4px_16px_rgba(164,103,183,0.08)] select-none z-30">
        <span className="text-[12px] animate-bounce">📍</span>
        <span className="font-body text-[11px] font-bold text-nearle-dark tracking-wide uppercase">
          Neighbourhood Plan
        </span>
      </div>
    </div>
  )
}
