'use client'

import { useState } from 'react'
import dynamic from 'next/dynamic'
import { AnimatePresence, motion } from 'framer-motion'
import { SectionHeader } from '@/components/ui/SectionHeader'
import { GlassCard } from '@/components/ui/GlassCard'

const IsoMap3D = dynamic(() => import('@/components/three/IsoMap3D'), {
  ssr: false,
  loading: () => (
    <div className="w-full h-full flex items-center justify-center bg-purple-soft/40 rounded-3xl">
      <span className="font-mono text-xs text-purple-deep tracking-widest uppercase">
        Loading 3D map…
      </span>
    </div>
  ),
})

type DetailNode = {
  id: string
  label: string
  emoji: string
  category: 'Registered Business' | 'Active Restaurant' | 'Community Home' | 'Network Hub'
  desc: string
  metric: string
  bullets: { icon: string; tone: string; text: string }[]
}

const DETAIL_BY_ID: Record<string, DetailNode> = {
  'food-essentials': {
    id: 'food-essentials',
    label: 'Food Essentials Store',
    emoji: '🛒',
    category: 'Registered Business',
    desc: 'Daily essentials, fruits, vegetables, and friendly service from local business.',
    metric: 'Neighbourhood offers · Local assurance',
    bullets: [
      { icon: '🛡️', tone: 'bg-[#ECFDF5] text-[#10B981]', text: 'Hyper-local catalog, updated by every shop daily' },
      { icon: '⚡', tone: 'bg-[#FFF7ED] text-[#F97316]', text: 'Live inventory from shops within walking distance' },
    ],
  },
  'shoppers': {
    id: 'shoppers',
    label: 'Local Shoppers',
    emoji: '🛍️',
    category: 'Community Home',
    desc: 'Households nearby who order daily essentials and discover neighbourhood deals.',
    metric: 'Active residents · Loyal community',
    bullets: [
      { icon: '🛡️', tone: 'bg-[#ECFDF5] text-[#10B981]', text: 'Trusted shopper accounts verified by community' },
      { icon: '⚡', tone: 'bg-[#FFF7ED] text-[#F97316]', text: 'Personalised recommendations from local stores' },
    ],
  },
  'hot-food': {
    id: 'hot-food',
    label: 'Hot Food Partner',
    emoji: '🍔',
    category: 'Active Restaurant',
    desc: 'Restaurants serving fresh meals to homes inside the neighbourhood radius.',
    metric: 'Live kitchen · Fast last-mile',
    bullets: [
      { icon: '🛡️', tone: 'bg-[#ECFDF5] text-[#10B981]', text: 'FSSAI compliant kitchens, live order pipeline' },
      { icon: '⚡', tone: 'bg-[#FFF7ED] text-[#F97316]', text: 'Average meal handover under 12 minutes' },
    ],
  },
  'community': {
    id: 'community',
    label: 'Community Homes',
    emoji: '🏠',
    category: 'Community Home',
    desc: 'Residential pockets connected through one Nearle Deal household account.',
    metric: 'Shared trust · Neighbourhood feed',
    bullets: [
      { icon: '🛡️', tone: 'bg-[#ECFDF5] text-[#10B981]', text: 'Verified resident network with private community feed' },
      { icon: '⚡', tone: 'bg-[#FFF7ED] text-[#F97316]', text: 'Group orders unlock neighbourhood bulk pricing' },
    ],
  },
  'nearle-hood': {
    id: 'nearle-hood',
    label: 'Nearle Neighbourhood',
    emoji: '🏘️',
    category: 'Network Hub',
    desc: 'The Nearle hyper-hub orchestrating routing, payments, and trust for the area.',
    metric: 'Routing live · 100% uptime',
    bullets: [
      { icon: '🛡️', tone: 'bg-[#ECFDF5] text-[#10B981]', text: 'Real-time delivery orchestration with safe payouts' },
      { icon: '⚡', tone: 'bg-[#FFF7ED] text-[#F97316]', text: 'Smart matching between residents, shops, and riders' },
    ],
  },
}

export function NeighbourhoodMap() {
  const [selectedId, setSelectedId] = useState<string>('food-essentials')
  const selected = DETAIL_BY_ID[selectedId]!

  return (
    <div className="py-24 sm:py-32 bg-nearle-bgsoft px-5 sm:px-8 relative overflow-hidden">
      <div className="absolute inset-0 bg-grid-soft opacity-30 pointer-events-none" />

      <div className="max-w-7xl mx-auto">
        <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6 mb-12">
          <SectionHeader
            label="Neighbourhood Commerce Map"
            heading={
              <>
                Your neighbourhood,
                <br />
                <span className="bg-gradient-purple bg-clip-text text-transparent">
                  fully connected
                </span>
              </>
            }
            sub="Explore how local businesses, homes, restaurants, and service providers connect inside one neighbourhood commerce platform."
            align="left"
            className="max-w-2xl"
          />

          <div className="flex items-center gap-2 self-start lg:self-end bg-white border border-nearle-border rounded-full pl-2 pr-4 py-2 shadow-nearle-sm">
            <span className="w-6 h-6 rounded-full bg-purple-primary" />
            <span className="font-display font-extrabold text-nearle-dark text-[11px] sm:text-xs uppercase tracking-wider">
              Connecting local business with the neighbourhood
            </span>
          </div>
        </div>

        <div className="grid lg:grid-cols-12 gap-8 items-stretch">
          {/* DETAIL CARD (4 cols) */}
          <div className="lg:col-span-4">
            <GlassCard className="h-full flex flex-col border-purple-lavender/50 shadow-nearle-md">
              <AnimatePresence mode="wait">
                <motion.div
                  key={selected.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  transition={{ duration: 0.25 }}
                  className="flex-1 flex flex-col"
                >
                  <div className="flex items-start gap-3 pb-5 border-b border-nearle-border">
                    <div className="w-12 h-12 rounded-2xl bg-purple-soft border border-purple-lavender/50 flex items-center justify-center text-2xl">
                      {selected.emoji}
                    </div>
                    <div>
                      <div className="label-mono text-purple-primary">
                        {selected.category}
                      </div>
                      <h3 className="font-display font-extrabold text-nearle-dark text-xl leading-tight mt-1">
                        {selected.label}
                      </h3>
                    </div>
                  </div>

                  <div className="pt-5">
                    <div className="flex items-center gap-2 mb-3">
                      <span className="w-4 h-4 rounded-full bg-purple-soft flex items-center justify-center text-[9px] text-purple-deep font-bold">
                        i
                      </span>
                      <span className="label-mono text-nearle-dark">
                        Neighbourhood Details
                      </span>
                    </div>
                    <p className="font-body text-nearle-mid text-sm leading-relaxed">
                      {selected.desc}
                    </p>
                  </div>

                  <div className="mt-5 rounded-2xl bg-purple-soft/60 border border-purple-lavender/40 p-4">
                    <div className="label-mono text-purple-primary mb-1">
                      Node Metrics
                    </div>
                    <div className="flex items-baseline gap-2">
                      <span className="font-body text-xs text-nearle-mid leading-snug w-20 shrink-0">
                        Nearle<br />Activity
                      </span>
                      <span className="font-display font-bold text-nearle-dark text-sm leading-snug">
                        {selected.metric}
                      </span>
                    </div>
                  </div>

                  <div className="mt-5 space-y-3">
                    {selected.bullets.map((b, i) => (
                      <div key={i} className="flex items-start gap-3">
                        <div className={`w-8 h-8 rounded-xl flex items-center justify-center text-sm shrink-0 ${b.tone}`}>
                          {b.icon}
                        </div>
                        <p className="font-body text-sm text-nearle-dark leading-snug pt-1">
                          {b.text}
                        </p>
                      </div>
                    ))}
                  </div>
                </motion.div>
              </AnimatePresence>
            </GlassCard>
          </div>

          {/* 3D MAP CANVAS (8 cols) */}
          <div className="lg:col-span-8 relative aspect-[4/3] sm:aspect-[16/11] bg-white rounded-3xl border border-nearle-border shadow-nearle-md overflow-hidden">
            {/* Legend chips */}
            <div className="absolute top-4 left-4 z-10 flex flex-col gap-2">
              <LegendChip color="#683285" label="Food Essentials / Shops" />
              <LegendChip color="#AE79BF" label="Active Restaurants" />
              <LegendChip color="#3B82F6" label="People / Neighbourhoods" emoji="🏠" />
            </div>

            <IsoMap3D
              selectedId={selectedId}
              onSelect={(id) => setSelectedId(id)}
            />
          </div>
        </div>
      </div>
    </div>
  )
}

function LegendChip({
  color,
  label,
  emoji,
  suffix,
}: {
  color: string
  label: string
  emoji?: string
  suffix?: string
}) {
  return (
    <div className="inline-flex items-center gap-2 bg-white border border-nearle-border rounded-full px-3 py-1.5 shadow-nearle-sm">
      <span
        className="w-2.5 h-2.5 rounded-full"
        style={{ backgroundColor: color }}
      />
      <span className="font-body text-[11px] font-semibold text-nearle-dark">
        {label}
      </span>
      {suffix && (
        <span className="font-body text-[11px] text-nearle-mid">
          {emoji} {suffix}
        </span>
      )}
    </div>
  )
}
