import React from 'react'
import Link from 'next/link'
import { getFeaturedSpots, getHomeStats } from '@/lib/spots'

export const dynamic = 'force-dynamic'
import { HomeSearch } from '@/components/HomeSearch'
import './page.css'

const ZONE_MAP: Record<string, { label: string; cls: string }> = {
  BEGINNER:     { label: 'Livre',    cls: 'free'   },
  INTERMEDIATE: { label: 'Condic.',  cls: 'cond'   },
  ADVANCED:     { label: 'Proibida', cls: 'banned' },
}

const DIFF_GRADIENT: Record<string, string> = {
  BEGINNER:     'linear-gradient(135deg,#7FC4FF,#0096FF)',
  INTERMEDIATE: 'linear-gradient(135deg,#FFD79A,#F5A623)',
  ADVANCED:     'linear-gradient(135deg,#9FB0C0,#3A4A5C)',
}

function normalizeImg(p: string) {
  return p.startsWith('/uploads/') ? `/api${p}` : p
}

function parseImages(val: unknown): string[] {
  if (Array.isArray(val)) return val as string[]
  if (typeof val === 'string') { try { const p = JSON.parse(val); return Array.isArray(p) ? p : [] } catch { return [] } }
  return []
}

function starsStr(n: number) {
  const full = Math.round(n)
  return '★'.repeat(full) + '☆'.repeat(5 - full)
}

export default async function HomePage() {
  const [spots, { spotCount, userCount }] = await Promise.all([
    getFeaturedSpots(3),
    getHomeStats(),
  ])

  return (
    <>
      {/* ── Hero ── */}
      <section className="hero">
        <svg className="hero-path" viewBox="0 0 1280 320" preserveAspectRatio="none" aria-hidden="true">
          <path d="M-20 220 C 240 160,400 280,640 210 S 1060 110,1300 160" fill="none" stroke="#0096FF" strokeWidth="2" strokeDasharray="2 12" strokeLinecap="round" />
        </svg>

        <div className="hero-inner">
          <div>
            <span className="eyebrow">A 1ª PLATAFORMA DE DRONES EM PORTUGAL</span>
            <h1>Onde podes voar<br />o teu drone hoje?</h1>
            <p className="hero-desc">Descobre locais aprovados pela comunidade, consulta as zonas ANAC e a meteorologia — tudo num só mapa, gratuito e sem subscrição.</p>

            <HomeSearch />

            <div className="hero-actions">
              <Link href="/mapa" className="hero-cta-primary">Ver mapa completo</Link>
              <Link href="/spots" className="hero-cta-ghost">Explorar spots</Link>
            </div>

            <div className="hero-stats">
              <div className="hero-stat">
                <span className="hero-stat-num">{userCount}+</span>
                <span className="hero-stat-label">Pilotos registados</span>
              </div>
              <div className="hero-stat-divider" aria-hidden="true" />
              <div className="hero-stat">
                <span className="hero-stat-num">{spotCount}</span>
                <span className="hero-stat-label">Spots verificados</span>
              </div>
              <div className="hero-stat-divider" aria-hidden="true" />
              <div className="hero-stat">
                <span className="hero-stat-num">2 400+</span>
                <span className="hero-stat-label">Zonas ANAC mapeadas</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ── Split: Map preview + Spots panel ── */}
      <section className="split">
        <div className="map-preview">
          <svg className="map-bg" viewBox="0 0 520 440" aria-hidden="true">
            <rect width="520" height="440" fill="#DDE6EC" />
            <path d="M0 90 L520 70 M0 180 L520 165 M0 280 L520 270 M0 370 L520 360 M110 0 L90 440 M250 0 L235 440 M390 0 L378 440" stroke="#CAD6DF" strokeWidth="1.5" />
            <path d="M150 100 C 230 130,210 230,300 250 S 410 310,440 380" fill="none" stroke="#0096FF" strokeWidth="2.5" strokeDasharray="1 8" strokeLinecap="round" />
          </svg>
          <div className="map-pin" style={{ top: '96px', left: '118px' }}>
            <i className="map-pin-dot" style={{ background: 'var(--ov-free)' }} />
          </div>
          <div className="map-pin" style={{ top: '210px', left: '298px' }}>
            <i className="map-pin-dot" style={{ background: 'var(--ov-cond)' }} />
          </div>
          <div className="map-pin" style={{ top: '330px', left: '430px' }}>
            <i className="map-pin-dot" style={{ background: 'var(--ov-banned)' }} />
          </div>
          <div className="map-legend">
            <span><span className="leg-dot" style={{ background: 'var(--ov-free)' }} />Livre</span>
            <span><span className="leg-dot" style={{ background: 'var(--ov-cond)' }} />Condic.</span>
            <span><span className="leg-dot" style={{ background: 'var(--ov-banned)' }} />Proibida</span>
          </div>
          <Link href="/mapa" className="map-cta-link">Abrir mapa completo →</Link>
        </div>

        <div className="spots-panel">
          <div className="panel-header">
            <b>Spots em destaque</b>
            <Link href="/spots">Ver todos</Link>
          </div>

          <div className="spot-list-panel">
            {spots.length === 0 && (
              <p style={{ padding: '24px', color: '#64748b', fontSize: '14px' }}>
                Ainda sem spots aprovados. <Link href="/spots/novo">Adiciona o primeiro!</Link>
              </p>
            )}
            {spots.map((spot) => {
              const zone = ZONE_MAP[spot.difficulty] ?? { label: 'Livre', cls: 'free' }
              const imgs = parseImages(spot.coverImage)
              const img = imgs[0] ? normalizeImg(imgs[0]) : null
              const thumbStyle = img
                ? { backgroundImage: `url(${img})`, backgroundSize: 'cover', backgroundPosition: 'center' }
                : { background: DIFF_GRADIENT[spot.difficulty] ?? DIFF_GRADIENT.BEGINNER }
              const avg = Number(spot.avgRating)
              const reviews = Number(spot.reviewCount)
              return (
                <Link key={spot.id} href={`/spots/${spot.id}`} className="spot-row">
                  <div className="spot-thumb" style={thumbStyle} />
                  <div className="spot-info">
                    <div className="spot-name-row">
                      <span className="spot-name">{spot.name}</span>
                      <span className={`zone-chip zone-chip--${zone.cls}`}>{zone.label}</span>
                    </div>
                    <div className="spot-meta">{spot.lat.toFixed(2)}°N · {Math.abs(spot.lng).toFixed(2)}°W</div>
                    {avg > 0 ? (
                      <div className="spot-stars">
                        {starsStr(avg)} <span>{avg.toFixed(1)} · {reviews} {reviews === 1 ? 'review' : 'reviews'}</span>
                      </div>
                    ) : (
                      <div className="spot-meta">Sem reviews ainda</div>
                    )}
                  </div>
                </Link>
              )
            })}
          </div>
        </div>
      </section>

      {/* ── Features bar ── */}
      <div className="features-bar">
        {([
          {
            icon: (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <polygon points="3 6 9 3 15 6 21 3 21 18 15 21 9 18 3 21"/>
                <line x1="9" y1="3" x2="9" y2="18"/><line x1="15" y1="6" x2="15" y2="21"/>
              </svg>
            ),
            title: 'Zonas ANAC',
            desc: 'Livre, condicionada e proibida em tempo real',
          },
          {
            icon: (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
                <circle cx="12" cy="10" r="3"/>
              </svg>
            ),
            title: 'Spots verificados',
            desc: 'Locais aprovados pela comunidade de pilotos',
          },
          {
            icon: (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9z"/>
              </svg>
            ),
            title: 'Meteorologia',
            desc: 'Condições actualizadas de 30 em 30 minutos',
          },
          {
            icon: (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
                <line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>
              </svg>
            ),
            title: 'NOTAMs',
            desc: 'Restrições temporárias antes de descolar',
          },
        ] as const).map((f) => (
          <div key={f.title} className="feature-item">
            <span className="feature-item-icon">{f.icon}</span>
            <p className="feature-item-title">{f.title}</p>
            <p className="feature-item-desc">{f.desc}</p>
          </div>
        ))}
      </div>

      {/* ── CTA ── */}
      <section className="cta-section">
        <div>
          <h2 className="cta-section-title">Pronto para descolar?</h2>
          <p className="cta-section-desc">Gratuito, sem subscrição. Feito por pilotos, para pilotos.</p>
          <Link href="/auth/register" className="cta-btn">Criar conta gratuita →</Link>
        </div>
      </section>
    </>
  )
}
