'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { projectCoord } from '@/lib/map-projection'
import { mineralColor, MINERAL_COLORS } from '@/lib/minerals'
import { COMMODITY_SYMBOLS, COMMODITY_LABELS, type Commodity } from '@/lib/constants'
import type { MapPin } from '@/lib/map-pin'
import { Icon } from './Icon'

const LAYERS = ['Satelital', 'Geológico', 'Concesiones', 'Infraestr.']
const LEGEND: Commodity[] = ['CU', 'AU', 'AG', 'LI', 'FE', 'MO']

export function SatelliteMap({
  pins,
  height = 560,
  hoveredId,
  onHover,
  onSelect,
  selectedId,
  showChrome = true,
}: {
  pins: MapPin[]
  height?: number
  hoveredId?: string | null
  onHover?: (id: string | null) => void
  onSelect?: (pin: MapPin) => void
  selectedId?: string | null
  showChrome?: boolean
}) {
  const router = useRouter()
  const [localHover, setLocalHover] = useState<string | null>(null)
  const hover = hoveredId !== undefined ? hoveredId : localHover
  const setHover = (id: string | null) => {
    setLocalHover(id)
    onHover?.(id)
  }
  const [layer, setLayer] = useState('Satelital')

  return (
    <div
      style={{
        position: 'relative',
        width: '100%',
        height,
        background: '#cdbfa6',
        overflow: 'hidden',
      }}
    >
      {/* Textura satelital — gradientes de terreno árido */}
      <div
        style={{
          position: 'absolute',
          inset: 0,
          background: `
            radial-gradient(ellipse at 68% 22%, rgba(184,115,51,0.30), transparent 42%),
            radial-gradient(ellipse at 40% 48%, rgba(122,59,46,0.26), transparent 46%),
            radial-gradient(ellipse at 30% 12%, rgba(120,95,60,0.30), transparent 40%),
            radial-gradient(ellipse at 58% 78%, rgba(45,106,79,0.20), transparent 42%),
            radial-gradient(ellipse at 80% 60%, rgba(150,120,80,0.25), transparent 40%),
            linear-gradient(160deg, #c9b48f 0%, #b89a72 45%, #9c8560 100%)
          `,
        }}
      />
      {/* Curvas de nivel + océano + relieve */}
      <svg
        viewBox="0 0 600 560"
        preserveAspectRatio="none"
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.5 }}
      >
        {/* Océano Pacífico (borde oeste) */}
        <path d="M0 0 L120 0 Q150 160 120 300 Q100 440 130 560 L0 560 Z" fill="#5e7d86" opacity="0.55" />
        <path d="M120 0 Q150 160 120 300 Q100 440 130 560" fill="none" stroke="rgba(20,20,20,0.4)" strokeWidth="1.4" />
        {/* Curvas de nivel topográficas (cordillera) */}
        {Array.from({ length: 9 }).map((_, i) => (
          <path
            key={i}
            d={`M ${180 + i * 16} 0 Q ${210 + i * 18} ${150 + i * 8} ${250 + i * 20} ${300 + i * 6} Q ${290 + i * 22} ${450 - i * 5} ${320 + i * 24} 560`}
            fill="none"
            stroke="rgba(60,40,25,0.35)"
            strokeWidth="0.7"
          />
        ))}
        {/* Picos nevados */}
        {[[300, 130], [360, 250], [330, 360], [400, 200]].map(([cx, cy], i) => (
          <path key={i} d={`M ${cx - 14} ${cy + 8} L ${cx} ${cy - 10} L ${cx + 14} ${cy + 8} Z`} fill="rgba(245,241,232,0.5)" />
        ))}
      </svg>

      {/* Grilla UTM */}
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', opacity: 0.18 }}>
        <defs>
          <pattern id="mapgrid" width="56" height="56" patternUnits="userSpaceOnUse">
            <path d="M 56 0 L 0 0 0 56" fill="none" stroke="rgba(20,20,20,0.5)" strokeWidth="0.4" />
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill="url(#mapgrid)" />
      </svg>

      {/* Pines */}
      {pins.map((p) => {
        const { x, y } = projectCoord(p.lat, p.lng)
        const isSel = selectedId === p.id
        const isHov = hover === p.id
        const symbol = COMMODITY_SYMBOLS[p.mineral as Commodity] ?? p.mineral
        return (
          <button
            key={p.id}
            onClick={() => (onSelect ? onSelect(p) : router.push(`/marketplace/${p.slug}`))}
            onMouseEnter={() => setHover(p.id)}
            onMouseLeave={() => setHover(null)}
            aria-label={p.title}
            style={{
              position: 'absolute',
              left: `calc(${x * 100}% - 18px)`,
              top: `calc(${y * 100}% - 36px)`,
              zIndex: isSel || isHov ? 20 : 10,
              background: 'none',
              border: 0,
              padding: 0,
            }}
          >
            <div
              style={{
                width: 34,
                height: 34,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                background: isSel ? 'var(--accent)' : 'var(--bg-elev)',
                border: `1.5px solid ${isSel ? 'var(--accent)' : 'var(--ink)'}`,
                color: isSel ? '#fff' : 'var(--ink)',
                fontFamily: 'var(--f-mono)',
                fontSize: 10.5,
                fontWeight: 700,
                boxShadow: isSel || isHov ? '0 8px 24px rgba(20,20,20,0.3)' : '0 2px 4px rgba(20,20,20,0.2)',
                transform: isHov || isSel ? 'scale(1.12)' : 'scale(1)',
                transition: 'transform .12s, background .12s',
                position: 'relative',
              }}
            >
              <span
                style={{
                  position: 'absolute',
                  top: -2,
                  right: -2,
                  width: 8,
                  height: 8,
                  background: mineralColor(p.mineral),
                  border: `1px solid ${isSel ? '#fff' : 'var(--ink)'}`,
                }}
              />
              {symbol}
            </div>
            <div
              style={{
                position: 'absolute',
                left: '50%',
                top: '100%',
                transform: 'translateX(-50%)',
                width: 0,
                height: 0,
                borderLeft: '4px solid transparent',
                borderRight: '4px solid transparent',
                borderTop: `6px solid ${isSel ? 'var(--accent)' : 'var(--ink)'}`,
              }}
            />
            {(isHov || isSel) && (
              <div
                style={{
                  position: 'absolute',
                  left: '50%',
                  top: 'calc(100% + 10px)',
                  transform: 'translateX(-50%)',
                  background: 'var(--ink)',
                  color: 'var(--bg-elev)',
                  padding: '8px 12px',
                  minWidth: 180,
                  fontSize: 11,
                  pointerEvents: 'none',
                  zIndex: 30,
                  textAlign: 'left',
                }}
              >
                <div className="mono uppercase-wide" style={{ fontSize: 9, opacity: 0.6, letterSpacing: '0.08em' }}>
                  {p.stageCode} · {p.region}
                </div>
                <div style={{ fontWeight: 600, marginTop: 2, fontSize: 12, lineHeight: 1.2 }}>{p.title}</div>
                <div className="mono" style={{ marginTop: 4, fontSize: 10, opacity: 0.75 }}>
                  {p.haLabel} · {p.priceLabel}
                </div>
              </div>
            )}
          </button>
        )
      })}

      {showChrome && (
        <>
          {/* Proyección / escala */}
          <div
            className="mono"
            style={{
              position: 'absolute',
              top: 14,
              left: 14,
              background: 'rgba(251,249,244,0.92)',
              border: '1px solid var(--line-soft)',
              padding: '8px 10px',
              fontSize: 10,
              letterSpacing: '0.05em',
              color: 'var(--ink-2)',
            }}
          >
            <div className="uppercase-wide" style={{ color: 'var(--muted)', fontSize: 9 }}>Proyección</div>
            <div style={{ fontWeight: 600, marginTop: 2 }}>UTM 19S · WGS84</div>
            <div style={{ marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--line-softer)' }}>
              <div className="uppercase-wide" style={{ color: 'var(--muted)', fontSize: 9 }}>Escala</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
                <div style={{ width: 60, height: 4, background: 'linear-gradient(90deg, var(--ink) 50%, transparent 50%)', backgroundSize: '12px 4px' }} />
                <span>200 km</span>
              </div>
            </div>
          </div>

          {/* Capas */}
          <div
            style={{
              position: 'absolute',
              top: 14,
              right: 14,
              display: 'flex',
              flexDirection: 'column',
              border: '1px solid var(--line-soft)',
              background: 'var(--bg-elev)',
            }}
          >
            {LAYERS.map((l) => {
              const active = layer === l
              return (
                <button
                  key={l}
                  onClick={() => setLayer(l)}
                  className="mono uppercase-wide"
                  style={{
                    padding: '6px 12px',
                    fontSize: 10,
                    letterSpacing: '0.06em',
                    borderBottom: '1px solid var(--line-softer)',
                    background: active ? 'var(--ink)' : 'transparent',
                    color: active ? 'var(--bg-elev)' : 'var(--muted)',
                    textAlign: 'left',
                    minWidth: 124,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 6,
                  }}
                >
                  <Icon name="layers" size={10} /> {l}
                </button>
              )
            })}
          </div>

          {/* Leyenda mineral */}
          <div
            className="mono"
            style={{
              position: 'absolute',
              bottom: 14,
              left: 14,
              background: 'rgba(251,249,244,0.92)',
              border: '1px solid var(--line-soft)',
              padding: '10px 12px',
              fontSize: 10,
            }}
          >
            <div className="uppercase-wide" style={{ fontSize: 9, color: 'var(--muted)', marginBottom: 6, letterSpacing: '0.08em' }}>
              Leyenda mineral
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 16px' }}>
              {LEGEND.map((k) => (
                <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ width: 8, height: 8, background: MINERAL_COLORS[k], display: 'inline-block' }} />
                  <b>{COMMODITY_SYMBOLS[k]}</b>
                  <span style={{ color: 'var(--muted)' }}>{COMMODITY_LABELS[k]}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Coords */}
          <div
            className="mono"
            style={{
              position: 'absolute',
              bottom: 14,
              right: 14,
              background: 'rgba(251,249,244,0.92)',
              border: '1px solid var(--line-soft)',
              padding: '8px 10px',
              fontSize: 10,
              color: 'var(--ink-2)',
              display: 'flex',
              gap: 14,
            }}
          >
            <div><span style={{ color: 'var(--muted)' }}>ACTIVOS</span> {pins.length}</div>
            <div><span style={{ color: 'var(--muted)' }}>ZOOM</span> 5.4</div>
          </div>
        </>
      )}
    </div>
  )
}
