'use client'
import { useEffect, useRef } from 'react'
import { STATIONS, LINE_COLOURS, LINE_LABELS, STATUS_COLOURS, STATUS_LABELS, type Station } from '@/lib/stations'

export default function MetroMap({ height = '580px' }: { height?: string }) {
  const containerRef = useRef<HTMLDivElement>(null)
  const mapRef = useRef<unknown>(null)

  useEffect(() => {
    if (mapRef.current || !containerRef.current) return
    import('leaflet').then(L => {
      if (!document.querySelector('link[href*="leaflet"]')) {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'
        document.head.appendChild(link)
      }
      if (!containerRef.current) return
      const map = L.map(containerRef.current, { center: [50.42, -4.10], zoom: 11, zoomControl: true })
      mapRef.current = map
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        maxZoom: 18,
      }).addTo(map)

      // Group by line key — deduplicate Plymouth Station for each line
      const byLine: Record<string, Station[]> = {}
      STATIONS.forEach(s => {
        if (!byLine[s.line]) byLine[s.line] = []
        byLine[s.line].push(s)
      })

      // Draw route lines
      const solidLines = ['red','blue-east','blue-west','sherford']
      solidLines.forEach(lk => {
        const coords = (byLine[lk] || []).map(s => [s.lat, s.lng] as [number, number])
        if (coords.length > 1)
          L.polyline(coords, { color: LINE_COLOURS[lk], weight: 5, opacity: 0.85, lineJoin: 'round' }).addTo(map)
      })
      // Tamar — open section solid, reinstated dashed
      const tamarOpen = (byLine['tamar'] || []).filter(s => s.status === 'open')
      const tamarNew  = (byLine['tamar'] || []).filter(s => s.id === 't8' || s.id === 't9')
      if (tamarOpen.length > 1)
        L.polyline(tamarOpen.map(s => [s.lat, s.lng] as [number,number]),
          { color: LINE_COLOURS['tamar'], weight: 5, opacity: 0.85, lineJoin: 'round' }).addTo(map)
      if (tamarNew.length > 1)
        L.polyline(tamarNew.map(s => [s.lat, s.lng] as [number,number]),
          { color: LINE_COLOURS['tamar'], weight: 5, opacity: 0.85, dashArray: '10,8', lineJoin: 'round' }).addTo(map)

      // Station markers — deduplicate by lat/lng (Plymouth Station appears on all lines)
      const drawn = new Set<string>()
      STATIONS.forEach(station => {
        const key = `${station.lat},${station.lng}`
        // For interchanges, only draw once
        if (station.interchange && drawn.has(key)) return
        drawn.add(key)
        const lc = LINE_COLOURS[station.line]
        const sc = STATUS_COLOURS[station.status]
        const sz = station.interchange ? 18 : 12
        const bw = station.interchange ? 3 : 2
        const icon = L.divIcon({
          className: '',
          html: `<div style="width:${sz}px;height:${sz}px;border-radius:50%;background:${sc};border:${bw}px solid ${lc};box-shadow:0 2px 6px rgba(0,0,0,0.3);${station.interchange?'outline:2px solid '+lc+';outline-offset:2px;':''}"></div>`,
          iconSize:[sz,sz], iconAnchor:[sz/2,sz/2],
        })
        const sbg:Record<Station['status'],string> = { open:'#DCFCE7','disused-station':'#FEF9C3','disused-trackbed':'#FEE2E2','new-build':'#F3F4F6' }
        const stx:Record<Station['status'],string> = { open:'#166534','disused-station':'#92400E','disused-trackbed':'#991B1B','new-build':'#374151' }
        const closed = station.closedYear ? `<p style="font-size:11px;color:#6B7E9A;margin:3px 0 0;">Closed: ${station.closedYear}</p>` : ''
        const notes = station.notes ? `<p style="font-size:11px;color:#374151;margin:5px 0 0;padding-top:5px;border-top:1px solid #e5e7eb;">${station.notes}</p>` : ''
        const html = `<div style="min-width:205px;max-width:265px;">
          <div style="display:flex;align-items:center;gap:7px;margin-bottom:6px;">
            <span style="width:10px;height:10px;border-radius:50%;background:${sc};border:2px solid ${lc};display:inline-block;flex-shrink:0;"></span>
            <strong style="font-size:14px;color:#0B2545;">${station.name}</strong>
          </div>
          <span style="display:inline-block;font-size:11px;font-weight:600;padding:2px 7px;border-radius:99px;background:${sbg[station.status]};color:${stx[station.status]};margin-bottom:5px;">${STATUS_LABELS[station.status]}</span>
          <p style="font-size:12px;color:#6B7E9A;margin:0;">${LINE_LABELS[station.line]} · Zone ${station.zone}</p>
          ${closed}
          ${station.interchange?'<span style="display:inline-block;margin-top:5px;background:#F0F6FF;color:#1B4F8A;font-size:11px;font-weight:600;padding:2px 7px;border-radius:99px;">Interchange</span>':''}
          <p style="font-size:11px;color:#3D5275;margin-top:6px;line-height:1.5;">${station.description}</p>
          ${notes}
          <a href="/stations/${station.slug}" style="display:inline-block;margin-top:8px;font-size:11px;font-weight:600;color:#2E9CCA;">View station details →</a>
        </div>`
        L.marker([station.lat, station.lng], { icon })
          .addTo(map).bindPopup(html, { maxWidth: 285 })
      })
    })
    return () => {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      if (mapRef.current) { (mapRef.current as any).remove(); mapRef.current = null }
    }
  }, [])

  return (
    <div className="w-full rounded-2xl overflow-hidden shadow-lg border border-metro-border">
      <div ref={containerRef} style={{ height }} className="w-full" />
    </div>
  )
}
