import Link from 'next/link'
import { parseSearchParams } from '@/lib/filters'
import { getListings } from '@/lib/listings'
import { toMapPins } from '@/lib/map-pin'
import { primaryCommodity } from '@/lib/listing-view'
import { Facets, type FacetCounts } from '@/components/terrano/Facets'
import { CatalogResults } from '@/components/terrano/CatalogResults'
import type { ListingWithRelations } from '@/lib/listings'

export const dynamic = 'force-dynamic'

function computeCounts(all: ListingWithRelations[]): FacetCounts {
  const counts: FacetCounts = { commodity: {}, stage: {}, dealType: {}, country: {}, verified: 0, total: all.length }
  for (const l of all) {
    const primary = primaryCommodity(l)
    if (primary) counts.commodity[primary] = (counts.commodity[primary] ?? 0) + 1
    if (l.stage) counts.stage[l.stage] = (counts.stage[l.stage] ?? 0) + 1
    const seenDeals = new Set<string>()
    for (const d of l.dealTypes) {
      if (seenDeals.has(d.dealType)) continue
      seenDeals.add(d.dealType)
      counts.dealType[d.dealType] = (counts.dealType[d.dealType] ?? 0) + 1
    }
    counts.country[l.country] = (counts.country[l.country] ?? 0) + 1
    if (l.verified) counts.verified += 1
  }
  return counts
}

export default async function MarketplacePage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>
}) {
  const params = await searchParams
  const filter = parseSearchParams(params)
  const [listings, all] = await Promise.all([
    getListings(filter),
    getListings({ verifiedOnly: false, sort: 'recientes' }),
  ])
  const counts = computeCounts(all)
  const pins = toMapPins(listings)

  return (
    <div>
      {/* Cabecera */}
      <section className="bleed" style={{ padding: '28px 28px 20px', borderBottom: '1px solid var(--line-soft)' }}>
        <div className="mono uppercase-wide" style={{ fontSize: 10, color: 'var(--muted)', letterSpacing: '0.1em', marginBottom: 10 }}>
          <Link href="/" style={{ textDecoration: 'underline' }}>Inicio</Link>
          {' / '}Marketplace{' / '}
          <span style={{ color: 'var(--ink)' }}>Activos mineros</span>
        </div>
        <h1 className="display" style={{ fontSize: 'clamp(28px, 4vw, 40px)', fontWeight: 600, margin: 0, letterSpacing: '-0.03em' }}>
          Activos mineros · Latinoamérica
        </h1>
        <div className="mono" style={{ fontSize: 12, color: 'var(--muted)', marginTop: 6 }}>
          Concesiones, propiedades, plantas y relaves publicados en Portal Minería.
        </div>
      </section>

      <div className="catalog-grid" style={{ display: 'grid', gridTemplateColumns: '260px 1fr', minHeight: 600 }}>
        <Facets counts={counts} />
        <main style={{ padding: 24 }}>
          <CatalogResults listings={listings} pins={pins} />
        </main>
      </div>
    </div>
  )
}
