import { useState } from 'react'
import { ComposableMap, Geographies, Geography } from 'react-simple-maps'

const WORLD_URL = 'https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json'
const US_URL = 'https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json'

// Normalize topojson country names to match what geolocation APIs typically return
const COUNTRY_ALIASES: Record<string, string> = {
  'united states of america': 'united states',
  'russian federation': 'russia',
  'republic of korea': 'south korea',
  "democratic people's republic of korea": 'north korea',
  'united kingdom of great britain and northern ireland': 'united kingdom',
  'iran (islamic republic of)': 'iran',
  'syrian arab republic': 'syria',
  'bolivarian republic of venezuela': 'venezuela',
  'plurinational state of bolivia': 'bolivia',
  'united republic of tanzania': 'tanzania',
  'democratic republic of the congo': 'dr congo',
  "lao people's democratic republic": 'laos',
  'viet nam': 'vietnam',
  'taiwan, province of china': 'taiwan',
}

function normalizeCountry(name: string): string {
  const lower = name.toLowerCase()
  return COUNTRY_ALIASES[lower] ?? lower
}

function getColor(hits: number, max: number, baseColor = '#1e1e18'): string {
  if (!hits || max === 0) return baseColor
  const t = Math.sqrt(hits / max) // sqrt for better visual spread
  const r = Math.round(30 + (201 - 30) * t)
  const g = Math.round(30 + (168 - 30) * t)
  const b = Math.round(21 + (76 - 21) * t)
  return `rgb(${r},${g},${b})`
}

interface TooltipState {
  name: string
  hits: number
  x: number
  y: number
}

interface GeoMapsProps {
  topCountries: Array<{ name: string; hits: number }>
  topStates: Array<{ name: string; hits: number }>
}

export default function GeoMaps({ topCountries, topStates }: GeoMapsProps) {
  const [tooltip, setTooltip] = useState<TooltipState | null>(null)

  const countryMap = new Map(topCountries.map(c => [c.name.toLowerCase(), c.hits]))
  const stateMap = new Map(topStates.map(s => [s.name.toLowerCase(), s.hits]))
  const maxCountry = Math.max(...topCountries.map(c => c.hits), 1)
  const maxState = Math.max(...topStates.map(s => s.hits), 1)

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '2rem' }}>

      {/* World map */}
      <div style={{ backgroundColor: '#1a1a15', padding: '1.5rem', borderRadius: '0.5rem', border: '1px solid #2a2518', position: 'relative' }}>
        <h3 style={{ marginBottom: '0.75rem', color: '#c9a84c', fontFamily: 'var(--brand-font-body)', textTransform: 'uppercase', letterSpacing: '0.08em', fontSize: '0.85rem' }}>
          Visitors by Country
        </h3>
        {topCountries.length === 0 && (
          <p style={{ color: '#b0a48c', fontSize: '0.875rem' }}>No country data yet.</p>
        )}
        <ComposableMap
          projectionConfig={{ scale: 145, center: [0, 10] }}
          style={{ width: '100%', height: 'auto', display: 'block' }}
        >
          <Geographies geography={WORLD_URL}>
            {({ geographies }) =>
              geographies.map(geo => {
                const geoName = geo.properties?.name ?? ''
                const normalized = normalizeCountry(geoName)
                const hits = countryMap.get(normalized) ?? countryMap.get(geoName.toLowerCase()) ?? 0
                return (
                  <Geography
                    key={geo.rsmKey ?? geoName}
                    geography={geo}
                    fill={getColor(hits, maxCountry)}
                    stroke="#0a0a08"
                    strokeWidth={0.4}
                    style={{
                      default: { outline: 'none' },
                      hover: { outline: 'none', fill: hits ? '#e0c070' : '#2a2a22', cursor: 'default' },
                      pressed: { outline: 'none' },
                    }}
                    onMouseEnter={(e) => setTooltip({ name: geoName, hits, x: e.clientX, y: e.clientY })}
                    onMouseMove={(e) => setTooltip(t => t ? { ...t, x: e.clientX, y: e.clientY } : null)}
                    onMouseLeave={() => setTooltip(null)}
                  />
                )
              })
            }
          </Geographies>
        </ComposableMap>

        {/* Color legend */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginTop: '0.5rem' }}>
          <span style={{ fontSize: '0.7rem', color: '#888' }}>0</span>
          <div style={{ flex: 1, height: '8px', borderRadius: '4px', background: 'linear-gradient(to right, #1e1e18, rgb(201,168,76))' }} />
          <span style={{ fontSize: '0.7rem', color: '#888' }}>{maxCountry.toLocaleString()} visits</span>
        </div>
      </div>

      {/* US states map */}
      <div style={{ backgroundColor: '#1a1a15', padding: '1.5rem', borderRadius: '0.5rem', border: '1px solid #2a2518', position: 'relative' }}>
        <h3 style={{ marginBottom: '0.75rem', color: '#c9a84c', fontFamily: 'var(--brand-font-body)', textTransform: 'uppercase', letterSpacing: '0.08em', fontSize: '0.85rem' }}>
          Visitors by US State
        </h3>
        {topStates.length === 0 && (
          <p style={{ color: '#b0a48c', fontSize: '0.875rem' }}>No state data yet.</p>
        )}
        <ComposableMap
          projection="geoAlbersUsa"
          style={{ width: '100%', height: 'auto', display: 'block' }}
        >
          <Geographies geography={US_URL}>
            {({ geographies }) =>
              geographies.map(geo => {
                const geoName = geo.properties?.name ?? ''
                const hits = stateMap.get(geoName.toLowerCase()) ?? 0
                return (
                  <Geography
                    key={geo.rsmKey ?? geoName}
                    geography={geo}
                    fill={getColor(hits, maxState)}
                    stroke="#0a0a08"
                    strokeWidth={0.8}
                    style={{
                      default: { outline: 'none' },
                      hover: { outline: 'none', fill: hits ? '#e0c070' : '#2a2a22', cursor: 'default' },
                      pressed: { outline: 'none' },
                    }}
                    onMouseEnter={(e) => setTooltip({ name: geoName, hits, x: e.clientX, y: e.clientY })}
                    onMouseMove={(e) => setTooltip(t => t ? { ...t, x: e.clientX, y: e.clientY } : null)}
                    onMouseLeave={() => setTooltip(null)}
                  />
                )
              })
            }
          </Geographies>
        </ComposableMap>

        {/* Color legend */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginTop: '0.5rem' }}>
          <span style={{ fontSize: '0.7rem', color: '#888' }}>0</span>
          <div style={{ flex: 1, height: '8px', borderRadius: '4px', background: 'linear-gradient(to right, #1e1e18, rgb(201,168,76))' }} />
          <span style={{ fontSize: '0.7rem', color: '#888' }}>{maxState.toLocaleString()} visits</span>
        </div>
      </div>

      {/* Tooltip */}
      {tooltip && (
        <div style={{
          position: 'fixed',
          left: tooltip.x + 14,
          top: tooltip.y - 36,
          backgroundColor: '#111',
          border: '1px solid #c9a84c',
          borderRadius: '4px',
          padding: '4px 10px',
          pointerEvents: 'none',
          zIndex: 9999,
          fontSize: '0.8rem',
          color: '#f0ead8',
          whiteSpace: 'nowrap',
          boxShadow: '0 2px 8px rgba(0,0,0,0.5)',
        }}>
          <strong style={{ color: '#c9a84c' }}>{tooltip.name}</strong>
          {' — '}
          {tooltip.hits > 0 ? <>{tooltip.hits.toLocaleString()} visit{tooltip.hits !== 1 ? 's' : ''}</> : 'no visits'}
        </div>
      )}
    </div>
  )
}
