import React, {
  ReactElement,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import Head from 'next/head';
import Link from 'next/link';
import axios from 'axios';
import {
  mdiArrowRight,
  mdiCash,
  mdiChartTimelineVariant,
  mdiClockOutline,
  mdiCrosshairsGps,
  mdiDatabaseSearchOutline,
  mdiFire,
  mdiLayersTripleOutline,
  mdiMagnify,
  mdiMapMarkerDistance,
  mdiMapMarkerRadiusOutline,
  mdiMapSearchOutline,
  mdiNavigationVariantOutline,
  mdiPackageVariantClosed,
  mdiRadar,
  mdiRobotHappyOutline,
  mdiShieldCheckOutline,
  mdiStar,
  mdiStorefrontOutline,
  mdiTextSearch,
  mdiTrendingUp,
} from '@mdi/js';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import LayoutGuest from '../layouts/Guest';
import { getPageTitle } from '../config';

type Category = {
  id: string;
  name: string;
  slug: string;
  description?: string;
  color_hex?: string;
};

type Offering = {
  id: string;
  name: string;
  description?: string;
  offering_type: 'product' | 'service';
  price?: number | null;
  stock_status: 'in_stock' | 'limited' | 'out_of_stock' | 'by_request';
  stock_label: string;
  stock_quantity?: number | null;
  is_verified?: boolean;
};

type OfferingSummary = {
  total: number;
  available: number;
  products: number;
  services: number;
  verified: number;
  top_available: Offering[];
};

type GeoScoreBreakdown = {
  relevance: number;
  distance: number;
  reputation: number;
  activity: number;
  interaction: number;
};

type RadiusZone = {
  value: number;
  label: string;
  range: string;
  description?: string;
};

type LiveStatus = {
  status: 'open' | 'closed';
  label: string;
  crowd: string;
  updated_label: string;
  source?: string;
};

type AiRecommendation = {
  label: string;
  reason: string;
  source?: string;
};

type PublicPlace = {
  id: string;
  name: string;
  short_description?: string;
  address?: string;
  city?: string;
  province?: string;
  latitude?: number | null;
  longitude?: number | null;
  phone_number?: string;
  whatsapp_number?: string;
  google_maps_url?: string;
  website_url?: string;
  price_level?: string;
  average_price?: number | null;
  rating_average?: number | null;
  rating_count?: number;
  is_verified?: boolean;
  distance_km?: number | null;
  search_score?: number;
  geo_score?: number;
  geo_score_breakdown?: GeoScoreBreakdown;
  radius_zone?: RadiusZone;
  live_status?: LiveStatus;
  ai_recommendation?: AiRecommendation;
  external_source?: string;
  offerings?: Offering[];
  offerings_summary?: OfferingSummary;
  category?: Category | null;
};

type LocationState = {
  lat: number;
  lng: number;
  label: string;
};


type SearchOrigin = {
  lat: number;
  lng: number;
  label: string;
  source: 'browser' | 'query_keyword' | 'default_local_keyword' | string;
  matched_keyword?: string;
  note?: string;
};

type DistanceBucket = {
  radius_km: number;
  label: string;
  zone_label: string;
  count: number;
};

type TrendingMeta = {
  local_topics: { name: string; count: number; label: string }[];
  products: {
    name: string;
    place_name: string;
    stock_label: string;
    type: string;
  }[];
  events: string[];
  live: { open_now: number; total: number };
};

type SearchMeta = {
  count: number;
  radius_km?: number | null;
  effective_radius_km?: number | null;
  radius_zone?: RadiusZone | null;
  radius_zones: RadiusZone[];
  distance_buckets: DistanceBucket[];
  filtered_by_radius: boolean;
  total_candidates: number;
  geo_score_formula: Record<string, number>;
  trending?: TrendingMeta;
  recommendation_engine?: string;
  expanded_for_nearest?: boolean;
  external_sources?: string[];
  external_source_errors?: string[];
  search_origin?: SearchOrigin | null;
};

const LOCATION_REQUIRED_MESSAGE =
  'Aktifkan izin lokasi browser agar GeoSeek memakai lokasi Anda, bukan titik default.';

const DEFAULT_RADIUS_KM = 5;
const GLOBAL_RADIUS_KM = 20038;


const keywordLocationPhrases = [
  'maps',
  'google maps',
  'maps google',
  'peta',
  'google earth',
  'waze',
  'street view',
  'google maps satellite',
  'peta indonesia',
  'cuaca',
  'cuaca hari ini',
  'prakiraan cuaca',
  'bmkg',
  'ramalan cuaca',
  'cuaca esok hari',
  'terdekat',
  'dekat saya',
  'near me',
  'jakarta',
  'bogor',
  'bekasi',
  'tangerang',
  'depok',
  'cikarang',
  'karawang',
  'bandung',
  'cafe',
  'restoran',
  'kuliner',
  'rumah makan',
  'tempat makan',
  'warkop',
  'kedai kopi',
  'hotel',
  'penginapan',
  'villa',
  'homestay',
  'kos',
  'kost',
  'kontrakan',
  'apartemen',
  'pom bensin',
  'spbu',
  'pertamini',
  'bengkel',
  'tambal ban',
  'atm',
  'bank',
  'minimarket',
  'indomaret',
  'alfamart',
  'supermarket',
  'toko kelontong',
  'pasar',
  'mall',
  'pusat perbelanjaan',
  'toko obat',
  'apotek',
  'rumah sakit',
  'puskesmas',
  'klinik',
  'dokter',
  'salon',
  'barbershop',
  'spa',
  'pijat',
  'gym',
  'fitness',
  'taman',
  'wisata',
  'masjid',
  'mushola',
  'gereja',
  'pura',
  'vihara',
  'sekolah',
  'kampus',
  'universitas',
  'stasiun',
  'halte',
  'terminal',
  'bandara',
  'band',
];

const normalizeSearchText = (value: string) =>
  value
    .toLowerCase()
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9]+/g, ' ')
    .trim();

const canSearchWithKeywordOrigin = (value: string) => {
  const normalized = normalizeSearchText(value);

  if (!normalized) {
    return false;
  }

  return keywordLocationPhrases.some((phrase) =>
    normalized.includes(normalizeSearchText(phrase)),
  );
};

const toSearchOrigin = (value: unknown): SearchOrigin | null => {
  if (!value || typeof value !== 'object') {
    return null;
  }

  const origin = value as Partial<SearchOrigin>;
  const lat = Number(origin.lat);
  const lng = Number(origin.lng);

  if (!Number.isFinite(lat) || !Number.isFinite(lng) || !origin.label) {
    return null;
  }

  return {
    lat,
    lng,
    label: String(origin.label),
    source: origin.source || 'query_keyword',
    matched_keyword: origin.matched_keyword,
    note: origin.note,
  };
};

const fallbackRadiusZones: RadiusZone[] = [
  { value: 1, label: 'Walking Zone', range: '0–1 Km' },
  { value: 5, label: 'Neighborhood Zone', range: '1–5 Km' },
  { value: 25, label: 'City Zone', range: '5–25 Km' },
  { value: 100, label: 'Regional Zone', range: '25–100 Km' },
  { value: 500, label: 'Provincial Zone', range: '100–500 Km' },
  { value: GLOBAL_RADIUS_KM, label: 'Global Zone', range: '500+ Km' },
];

const priceLabels: Record<string, string> = {
  budget: 'Ramah kantong',
  midrange: 'Menengah',
  premium: 'Premium',
  unknown: 'Tanya harga',
};

const mainAdvantages = [
  {
    title: 'Pencarian Radius Instan',
    icon: mdiRadar,
    metric: '0–5 Km',
    metricLabel: 'prioritas area terdekat',
    description:
      'Pengguna langsung menemukan tempat, produk, jasa, dan kebutuhan sekitar berdasarkan radius hyperlocal yang mudah diubah.',
    bullets: ['Walking Zone', 'Neighborhood', 'City/Regional'],
  },
  {
    title: 'Rute Dinamis & Cepat',
    icon: mdiNavigationVariantOutline,
    metric: 'Live',
    metricLabel: 'arah dan aksi cepat',
    description:
      'Hasil pencarian diarahkan ke aksi nyata: buka rute, cek stok, hubungi WhatsApp, booking layanan, atau lanjutkan ke kurir lokal.',
    bullets: ['Buka rute', 'Alternatif lokasi', 'Aksi 1-tap'],
  },
  {
    title: 'Data Berbasis Pengguna',
    icon: mdiDatabaseSearchOutline,
    metric: 'User Signal',
    metricLabel: 'laporan dan draft lokal',
    description:
      'Smart Input dan kontribusi pengguna membantu data komunitas bertambah cepat, dari UMKM baru sampai info jalan dan layanan sekitar.',
    bullets: ['Smart Input', 'Draft lokal', 'Update komunitas'],
  },
  {
    title: 'Mobilitas Harian Siap Pakai',
    icon: mdiPackageVariantClosed,
    metric: 'Driver+',
    metricLabel: 'mobil, ojek, taksi, kurir',
    description:
      'Aplikasi dibuat untuk kebutuhan bergerak cepat: pengemudi, pelanggan, UMKM, dan kurir bisa mengambil keputusan dalam satu layar.',
    bullets: ['Mobil', 'Ojek online', 'Taksi', 'Kurir lokal'],
  },
];

const comparisonAdvantages = [
  {
    title: 'Mesin Pencari Hyperlocal',
    icon: mdiMapMarkerRadiusOutline,
    description:
      'GeoSeek fokus pada produk, jasa, UMKM, dan transaksi lokal, bukan sekadar peta dan petunjuk arah.',
    points: [
      'Produk lokal',
      'Jasa lokal',
      'UMKM sekitar',
      'Transaksi langsung',
    ],
  },
  {
    title: 'Prioritas Jarak Nyata',
    icon: mdiMapMarkerDistance,
    description:
      'Hasil pencarian diprioritaskan berdasarkan radius terdekat dari pengguna agar bisnis sekitar lebih mudah ditemukan.',
    points: [
      'Radius terdekat',
      'Jarak aktual',
      'Peluang bisnis sekitar',
      'Relevansi lokasi',
    ],
  },
  {
    title: 'Katalog Produk Lengkap',
    icon: mdiPackageVariantClosed,
    description:
      'Pengguna bisa melihat produk, harga, stok real-time, promo, diskon, dan ketersediaan barang dari toko terdekat.',
    points: ['Harga', 'Stok real-time', 'Promo', 'Diskon'],
  },
  {
    title: 'Direktori Jasa Terverifikasi',
    icon: mdiShieldCheckOutline,
    description:
      'GeoSeek mendukung pencarian tukang, servis AC, bengkel, dokter, notaris, guru privat, dan layanan lain dengan data yang jelas.',
    points: ['Harga jasa', 'Jadwal', 'Rating', 'Status tersedia'],
  },
  {
    title: 'Cakupan Sampai RT/RW',
    icon: mdiCrosshairsGps,
    description:
      'Pencarian dapat diarahkan sampai tingkat RT, RW, dusun, desa, kelurahan, dan kecamatan untuk menemukan usaha rumahan.',
    points: ['RT/RW', 'Dusun/desa', 'Kelurahan', 'Kecamatan'],
  },
  {
    title: 'Transaksi dalam Satu Platform',
    icon: mdiCash,
    description:
      'GeoSeek dapat menggabungkan marketplace lokal, QRIS, transfer bank, e-wallet, booking, reservasi, kurir, dan pengiriman.',
    points: ['Marketplace', 'QRIS', 'Booking', 'Kurir lokal'],
  },
  {
    title: 'Dashboard Bisnis Lokal',
    icon: mdiChartTimelineVariant,
    description:
      'Pelaku usaha dapat memantau pencarian, klik, panggilan, kunjungan, serta tren produk dan jasa untuk mengambil keputusan.',
    points: [
      'Jumlah pencarian',
      'Klik & panggilan',
      'Kunjungan',
      'Tren produk/jasa',
    ],
  },
];

const comparisonMatrix = [
  {
    label: 'Fokus utama',
    maps: 'Peta, navigasi, dan profil bisnis',
    geoseek: 'Produk, jasa, UMKM, stok, booking, dan transaksi lokal',
  },
  {
    label: 'Prioritas hasil',
    maps: 'Relevansi umum dan popularitas lokasi',
    geoseek: 'Radius terdekat, jarak aktual, ketersediaan, dan GeoScore',
  },
  {
    label: 'Level wilayah',
    maps: 'Kota, jalan, dan titik tempat',
    geoseek: 'RT/RW, dusun/desa, kelurahan, kecamatan, sampai usaha rumahan',
  },
  {
    label: 'Aksi pengguna',
    maps: 'Lihat rute, telepon, dan info tempat',
    geoseek:
      'Cari barang/jasa, cek stok, booking, bayar, panggil kurir, dan pantau transaksi',
  },
];

const ecosystemSteps = [
  {
    title: '1. Cari kebutuhan sekitar',
    icon: mdiMagnify,
    description:
      'Pengguna memasukkan kata kunci produk, jasa, UMKM, atau kebutuhan harian lalu memilih radius lingkungan mikro.',
    tags: ['Produk lokal', 'Jasa lokal', 'RT/RW', 'Radius nyata'],
  },
  {
    title: '2. Bandingkan hasil live',
    icon: mdiMapSearchOutline,
    description:
      'GeoSeek menampilkan jarak aktual, GeoScore, harga, stok, jadwal, rating, status buka, dan status tersedia.',
    tags: ['GeoScore', 'Harga', 'Stok real-time', 'Jadwal'],
  },
  {
    title: '3. Lanjut transaksi lokal',
    icon: mdiCash,
    description:
      'Pengguna bisa menghubungi WhatsApp, booking layanan, reservasi, bayar via QRIS/e-wallet, atau panggil kurir lokal.',
    tags: ['WhatsApp', 'QRIS', 'Booking', 'Kurir lokal'],
  },
  {
    title: '4. Usaha dapat insight',
    icon: mdiChartTimelineVariant,
    description:
      'Pelaku usaha memantau pencarian, klik, panggilan, kunjungan, tren produk/jasa, dan peluang permintaan sekitar.',
    tags: ['Pencarian', 'Klik & panggilan', 'Kunjungan', 'Tren'],
  },
];

const dashboardMetrics = [
  { metric: 'Search', label: 'kata kunci dan jumlah pencarian lingkungan' },
  { metric: 'Click', label: 'klik profil, WhatsApp, rute, dan katalog' },
  { metric: 'Visit', label: 'kunjungan dari radius terdekat' },
  { metric: 'Trend', label: 'produk/jasa yang sedang naik' },
];

const smartInputOptions = [
  {
    id: 'traffic',
    label: 'Laporan Jalan',
    title:
      'Macet, kecelakaan, polisi, jalan rusak, banjir, atau penutupan jalan',
    outputTitle: 'Draft laporan jalan',
    placeholder:
      'Contoh: Jalan Ahmad Yani macet karena truk mogok, lajur kiri tertutup, arah pusat kota padat.',
    tags: [
      'Deteksi lokasi',
      'Kategori otomatis',
      'Validasi warga',
      'Update rute',
    ],
  },
  {
    id: 'business',
    label: 'Data UMKM',
    title: 'Input toko, warung, bengkel, jasa rumahan, atau usaha lingkungan',
    outputTitle: 'Draft profil usaha',
    placeholder:
      'Contoh: Warung Bu Sari jual beras 5 kg, telur, minyak, buka 06.00-21.00, bisa QRIS dan antar sekitar RT.',
    tags: ['Profil otomatis', 'Jam buka', 'Radius layanan', 'Kontak cepat'],
  },
  {
    id: 'stock',
    label: 'Stok & Promo',
    title:
      'Update harga, stok real-time, diskon, produk ready, atau barang habis',
    outputTitle: 'Draft update stok',
    placeholder:
      'Contoh: Stok gas 3 kg tersedia 20 tabung, harga Rp22.000, promo air galon beli 2 gratis ongkir radius 2 km.',
    tags: ['Harga', 'Stok real-time', 'Promo', 'Notifikasi pembeli'],
  },
  {
    id: 'service',
    label: 'Jasa & Booking',
    title:
      'Input jadwal tukang, servis AC, bengkel, dokter, guru privat, atau reservasi',
    outputTitle: 'Draft layanan jasa',
    placeholder:
      'Contoh: Servis AC tersedia hari ini jam 15.00-18.00, estimasi mulai Rp75.000, teknisi bersertifikat, area 5 km.',
    tags: ['Jadwal', 'Harga jasa', 'Booking online', 'Status tersedia'],
  },
];

const automationInputFeatures = [
  {
    title: 'Input Cepat Anti Ribet',
    icon: mdiRobotHappyOutline,
    description:
      'Pengguna atau pelaku usaha cukup menulis laporan singkat. GeoSeek mengubahnya menjadi data terstruktur yang siap dicari.',
    points: ['Teks bebas', 'Template cepat', 'Auto kategori', 'Auto radius'],
  },
  {
    title: 'Auto Update Stok & Status',
    icon: mdiPackageVariantClosed,
    description:
      'Stok produk, promo, jam buka, dan status layanan dapat diperbarui cepat agar hasil pencarian selalu relevan.',
    points: ['Ready stock', 'Barang habis', 'Promo aktif', 'Buka/tutup'],
  },
  {
    title: 'Laporan Jalan Sekali Tap',
    icon: mdiNavigationVariantOutline,
    description:
      'Seperti kekuatan laporan komunitas, tetapi diperluas untuk rute, hambatan, bisnis, produk, dan jasa sekitar.',
    points: ['Macet', 'Kecelakaan', 'Banjir', 'Jalan ditutup'],
  },
  {
    title: 'Validasi Komunitas + Skor',
    icon: mdiShieldCheckOutline,
    description:
      'Input bisa diberi sinyal kepercayaan dari pengguna sekitar, rating, aktivitas terbaru, dan histori interaksi.',
    points: ['Verifikasi warga', 'Anti spam', 'GeoScore', 'Riwayat update'],
  },
  {
    title: 'Booking, Order, dan Kurir Otomatis',
    icon: mdiCash,
    description:
      'Dari pencarian, pengguna dapat lanjut ke booking, pesanan, pembayaran digital, dan pengiriman lokal tanpa pindah aplikasi.',
    points: ['Booking', 'QRIS', 'E-wallet', 'Kurir lokal'],
  },
  {
    title: 'Notifikasi Peluang Lokal',
    icon: mdiTrendingUp,
    description:
      'GeoSeek dapat memberi insight otomatis untuk pemilik usaha ketika ada tren pencarian, produk laris, atau kebutuhan jasa naik.',
    points: ['Tren pencarian', 'Produk laris', 'Jasa dicari', 'Saran update'],
  },
];

const indexedLevels = [
  {
    level: 'Level 1',
    title: 'Web & Marketplace',
    icon: mdiTextSearch,
    items: ['Website', 'Blog', 'Portal berita', 'Marketplace'],
  },
  {
    level: 'Level 2',
    title: 'Media & Dokumen',
    icon: mdiLayersTripleOutline,
    items: ['Video', 'Gambar', 'Podcast', 'PDF'],
  },
  {
    level: 'Level 3',
    title: 'Hyperlocal Places',
    icon: mdiStorefrontOutline,
    items: [
      'UMKM',
      'Restoran',
      'Bengkel',
      'Klinik',
      'Kantor pemerintah/BUMN',
      'Sekolah',
      'Tempat ibadah',
      'Wisata',
    ],
  },
];

type KeywordChip = {
  label: string;
  query: string;
  score?: string;
  category?: string;
  radiusKm?: number;
};

type KeywordGroup = {
  title: string;
  description: string;
  keywords: KeywordChip[];
};

type PatternLevel = {
  level: string;
  formula: string;
  examples: KeywordChip[];
};

const topLocationKeywords: KeywordChip[] = [
  { label: 'Terdekat', query: 'terdekat', score: '10/10' },
  { label: 'Dekat Saya', query: 'dekat saya', score: '10/10' },
  { label: 'Near Me', query: 'near me', score: '10/10' },
  { label: 'Sekitar Saya', query: 'sekitar saya', score: '9.9/10' },
  { label: 'Lokasi Terdekat', query: 'lokasi terdekat', score: '9.9/10' },
  { label: 'Buka Sekarang', query: 'buka sekarang', score: '9.8/10' },
  { label: '24 Jam', query: '24 jam', score: '9.8/10' },
  { label: 'Di Kota Saya', query: 'di kota saya', score: '9.7/10' },
  { label: 'Di Kecamatan Saya', query: 'di kecamatan saya', score: '9.7/10' },
  {
    label: 'Dalam Radius 5 Km',
    query: 'dalam radius 5 km',
    score: '9.6/10',
    radiusKm: 5,
  },
];

const categoryKeywordGroups: KeywordGroup[] = [
  {
    title: 'Maps, Navigasi & Cuaca',
    description:
      'Intent maps, peta, navigasi, street view, peta Indonesia, dan keyword cuaca/BMKG yang diarahkan ke data lokasi publik.',
    keywords: [
      { label: 'Maps', query: 'maps' },
      { label: 'Google Maps', query: 'google maps' },
      { label: 'Maps Google', query: 'maps google' },
      { label: 'Peta', query: 'peta' },
      { label: 'Google Earth', query: 'google earth' },
      { label: 'Waze', query: 'waze' },
      { label: 'Street View', query: 'street view' },
      { label: 'Google Maps Satellite', query: 'google maps satellite' },
      { label: 'Peta Indonesia', query: 'peta indonesia', radiusKm: 100 },
      { label: 'Cuaca', query: 'cuaca' },
      { label: 'Cuaca Hari Ini', query: 'cuaca hari ini' },
      { label: 'Prakiraan Cuaca', query: 'prakiraan cuaca' },
      { label: 'BMKG', query: 'BMKG' },
      { label: 'Ramalan Cuaca', query: 'ramalan cuaca' },
      { label: 'Cuaca Esok Hari', query: 'cuaca esok hari' },
    ],
  },
  {
    title: 'Kuliner',
    description:
      'Intent makanan, restoran, cafe, warung makan, warteg, bakso, soto, seafood, dan catering.',
    keywords: [
      { label: 'Makanan terdekat', query: 'makanan terdekat' },
      { label: 'Restoran terdekat', query: 'restoran terdekat' },
      { label: 'Kuliner terdekat', query: 'kuliner terdekat' },
      { label: 'Rumah makan terdekat', query: 'rumah makan terdekat' },
      { label: 'Tempat makan terdekat', query: 'tempat makan terdekat' },
      { label: 'Cafe terdekat', query: 'cafe terdekat' },
      { label: 'Cafe aesthetic', query: 'cafe aesthetic' },
      { label: 'Tempat nongkrong', query: 'tempat nongkrong terdekat' },
      { label: 'Warung makan terdekat', query: 'warung makan terdekat' },
      { label: 'Warkop terdekat', query: 'warkop terdekat' },
      { label: 'Kedai kopi terdekat', query: 'kedai kopi terdekat' },
      { label: 'Warteg terdekat', query: 'warteg terdekat' },
      { label: 'Bakso terdekat', query: 'bakso terdekat' },
      { label: 'Soto terdekat', query: 'soto terdekat' },
      { label: 'Ayam goreng terdekat', query: 'ayam goreng terdekat' },
      { label: 'Seafood terdekat', query: 'seafood terdekat' },
      { label: 'Kuliner malam', query: 'kuliner malam' },
      { label: 'Cemilan unik', query: 'cemilan unik' },
      { label: 'Jajanan pasar modern', query: 'jajanan pasar modern' },
      { label: 'Makanan viral murah', query: 'makanan viral murah' },
      { label: 'Ide jualan makanan', query: 'ide jualan makanan' },
      { label: 'Makanan pedas', query: 'makanan pedas' },
      { label: 'Catering terdekat', query: 'catering terdekat' },
      { label: 'Katering sehat', query: 'katering sehat' },
      { label: 'Minuman terdekat', query: 'minuman terdekat' },
      { label: 'Minuman kekinian', query: 'minuman kekinian' },
      { label: 'Es kopi susu', query: 'es kopi susu' },
      { label: 'Boba drink', query: 'boba drink' },
      { label: 'Resep minuman segar', query: 'resep minuman segar' },
    ],
  },
  {
    title: 'Produk & Toko',
    description:
      'Intent penjual, toko, ready stock, elektronik, fashion, herbal, furniture, bayi, buku, perhiasan, dan kebutuhan kantor.',
    keywords: [
      { label: 'Smartphone terdekat', query: 'penjual smartphone terdekat' },
      { label: 'Laptop terdekat', query: 'penjual laptop terdekat' },
      { label: 'Elektronik terdekat', query: 'toko elektronik terdekat' },
      { label: 'Fashion terdekat', query: 'toko fashion terdekat' },
      { label: 'Sepatu terdekat', query: 'toko sepatu terdekat' },
      { label: 'Tas terdekat', query: 'toko tas terdekat' },
      { label: 'Kosmetik terdekat', query: 'toko kosmetik terdekat' },
      { label: 'Skincare terdekat', query: 'toko skincare terdekat' },
      { label: 'Herbal terdekat', query: 'toko herbal terdekat' },
      { label: 'Obat terdekat', query: 'toko obat terdekat' },
      { label: 'Indomaret terdekat', query: 'indomaret terdekat' },
      { label: 'Alfamart terdekat', query: 'alfamart terdekat' },
      { label: 'Supermarket terdekat', query: 'supermarket terdekat' },
      { label: 'Pusat perbelanjaan', query: 'pusat perbelanjaan terdekat' },
      { label: 'Toko baju terdekat', query: 'toko baju terdekat' },
      { label: 'Furniture terdekat', query: 'toko furniture terdekat' },
      {
        label: 'Peralatan rumah tangga',
        query: 'peralatan rumah tangga terdekat',
      },
      { label: 'Peralatan dapur', query: 'peralatan dapur terdekat' },
      { label: 'Perlengkapan bayi', query: 'perlengkapan bayi terdekat' },
      { label: 'Mainan anak', query: 'mainan anak terdekat' },
      { label: 'Buku terdekat', query: 'toko buku terdekat' },
      { label: 'Kebutuhan kantor', query: 'kebutuhan kantor terdekat' },
      { label: 'Perhiasan terdekat', query: 'toko perhiasan terdekat' },
      { label: 'Jam tangan terdekat', query: 'toko jam tangan terdekat' },
      { label: 'Aksesoris terdekat', query: 'toko aksesoris terdekat' },
    ],
  },
  {
    title: 'Bangunan & Otomotif',
    description:
      'Intent toko bahan bangunan, renovasi, servis AC, bengkel, sparepart, dealer, tambal ban, dan cuci mobil.',
    keywords: [
      { label: 'Toko bahan bangunan', query: 'toko bahan bangunan terdekat' },
      { label: 'Servis AC terdekat', query: 'servis ac terdekat' },
      { label: 'Tukang bangunan', query: 'tukang bangunan terdekat' },
      { label: 'Renovasi rumah', query: 'renovasi rumah terdekat' },
      { label: 'Jasa kebersihan', query: 'jasa kebersihan terdekat' },
      { label: 'Bengkel motor', query: 'bengkel motor terdekat' },
      { label: 'Bengkel mobil', query: 'bengkel mobil terdekat' },
      { label: 'Sparepart motor', query: 'sparepart motor terdekat' },
      { label: 'Sparepart mobil', query: 'sparepart mobil terdekat' },
      { label: 'Dealer motor', query: 'dealer motor terdekat' },
      { label: 'Tambal ban', query: 'tambal ban terdekat' },
      { label: 'Cuci mobil', query: 'cuci mobil terdekat' },
      { label: 'SPBU terdekat', query: 'SPBU terdekat' },
      { label: 'Pom bensin', query: 'pom bensin terdekat' },
      { label: 'Pertamini', query: 'pertamini terdekat' },
    ],
  },
  {
    title: 'Kesehatan & Hewan',
    description:
      'Intent rumah sakit, klinik, apotek, dokter, laboratorium, alat kesehatan, pet shop, klinik hewan, dan grooming.',
    keywords: [
      { label: 'Rumah sakit terdekat', query: 'rumah sakit terdekat' },
      { label: 'Klinik terdekat', query: 'klinik terdekat' },
      { label: 'Apotek terdekat', query: 'apotek terdekat' },
      { label: 'Apotek 24 jam', query: 'apotek 24 jam terdekat' },
      { label: 'Puskesmas terdekat', query: 'puskesmas terdekat' },
      { label: 'Dokter terdekat', query: 'dokter terdekat' },
      { label: 'Dokter gigi', query: 'dokter gigi terdekat' },
      { label: 'Bidan terdekat', query: 'bidan terdekat' },
      { label: 'Laboratorium', query: 'laboratorium terdekat' },
      { label: 'Alat kesehatan', query: 'alat kesehatan terdekat' },
      { label: 'Pet shop', query: 'pet shop terdekat' },
      { label: 'Klinik hewan', query: 'klinik hewan terdekat' },
      { label: 'Grooming hewan', query: 'grooming hewan terdekat' },
    ],
  },
  {
    title: 'Properti',
    description:
      'Intent properti, rumah dijual, tanah dijual, ruko, apartemen, kost, dan kontrakan.',
    keywords: [
      { label: 'Properti terdekat', query: 'properti terdekat' },
      { label: 'Rumah dijual', query: 'rumah dijual terdekat' },
      { label: 'Tanah dijual', query: 'tanah dijual terdekat' },
      { label: 'Ruko terdekat', query: 'ruko terdekat' },
      { label: 'Apartemen terdekat', query: 'apartemen terdekat' },
      { label: 'Kost terdekat', query: 'kost terdekat' },
      { label: 'Kontrakan terdekat', query: 'kontrakan terdekat' },
    ],
  },
  {
    title: 'Jasa Profesional & Digital',
    description:
      'Intent notaris, pengacara, guru privat, digital marketing, website, aplikasi, desain, foto/video, pajak, dan konsultan.',
    keywords: [
      { label: 'Notaris terdekat', query: 'notaris terdekat' },
      { label: 'Pengacara terdekat', query: 'pengacara terdekat' },
      { label: 'Guru privat', query: 'guru privat terdekat' },
      { label: 'Les privat', query: 'les privat terdekat' },
      { label: 'Digital marketing', query: 'digital marketing terdekat' },
      { label: 'SEO terdekat', query: 'jasa seo terdekat' },
      { label: 'Pembuatan website', query: 'pembuatan website terdekat' },
      { label: 'Pembuatan aplikasi', query: 'pembuatan aplikasi terdekat' },
      { label: 'Desain grafis', query: 'desain grafis terdekat' },
      { label: 'Fotografer', query: 'fotografer terdekat' },
      { label: 'Videografer', query: 'videografer terdekat' },
      { label: 'Wedding organizer', query: 'wedding organizer terdekat' },
      { label: 'Event organizer', query: 'event organizer terdekat' },
      { label: 'Jasa pajak', query: 'jasa pajak terdekat' },
      { label: 'Konsultan bisnis', query: 'konsultan bisnis terdekat' },
      { label: 'Konsultan hukum', query: 'konsultan hukum terdekat' },
      { label: 'Konsultan keuangan', query: 'konsultan keuangan terdekat' },
      { label: 'Percetakan', query: 'percetakan terdekat' },
      { label: 'Konveksi', query: 'konveksi terdekat' },
    ],
  },
  {
    title: 'Pertanian & Peternakan',
    description:
      'Intent pupuk, bibit tanaman, pestisida, alat pertanian, peternakan, dan pakan ternak.',
    keywords: [
      { label: 'Pupuk terdekat', query: 'pupuk terdekat' },
      { label: 'Bibit tanaman', query: 'bibit tanaman terdekat' },
      { label: 'Pestisida terdekat', query: 'pestisida terdekat' },
      { label: 'Alat pertanian', query: 'alat pertanian terdekat' },
      { label: 'Peternakan', query: 'peternakan terdekat' },
      { label: 'Pakan ternak', query: 'pakan ternak terdekat' },
    ],
  },
  {
    title: 'Keuangan',
    description: 'Intent bank, ATM, koperasi, pegadaian, pembayaran, dan QRIS.',
    keywords: [
      { label: 'Bank terdekat', query: 'bank terdekat' },
      { label: 'ATM terdekat', query: 'ATM terdekat' },
      { label: 'ATM BCA', query: 'atm bca terdekat' },
      { label: 'ATM BRI', query: 'atm bri terdekat' },
      { label: 'ATM Mandiri', query: 'atm mandiri terdekat' },
      { label: 'ATM BNI', query: 'atm bni terdekat' },
      { label: 'Koperasi terdekat', query: 'koperasi terdekat' },
      { label: 'Pegadaian terdekat', query: 'pegadaian terdekat' },
    ],
  },
  {
    title: 'Travel & Logistik',
    description:
      'Intent rental mobil/motor, travel, agen travel, kurir, logistik, ekspedisi, dan pengiriman barang.',
    keywords: [
      { label: 'Rental mobil', query: 'rental mobil terdekat' },
      { label: 'Rental motor', query: 'rental motor terdekat' },
      { label: 'Travel terdekat', query: 'travel terdekat' },
      { label: 'Agen travel', query: 'agen travel terdekat' },
      { label: 'Kurir terdekat', query: 'kurir terdekat' },
      { label: 'Logistik terdekat', query: 'logistik terdekat' },
      { label: 'Ekspedisi terdekat', query: 'ekspedisi terdekat' },
      { label: 'Pengiriman barang', query: 'pengiriman barang terdekat' },
    ],
  },
  {
    title: 'Kecantikan',
    description: 'Intent salon, barbershop, skincare, kosmetik, dan beauty care.',
    keywords: [
      { label: 'Salon terdekat', query: 'salon terdekat' },
      { label: 'Barbershop terdekat', query: 'barbershop terdekat' },
      { label: 'Pangkas rambut', query: 'pangkas rambut terdekat' },
      { label: 'Spa terdekat', query: 'spa terdekat' },
      { label: 'Pijat terdekat', query: 'pijat terdekat' },
      { label: 'Skincare terdekat', query: 'skincare terdekat' },
      { label: 'Kosmetik terdekat', query: 'kosmetik terdekat' },
    ],
  },
  {
    title: 'Komputer & Internet',
    description:
      'Intent service laptop, service printer, komputer, CCTV, internet, wifi, dan toko IT.',
    keywords: [
      { label: 'Service laptop', query: 'service laptop terdekat' },
      { label: 'Service printer', query: 'service printer terdekat' },
      { label: 'Komputer terdekat', query: 'komputer terdekat' },
      { label: 'CCTV terdekat', query: 'cctv terdekat' },
      { label: 'Internet terdekat', query: 'internet terdekat' },
      { label: 'Wifi terdekat', query: 'wifi terdekat' },
    ],
  },
  {
    title: 'Kerja, Event & UMKM',
    description:
      'Intent lowongan kerja, freelance, magang, seminar, festival, bazar, UMKM, toko kelontong, dan home industry.',
    keywords: [
      { label: 'Lowongan kerja', query: 'lowongan kerja terdekat' },
      { label: 'Freelance', query: 'freelance terdekat' },
      { label: 'Magang', query: 'magang terdekat' },
      { label: 'Seminar', query: 'seminar terdekat' },
      { label: 'Festival', query: 'festival terdekat' },
      { label: 'Bazar', query: 'bazar terdekat' },
      { label: 'UMKM terdekat', query: 'umkm terdekat' },
      { label: 'Toko kelontong', query: 'toko kelontong terdekat' },
      { label: 'Home industry', query: 'home industry terdekat' },
    ],
  },
  {
    title: 'Wisata & Penginapan',
    description: 'Intent tempat wisata, hotel, penginapan, villa, dan pantai.',
    keywords: [
      { label: 'Tempat wisata', query: 'tempat wisata terdekat' },
      { label: 'Wisata alam', query: 'wisata alam terdekat' },
      { label: 'Taman terdekat', query: 'taman terdekat' },
      { label: 'Alun-alun', query: 'alun alun terdekat' },
      { label: 'Museum terdekat', query: 'museum terdekat' },
      { label: 'Kebun binatang', query: 'kebun binatang terdekat' },
      { label: 'Hotel terdekat', query: 'hotel terdekat' },
      { label: 'Penginapan terdekat', query: 'penginapan terdekat' },
      { label: 'Villa terdekat', query: 'villa terdekat' },
      { label: 'Homestay terdekat', query: 'homestay terdekat' },
      { label: 'Pantai terdekat', query: 'pantai terdekat' },
    ],
  },
  {
    title: 'Ibadah, Pendidikan & Transportasi',
    description:
      'Intent masjid, mushola, gereja, pura, vihara, sekolah, kampus, tempat les, stasiun, halte, terminal, dan bandara.',
    keywords: [
      { label: 'Masjid terdekat', query: 'masjid terdekat' },
      { label: 'Mushola terdekat', query: 'mushola terdekat' },
      { label: 'Gereja terdekat', query: 'gereja terdekat' },
      { label: 'Pura terdekat', query: 'pura terdekat' },
      { label: 'Vihara terdekat', query: 'vihara terdekat' },
      { label: 'Sekolah terdekat', query: 'sekolah terdekat' },
      { label: 'SD terdekat', query: 'sd terdekat' },
      { label: 'SMP terdekat', query: 'smp terdekat' },
      { label: 'SMA terdekat', query: 'sma terdekat' },
      { label: 'Kampus terdekat', query: 'kampus terdekat' },
      { label: 'Universitas terdekat', query: 'universitas terdekat' },
      { label: 'Pesantren terdekat', query: 'pesantren terdekat' },
      { label: 'LPK terdekat', query: 'lpk terdekat' },
      { label: 'Tempat les', query: 'tempat les terdekat' },
      { label: 'Stasiun terdekat', query: 'stasiun terdekat' },
      { label: 'Stasiun kereta', query: 'stasiun kereta terdekat' },
      { label: 'Halte terdekat', query: 'halte terdekat' },
      { label: 'Halte busway', query: 'halte busway terdekat' },
      { label: 'Terminal terdekat', query: 'terminal terdekat' },
      { label: 'Bandara', query: 'bandara terdekat' },
    ],
  },
  {
    title: 'Olahraga & Rekreasi Harian',
    description:
      'Intent gym, tempat fitness, kolam renang, lapangan futsal, taman, dan aktivitas rekreasi sekitar.',
    keywords: [
      { label: 'Gym terdekat', query: 'gym terdekat' },
      { label: 'Tempat fitness', query: 'tempat fitness terdekat' },
      { label: 'Kolam renang', query: 'kolam renang terdekat' },
      { label: 'Lapangan futsal', query: 'lapangan futsal terdekat' },
      { label: 'Taman terdekat', query: 'taman terdekat' },
    ],
  },
  {
    title: 'Pemerintahan & BUMN',
    description:
      'Intent kantor layanan publik, instansi pemerintah, kecamatan, Samsat, dan BUMN/BUMD.',
    keywords: [
      { label: 'Kantor BPN terdekat', query: 'kantor bpn terdekat' },
      { label: 'Kantor Camat terdekat', query: 'kantor camat terdekat' },
      { label: 'Samsat terdekat', query: 'samsat terdekat' },
      { label: 'Dukcapil terdekat', query: 'dukcapil terdekat' },
      { label: 'Kantor pajak terdekat', query: 'kantor pajak terdekat' },
      { label: 'Kantor PLN terdekat', query: 'kantor pln terdekat' },
      { label: 'Kantor pos terdekat', query: 'kantor pos terdekat' },
      { label: 'Kantor BPJS terdekat', query: 'kantor bpjs terdekat' },
    ],
  },
];

const requiredLocationKeywords: KeywordChip[] = [
  { label: 'Terdekat', query: 'terdekat' },
  { label: 'Dekat Saya', query: 'dekat saya' },
  { label: 'Near Me', query: 'near me' },
  { label: 'Sekitar Saya', query: 'sekitar saya' },
  { label: 'Lokasi Terdekat', query: 'lokasi terdekat' },
  { label: 'Alamat Penjual', query: 'alamat penjual terdekat' },
  { label: 'Lokasi Penjual', query: 'lokasi penjual terdekat' },
  { label: 'Buka Sekarang', query: 'buka sekarang' },
  { label: '24 Jam', query: '24 jam' },
  { label: 'Murah', query: 'murah terdekat' },
  { label: 'Terbaik', query: 'terbaik terdekat' },
  { label: 'Terlaris', query: 'terlaris terdekat' },
  { label: 'Terpopuler', query: 'terpopuler terdekat' },
  { label: 'Rating Tertinggi', query: 'rating tertinggi' },
  { label: 'Promo', query: 'promo terdekat' },
  { label: 'Diskon', query: 'diskon terdekat' },
  { label: 'Ready Stock', query: 'ready stock terdekat' },
  { label: 'Tersedia', query: 'tersedia terdekat' },
  { label: 'Terverifikasi', query: 'terverifikasi terdekat' },
  { label: 'Radius 1 Km', query: 'dalam radius 1 km', radiusKm: 1 },
  { label: 'Radius 5 Km', query: 'dalam radius 5 km', radiusKm: 5 },
  { label: 'Radius 10 Km', query: 'dalam radius 10 km', radiusKm: 10 },
  { label: 'RT/RW', query: 'sekitar rt rw' },
  { label: 'Dusun', query: 'sekitar dusun' },
  { label: 'Desa', query: 'sekitar desa' },
  { label: 'Kelurahan', query: 'sekitar kelurahan' },
  { label: 'Kecamatan', query: 'sekitar kecamatan' },
  { label: 'Kabupaten', query: 'sekitar kabupaten' },
  { label: 'Kota', query: 'sekitar kota' },
  { label: 'Provinsi', query: 'sekitar provinsi' },
  { label: 'Beli', query: 'beli terdekat' },
  { label: 'Pesan', query: 'pesan terdekat' },
  { label: 'Booking', query: 'booking terdekat' },
  { label: 'Reservasi', query: 'reservasi terdekat' },
  { label: 'Order', query: 'order terdekat' },
  { label: 'Antar', query: 'antar terdekat' },
  { label: 'Kirim', query: 'kirim terdekat' },
  { label: 'COD', query: 'cod terdekat' },
  { label: 'QRIS', query: 'qris terdekat' },
  { label: 'E-Wallet', query: 'e-wallet terdekat' },
  { label: 'Cashback', query: 'cashback terdekat' },
  { label: 'Gratis Ongkir', query: 'gratis ongkir terdekat' },
  { label: 'Same Day', query: 'same day terdekat' },
  { label: 'Instant', query: 'instant terdekat' },
];

const topTrafficKeywords: KeywordChip[] = [
  { label: 'Makanan Terdekat', query: 'makanan terdekat' },
  { label: 'Warteg Terdekat', query: 'warteg terdekat' },
  { label: 'Restoran Terdekat', query: 'restoran terdekat' },
  { label: 'Cafe Terdekat', query: 'cafe terdekat' },
  { label: 'Apotek Terdekat', query: 'apotek terdekat' },
  { label: 'Rumah Sakit Terdekat', query: 'rumah sakit terdekat' },
  { label: 'Bengkel Terdekat', query: 'bengkel terdekat' },
  { label: 'Hotel Terdekat', query: 'hotel terdekat' },
  { label: 'ATM Terdekat', query: 'ATM terdekat' },
  { label: 'SPBU Terdekat', query: 'SPBU terdekat' },
  { label: 'Toko Terdekat', query: 'toko terdekat' },
  { label: 'Toko Bahan Bangunan', query: 'toko bahan bangunan terdekat' },
  { label: 'Laundry Terdekat', query: 'laundry terdekat' },
  { label: 'Servis AC Terdekat', query: 'servis ac terdekat' },
  { label: 'Service Laptop', query: 'service laptop terdekat' },
  { label: 'Dokter Terdekat', query: 'dokter terdekat' },
  { label: 'Kost Terdekat', query: 'kost terdekat' },
  { label: 'Rumah Dijual', query: 'rumah dijual terdekat' },
  { label: 'Lowongan Kerja', query: 'lowongan kerja terdekat' },
  { label: 'Pupuk Terdekat', query: 'pupuk terdekat' },
  { label: 'Rental Mobil', query: 'rental mobil terdekat' },
  { label: 'Kurir Terdekat', query: 'kurir terdekat' },
  { label: 'Jasa Terdekat', query: 'jasa terdekat' },
  { label: 'Wifi Terdekat', query: 'wifi terdekat' },
  { label: 'Kantor BPN Terdekat', query: 'kantor bpn terdekat' },
  { label: 'Kantor Camat Terdekat', query: 'kantor camat terdekat' },
  { label: 'Samsat Terdekat', query: 'samsat terdekat' },
  { label: 'Kantor PLN Terdekat', query: 'kantor pln terdekat' },
];

const hyperlocalPatternLevels: PatternLevel[] = [
  {
    level: 'Level 1',
    formula: '[Jenis usaha] + Terdekat',
    examples: [
      { label: 'Hotel terdekat', query: 'hotel terdekat' },
      { label: 'ATM terdekat', query: 'ATM terdekat' },
      { label: 'Kantor BPN terdekat', query: 'kantor bpn terdekat' },
      { label: 'Samsat terdekat', query: 'samsat terdekat' },
      {
        label: 'Bengkel terdekat',
        query: 'bengkel terdekat',
        category: 'bengkel-mobil',
      },
    ],
  },
  {
    level: 'Level 2',
    formula: '[Jenis usaha] + Dekat Saya',
    examples: [
      {
        label: 'Restoran dekat saya',
        query: 'restoran dekat saya',
        category: 'cafe-melayu',
      },
      {
        label: 'Apotek dekat saya',
        query: 'apotek dekat saya',
        category: 'toko-herbal-kesehatan',
      },
      { label: 'Kantor camat dekat saya', query: 'kantor camat dekat saya' },
      { label: 'Kantor PLN dekat saya', query: 'kantor pln dekat saya' },
    ],
  },
  {
    level: 'Level 3',
    formula: '[Jenis usaha] + Kecamatan',
    examples: [
      {
        label: 'Klinik Cibinong',
        query: 'klinik Cibinong',
        category: 'toko-herbal-kesehatan',
      },
      {
        label: 'Bengkel Citeureup',
        query: 'bengkel Citeureup',
        category: 'bengkel-mobil',
      },
      { label: 'Samsat Cibinong', query: 'samsat Cibinong' },
      { label: 'Kantor BPN Bogor', query: 'kantor bpn Bogor' },
    ],
  },
  {
    level: 'Level 4',
    formula: '[Jenis usaha] + Kota',
    examples: [
      { label: 'Hotel Bogor', query: 'hotel Bogor' },
      { label: 'Wisata Bandung', query: 'wisata Bandung' },
    ],
  },
  {
    level: 'Level 5',
    formula: '[Jenis usaha] + Provinsi',
    examples: [
      { label: 'Wisata Jawa Barat', query: 'wisata Jawa Barat' },
      { label: 'Hotel Bali', query: 'hotel Bali' },
    ],
  },
];

const totalKeywordChips =
  topLocationKeywords.length +
  requiredLocationKeywords.length +
  topTrafficKeywords.length +
  categoryKeywordGroups.reduce(
    (total, group) => total + group.keywords.length,
    0,
  ) +
  hyperlocalPatternLevels.reduce(
    (total, pattern) => total + pattern.examples.length,
    0,
  );

const formatRupiah = (value?: number | null) => {
  if (!value) return 'Tanya harga';
  return new Intl.NumberFormat('id-ID', {
    style: 'currency',
    currency: 'IDR',
    maximumFractionDigits: 0,
  }).format(value);
};

const formatRadius = (value: number) =>
  value >= GLOBAL_RADIUS_KM ? '500+ km' : `${value} km`;

const stockColor = (status: string) => {
  if (status === 'in_stock') return 'bg-[#E8F6F1] text-[#087F6D]';
  if (status === 'limited') return 'bg-[#FFF3D7] text-[#9A6500]';
  if (status === 'out_of_stock') return 'bg-[#FFE7E0] text-[#A23A24]';
  return 'bg-[#F7F2E8] text-[#5D6B62]';
};

const scoreLabels: Record<keyof GeoScoreBreakdown, string> = {
  relevance: 'Relevansi kata kunci',
  distance: 'Jarak',
  reputation: 'Rating/reputasi',
  activity: 'Aktivitas terbaru',
  interaction: 'Interaksi pengguna',
};

export default function Starter() {
  const [query, setQuery] = useState('');
  const [radiusKm, setRadiusKm] = useState(DEFAULT_RADIUS_KM);
  const [places, setPlaces] = useState<PublicPlace[]>([]);
  const [searchMeta, setSearchMeta] = useState<SearchMeta>({
    count: 0,
    radius_km: DEFAULT_RADIUS_KM,
    radius_zone: fallbackRadiusZones[1],
    radius_zones: fallbackRadiusZones,
    distance_buckets: [],
    filtered_by_radius: true,
    total_candidates: 0,
    geo_score_formula: {
      relevance: 40,
      distance: 25,
      reputation: 15,
      activity: 10,
      interaction: 10,
    },
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [location, setLocation] = useState<LocationState | null>(null);
  const [locationReady, setLocationReady] = useState(false);
  const [locationStatus, setLocationStatus] = useState(
    'Mengambil lokasi Anda...',
  );
  const [smartInputType, setSmartInputType] = useState(smartInputOptions[0].id);
  const [smartInputText, setSmartInputText] = useState(
    smartInputOptions[0].placeholder,
  );
  const hasRequestedLocation = useRef(false);

  const radiusZones = searchMeta.radius_zones?.length
    ? searchMeta.radius_zones
    : fallbackRadiusZones;
  const selectedZone =
    searchMeta.radius_zone ||
    radiusZones.find((item) => item.value === radiusKm) ||
    fallbackRadiusZones[1];
  const featuredPlaces = places.slice(0, 3);
  const formulaEntries = Object.entries(searchMeta.geo_score_formula || {});
  const hasActiveLocation = locationReady && Boolean(location);
  const canUseKeywordLocation = canSearchWithKeywordOrigin(query);
  const canSubmitSearch = hasActiveLocation || canUseKeywordLocation;
  const activeSearchOrigin =
    location ||
    (searchMeta.search_origin
      ? {
          lat: searchMeta.search_origin.lat,
          lng: searchMeta.search_origin.lng,
          label: searchMeta.search_origin.label,
        }
      : null);
  const activeLocationLabel =
    activeSearchOrigin?.label || 'Belum aktif — izinkan lokasi browser';
  const openNow =
    searchMeta.trending?.live?.open_now ||
    places.filter((place) => place.live_status?.status === 'open').length;
  const selectedSmartInput =
    smartInputOptions.find((item) => item.id === smartInputType) ||
    smartInputOptions[0];
  const smartInputWords = smartInputText.trim().split(/\s+/).filter(Boolean);
  const smartInputSummary = smartInputWords.length
    ? `${selectedSmartInput.outputTitle}: ${smartInputWords.slice(0, 9).join(' ')}${smartInputWords.length > 9 ? '...' : ''}`
    : 'Isi input untuk membuat draft otomatis';

  const fetchPlaces = useCallback(
    async (
      nextQuery: string,
      nextLocation: LocationState | null,
      nextRadiusKm: number,
    ) => {
      setLoading(true);
      setError('');

      try {
        const params: {
          q: string;
          radiusKm: number;
          limit: number;
          lat?: number;
          lng?: number;
        } = {
          q: nextQuery,
          radiusKm: nextRadiusKm,
          limit: 30,
        };

        if (nextLocation) {
          params.lat = nextLocation.lat;
          params.lng = nextLocation.lng;
        }

        const response = await axios.get('/public/places', { params });
        const responseSearchOrigin = toSearchOrigin(response.data?.search_origin);

        if (!nextLocation && responseSearchOrigin) {
          setLocationStatus(`Lokasi dari kata kunci: ${responseSearchOrigin.label}`);
        }

        setPlaces(Array.isArray(response.data?.rows) ? response.data.rows : []);
        setSearchMeta({
          count: Number(response.data?.count || 0),
          radius_km: response.data?.radius_km,
          effective_radius_km: response.data?.effective_radius_km,
          radius_zone: response.data?.radius_zone || null,
          radius_zones: Array.isArray(response.data?.radius_zones)
            ? response.data.radius_zones
            : fallbackRadiusZones,
          distance_buckets: Array.isArray(response.data?.distance_buckets)
            ? response.data.distance_buckets
            : [],
          filtered_by_radius: Boolean(response.data?.filtered_by_radius),
          total_candidates: Number(response.data?.total_candidates || 0),
          geo_score_formula: response.data?.geo_score_formula || {
            relevance: 40,
            distance: 25,
            reputation: 15,
            activity: 10,
            interaction: 10,
          },
          trending: response.data?.trending,
          recommendation_engine: response.data?.recommendation_engine,
          expanded_for_nearest: Boolean(response.data?.expanded_for_nearest),
          external_sources: Array.isArray(response.data?.external_sources)
            ? response.data.external_sources
            : [],
          external_source_errors: Array.isArray(
            response.data?.external_source_errors,
          )
            ? response.data.external_source_errors
            : [],
          search_origin: responseSearchOrigin,
        });
      } catch (err) {
        console.error('Gagal memuat GeoSeek public search', err);
        setError(
          'Maaf, pencarian GeoSeek belum bisa dimuat. Coba ulang beberapa saat lagi.',
        );
      } finally {
        setLoading(false);
      }
    },
    [],
  );

  const requestCurrentLocation = useCallback(() => {
    setError('');

    if (typeof navigator === 'undefined' || !navigator.geolocation) {
      setLocation(null);
      setLocationReady(false);
      setPlaces([]);
      setLoading(false);
      setLocationStatus(
        'Browser tidak mendukung lokasi. Gunakan browser/perangkat yang mengizinkan akses lokasi.',
      );
      setError(LOCATION_REQUIRED_MESSAGE);
      return;
    }

    setLocation(null);
    setLocationReady(false);
    setPlaces([]);
    setLocationStatus('Mengambil lokasi Anda...');
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const nextLocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
          label: 'Lokasi saya',
        };
        setLocation(nextLocation);
        setLocationReady(true);
        setLocationStatus('Lokasi aktif: lokasi saya');
        setError('');
      },
      (geoError) => {
        console.error('Izin lokasi ditolak atau gagal', geoError);
        setLocation(null);
        setLocationReady(false);
        setPlaces([]);
        setLoading(false);
        setLocationStatus(
          'Lokasi belum aktif. Izinkan akses lokasi browser, lalu klik “Gunakan lokasi saya”.',
        );
        setError(LOCATION_REQUIRED_MESSAGE);
      },
      { enableHighAccuracy: true, timeout: 8000, maximumAge: 60000 },
    );
  }, []);

  useEffect(() => {
    if (hasRequestedLocation.current) {
      return;
    }

    hasRequestedLocation.current = true;
    requestCurrentLocation();
  }, [requestCurrentLocation]);

  useEffect(() => {
    if (!locationReady || !location) {
      return undefined;
    }

    const timeout = window.setTimeout(() => {
      fetchPlaces(query, location, radiusKm);
    }, 420);

    return () => window.clearTimeout(timeout);
  }, [query, radiusKm, location, locationReady, fetchPlaces]);

  const handleSearch = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!canSubmitSearch) {
      setError(LOCATION_REQUIRED_MESSAGE);
      setLocationStatus(
        'Lokasi belum aktif. Klik “Gunakan lokasi saya” atau ketik keyword local SEO/kota seperti “kuliner Jakarta”, “maps”, “SPBU terdekat”, atau “cuaca”.',
      );
      return;
    }

    await fetchPlaces(query, location, radiusKm);
  };

  const applyKeyword = (keyword: KeywordChip) => {
    setQuery(keyword.query);

    if (keyword.radiusKm) {
      setRadiusKm(keyword.radiusKm);
    }

    window.setTimeout(() => {
      document
        .getElementById('results')
        ?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 160);
  };

  const buildPlaceHref = (place: PublicPlace) => {
    if (place.external_source === 'openstreetmap' && place.google_maps_url) {
      return place.google_maps_url;
    }

    if (!activeSearchOrigin) {
      return '#search';
    }

    return `/tempat/${place.id}?lat=${activeSearchOrigin.lat}&lng=${activeSearchOrigin.lng}&radiusKm=${radiusKm}&q=${encodeURIComponent(query)}`;
  };

  const shouldOpenExternalPlace = (place: PublicPlace) =>
    place.external_source === 'openstreetmap' && Boolean(place.google_maps_url);

  return (
    <>
      <Head>
        <title>{getPageTitle('GeoSeek 2.0 Hyperlocal Search')}</title>
        <meta
          name='description'
          content='GeoSeek 2.0 adalah mesin pencari hyperlocal untuk menemukan tempat, UMKM, produk, stok, jasa, dan rekomendasi terdekat berbasis GeoScore.'
        />
      </Head>

      <main className='min-h-screen bg-[#F7F2E8] text-[#17231B]'>
        <section className='relative overflow-hidden bg-[#073B3A] text-white'>
          <div className='absolute inset-0 opacity-30'>
            <div className='absolute -left-24 top-16 h-72 w-72 rounded-full bg-[#F2A541] blur-3xl' />
            <div className='absolute right-0 top-0 h-96 w-96 rounded-full bg-[#2CA58D] blur-3xl' />
            <div className='absolute bottom-0 left-1/2 h-64 w-64 rounded-full bg-[#F26A4B] blur-3xl' />
          </div>

          <div className='relative mx-auto flex min-h-[760px] max-w-7xl flex-col px-6 py-6 lg:px-8'>
            <nav className='flex items-center justify-between rounded-full border border-white/15 bg-white/10 px-5 py-3 shadow-2xl shadow-black/10 backdrop-blur'>
              <Link
                href='/'
                className='flex items-center gap-3 font-black tracking-tight'
              >
                <span className='grid h-10 w-10 place-items-center rounded-full bg-[#F2A541] text-[#073B3A]'>
                  GS
                </span>
                <span>GeoSeek 2.0</span>
              </Link>
              <div className='hidden items-center gap-6 text-sm text-white/80 md:flex'>
                <a href='#search' className='hover:text-white'>
                  Live Search
                </a>
                <a href='#keywords' className='hover:text-white'>
                  Kata Kunci
                </a>
                <a href='#advantages' className='hover:text-white'>
                  Keunggulan
                </a>
                <a href='#comparison' className='hover:text-white'>
                  GeoSeek vs Maps
                </a>
                <a href='#automation' className='hover:text-white'>
                  Auto Input
                </a>
                <a href='#geoscore' className='hover:text-white'>
                  GeoScore
                </a>
                <a href='#trending' className='hover:text-white'>
                  Trending
                </a>
                <Link href='/login' className='hover:text-white'>
                  Admin / Login
                </Link>
              </div>
              <BaseButton
                href='/login'
                label='Admin'
                color='warning'
                roundedFull
                className='border-0 font-bold text-[#073B3A]'
              />
            </nav>

            <div className='grid flex-1 items-center gap-10 py-16 lg:grid-cols-[1.02fr_0.98fr]'>
              <div>
                <div className='mb-5 inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/10 px-4 py-2 text-sm text-white/85 backdrop-blur'>
                  <BaseIcon path={mdiRadar} size={18} />
                  Konten paling dekat • paling relevan • paling berguna saat ini
                </div>
                <h1 className='max-w-4xl text-5xl font-black leading-[0.95] tracking-tight md:text-7xl'>
                  Hyperlocal search ecosystem untuk UMKM, produk, stok, dan jasa
                  sekitar.
                </h1>
                <p className='mt-6 max-w-2xl text-lg leading-8 text-white/80 md:text-xl'>
                  GeoSeek tidak hanya mengurutkan berdasarkan jarak. Ranking
                  memakai GeoScore: relevansi kata kunci, jarak, reputasi,
                  aktivitas terbaru, dan interaksi pengguna.
                </p>

                <form
                  id='search'
                  onSubmit={handleSearch}
                  className='mt-8 rounded-[2rem] border border-white/15 bg-white p-3 text-[#17231B] shadow-2xl shadow-black/20'
                >
                  <div className='grid gap-3 lg:grid-cols-[1fr_auto]'>
                    <label className='relative block'>
                      <span className='sr-only'>Kata kunci pencarian</span>
                      <BaseIcon
                        path={mdiMagnify}
                        className='pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-[#6A7A70]'
                        size={22}
                      />
                      <input
                        value={query}
                        onChange={(event) => setQuery(event.target.value)}
                        placeholder='Cari “maps”, “cuaca”, “kuliner Jakarta”, “cafe aesthetic”, “SPBU terdekat”, “ATM BCA”, “stasiun terdekat”...'
                        className='h-14 w-full rounded-2xl border border-[#E0D6C3] bg-[#FCFAF5] pl-12 pr-4 text-sm outline-none transition focus:border-[#2CA58D] focus:ring-4 focus:ring-[#2CA58D]/15'
                      />
                    </label>
                    <button
                      type='submit'
                      disabled={!canSubmitSearch || loading}
                      className='h-14 rounded-2xl bg-[#F26A4B] px-7 font-black text-white shadow-lg shadow-[#F26A4B]/30 transition hover:bg-[#E85A39] focus:outline-none focus:ring-4 focus:ring-[#F26A4B]/30 disabled:cursor-not-allowed disabled:opacity-60'
                    >
                      Cari
                    </button>
                  </div>

                  <div className='mt-4 flex flex-col gap-3 px-2 pb-1 text-sm text-[#6A7A70] lg:flex-row lg:items-center lg:justify-between'>
                    <button
                      type='button'
                      onClick={requestCurrentLocation}
                      className='inline-flex items-center gap-2 font-semibold text-[#087F6D] hover:text-[#073B3A]'
                    >
                      <BaseIcon path={mdiCrosshairsGps} size={18} />
                      Gunakan lokasi saya
                    </button>
                    <span>
                      {locationStatus || 'Lokasi belum aktif'} • Kategori
                      dikosongkan •{' '}
                      {hasActiveLocation
                        ? 'Live search aktif'
                        : canUseKeywordLocation
                          ? 'Bisa cari dari keyword/kota'
                          : 'Menunggu izin lokasi'}
                    </span>
                  </div>

                  <div className='mt-4 flex flex-wrap gap-2 px-2 pb-2'>
                    {radiusZones.map((zone) => (
                      <button
                        type='button'
                        key={zone.value}
                        onClick={() => setRadiusKm(zone.value)}
                        className={`rounded-full px-4 py-2 text-xs font-black transition ${radiusKm === zone.value ? 'bg-[#073B3A] text-white' : 'bg-[#F7F2E8] text-[#5D6B62] hover:bg-[#E8F6F1]'}`}
                        title={zone.description || zone.range}
                      >
                        {zone.range} · {zone.label}
                      </button>
                    ))}
                  </div>
                </form>

                <div className='mt-6 inline-flex rounded-full border border-white/15 bg-white/10 px-4 py-2 text-sm font-bold text-white/80'>
                  Kategori pencarian dikosongkan otomatis — hasil ditentukan
                  dari kata kunci dan jarak. Jika lokasi browser belum aktif,
                  keyword local SEO/kota memakai titik awal dari backend.
                </div>
              </div>

              <div className='relative lg:self-end lg:mb-[102px]'>
                <div className='absolute -inset-4 rounded-[2.5rem] bg-gradient-to-br from-[#F2A541]/40 via-white/5 to-[#2CA58D]/30 blur-xl' />
                <div className='relative rounded-[2rem] border border-white/15 bg-[#FDF8EE] p-5 text-[#17231B] shadow-2xl'>
                  <div className='mb-4 flex items-center justify-between gap-4'>
                    <div>
                      <p className='text-xs font-black uppercase tracking-[0.25em] text-[#087F6D]'>
                        Live Nearby Map
                      </p>
                      <h2 className='text-2xl font-black'>
                        {selectedZone.label}
                      </h2>
                    </div>
                    <span className='rounded-full bg-[#073B3A] px-3 py-1 text-xs font-bold text-white'>
                      {activeLocationLabel}
                    </span>
                  </div>
                  <div className='relative h-80 overflow-hidden rounded-[1.6rem] bg-[#D9E7D8]'>
                    <div className='absolute inset-0 opacity-40 [background-image:linear-gradient(#ffffff_1px,transparent_1px),linear-gradient(90deg,#ffffff_1px,transparent_1px)] [background-size:38px_38px]' />
                    <div className='absolute left-1/2 top-1/2 h-60 w-60 -translate-x-1/2 -translate-y-1/2 rounded-full border border-[#087F6D]/15 bg-[#2CA58D]/5' />
                    <div className='absolute left-1/2 top-1/2 h-40 w-40 -translate-x-1/2 -translate-y-1/2 rounded-full border border-[#087F6D]/25 bg-[#2CA58D]/10' />
                    <div className='absolute left-1/2 top-1/2 h-24 w-24 -translate-x-1/2 -translate-y-1/2 rounded-full border border-[#087F6D]/35 bg-[#2CA58D]/10' />
                    <div className='absolute left-1/2 top-1/2 grid h-14 w-14 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full bg-[#073B3A] text-white shadow-xl'>
                      <BaseIcon path={mdiCrosshairsGps} size={26} />
                    </div>
                    {featuredPlaces.map((place, index) => (
                      <Link
                        key={place.id}
                        href={buildPlaceHref(place)}
                        target={
                          shouldOpenExternalPlace(place) ? '_blank' : undefined
                        }
                        rel={
                          shouldOpenExternalPlace(place)
                            ? 'noreferrer'
                            : undefined
                        }
                        className={`absolute rounded-2xl bg-white px-3 py-2 text-xs font-bold shadow-xl transition hover:-translate-y-1 ${index === 0 ? 'left-8 top-10' : index === 1 ? 'right-7 top-28' : 'bottom-10 left-20'}`}
                      >
                        <span className='block max-w-[140px] truncate'>
                          {place.name}
                        </span>
                        <span className='text-[#087F6D]'>
                          {place.distance_km !== null &&
                          place.distance_km !== undefined
                            ? `${place.distance_km} km`
                            : 'Lihat detail'}
                        </span>
                        <span className='block text-[#F26A4B]'>
                          GeoScore{' '}
                          {place.geo_score || place.search_score || '-'}
                        </span>
                      </Link>
                    ))}
                  </div>
                  <div className='mt-4 grid grid-cols-3 gap-3 text-center'>
                    <MetricCard
                      value={String(places.length)}
                      label='hasil tampil'
                    />
                    <MetricCard value={String(openNow)} label='buka sekarang' />
                    <MetricCard value='0' label='login' />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        <section id='results' className='mx-auto max-w-7xl px-6 py-12 lg:px-8'>
          <div className='mb-8 flex flex-col gap-4 md:flex-row md:items-end md:justify-between'>
            <div>
              <p className='text-sm font-black uppercase tracking-[0.25em] text-[#087F6D]'>
                Live Search Results
              </p>
              <h2 className='mt-2 text-4xl font-black tracking-tight'>
                Konten paling dekat, relevan, dan berguna.
              </h2>
              <p className='mt-3 max-w-3xl text-[#5D6B62]'>
                Lokasi:{' '}
                <strong>
                  {activeLocationLabel}
                </strong>
                . Radius aktif:{' '}
                <strong>
                  {selectedZone.range} · {selectedZone.label}
                </strong>
                . Ditemukan {searchMeta.count} hasil dari{' '}
                {searchMeta.total_candidates} kandidat terindeks.
                {searchMeta.expanded_for_nearest
                  ? ` Radius awal ${formatRadius(radiusKm)} belum memenuhi target minimal 10 hasil, jadi GeoSeek memperluas pencarian sampai ${formatRadius(searchMeta.effective_radius_km || radiusKm)} dan tetap mengurutkan berdasarkan jarak.`
                  : ''}
                {searchMeta.search_origin?.source === 'query_keyword'
                  ? ` Lokasi dipilih dari kata kunci: ${searchMeta.search_origin.label}.`
                  : ''}
                {searchMeta.search_origin?.source === 'default_local_keyword'
                  ? ` ${searchMeta.search_origin.note || 'Lokasi browser tidak aktif, GeoSeek memakai titik awal SEO lokal.'}`
                  : ''}
              </p>
            </div>
            <BaseButton
              href='/login'
              label='Kelola listing UMKM'
              color='info'
              roundedFull
              className='font-bold'
            />
          </div>

          {searchMeta.distance_buckets.length ? (
            <div className='mb-8 rounded-[2rem] bg-white p-5 shadow-sm'>
              <div className='mb-4 flex items-center gap-2 font-black'>
                <BaseIcon
                  path={mdiMapMarkerDistance}
                  size={22}
                  className='text-[#087F6D]'
                />{' '}
                Search by Distance
              </div>
              <div className='flex flex-wrap gap-2'>
                {searchMeta.distance_buckets.map((bucket) => (
                  <button
                    type='button'
                    key={`${bucket.radius_km}-${bucket.zone_label}`}
                    onClick={() => setRadiusKm(bucket.radius_km)}
                    className={`rounded-full px-4 py-2 text-xs font-black transition ${radiusKm === bucket.radius_km ? 'bg-[#073B3A] text-white' : 'bg-[#F7F2E8] text-[#5D6B62] hover:bg-[#E8F6F1]'}`}
                  >
                    {bucket.label} · {bucket.count} hasil
                  </button>
                ))}
              </div>
            </div>
          ) : null}

          {error ? (
            <div className='rounded-[2rem] border border-[#F26A4B]/30 bg-white p-8 text-[#A23A24]'>
              {error}
            </div>
          ) : null}

          {searchMeta.external_source_errors?.length ? (
            <div className='mb-6 rounded-[2rem] border border-[#F2A541]/40 bg-white p-5 text-sm font-bold text-[#9A6500]'>
              {searchMeta.external_source_errors.join(' ')}
            </div>
          ) : null}

          {loading ? (
            <div className='grid gap-5 md:grid-cols-3'>
              {[0, 1, 2].map((item) => (
                <div
                  key={item}
                  className='h-96 animate-pulse rounded-[2rem] bg-white/70'
                />
              ))}
            </div>
          ) : !activeSearchOrigin ? (
            <div className='rounded-[2rem] border border-dashed border-[#087F6D]/40 bg-white p-10 text-center'>
              <h3 className='text-2xl font-black'>Aktifkan Lokasi Saya dulu</h3>
              <p className='mx-auto mt-3 max-w-xl text-[#5D6B62]'>
                GeoSeek bisa memakai lokasi browser, kata kunci kota, atau
                titik awal SEO lokal untuk menampilkan hasil pencarian.
              </p>
              <div className='mt-6'>
                <button
                  type='button'
                  onClick={requestCurrentLocation}
                  className='rounded-full bg-[#073B3A] px-6 py-3 font-black text-white transition hover:bg-[#087F6D]'
                >
                  Gunakan lokasi saya
                </button>
              </div>
            </div>
          ) : places.length ? (
            <div className='grid gap-5 md:grid-cols-2 xl:grid-cols-3'>
              {places.map((place) => (
                <article
                  key={place.id}
                  className='group flex min-h-[460px] flex-col rounded-[2rem] border border-[#E8DEC9] bg-white p-5 shadow-sm transition hover:-translate-y-1 hover:shadow-2xl hover:shadow-[#073B3A]/10'
                >
                  <div className='flex items-start justify-between gap-4'>
                    <span
                      className='rounded-full px-3 py-1 text-xs font-black text-white'
                      style={{
                        backgroundColor: place.category?.color_hex || '#087F6D',
                      }}
                    >
                      {place.category?.name || 'Tempat'}
                    </span>
                    {place.is_verified ? (
                      <span className='inline-flex items-center gap-1 rounded-full bg-[#E8F6F1] px-3 py-1 text-xs font-bold text-[#087F6D]'>
                        <BaseIcon path={mdiShieldCheckOutline} size={14} />{' '}
                        Verified
                      </span>
                    ) : null}
                  </div>

                  <div className='mt-5 flex items-start justify-between gap-4'>
                    <div>
                      <h3 className='text-2xl font-black tracking-tight'>
                        {place.name}
                      </h3>
                      <p className='mt-2 text-xs font-bold uppercase tracking-wide text-[#087F6D]'>
                        {place.distance_km !== null &&
                        place.distance_km !== undefined
                          ? `Jarak ${place.distance_km} km dari lokasi saya`
                          : place.radius_zone?.label || selectedZone.label}
                      </p>
                    </div>
                    <div className='text-right'>
                      <p className='text-xs font-bold text-[#6A7A70]'>
                        GeoScore
                      </p>
                      <p className='text-3xl font-black text-[#F26A4B]'>
                        {place.geo_score || place.search_score || '-'}
                      </p>
                    </div>
                  </div>

                  <p className='mt-3 line-clamp-3 text-sm leading-6 text-[#5D6B62]'>
                    {place.short_description ||
                      'Detail tempat akan tampil di sini setelah admin melengkapinya.'}
                  </p>

                  <div className='mt-4 grid grid-cols-2 gap-3 text-sm'>
                    <InfoTile
                      label='Jarak'
                      value={
                        place.distance_km !== null &&
                        place.distance_km !== undefined
                          ? `${place.distance_km} km`
                          : 'Aktifkan lokasi'
                      }
                      icon={mdiNavigationVariantOutline}
                    />
                    <InfoTile
                      label='Rating'
                      value={`${place.rating_average || '-'} (${place.rating_count || 0})`}
                      icon={mdiStar}
                    />
                    <InfoTile
                      label='Live'
                      value={`${place.live_status?.label || '-'} · ${place.live_status?.crowd || '-'}`}
                      icon={mdiClockOutline}
                    />
                    <InfoTile
                      label='Stok/Jasa'
                      value={`${place.offerings_summary?.available || 0}/${place.offerings_summary?.total || 0} aktif`}
                      icon={mdiPackageVariantClosed}
                    />
                  </div>

                  {place.geo_score_breakdown ? (
                    <div className='mt-4 rounded-2xl bg-[#F7F2E8] p-4'>
                      <p className='mb-3 text-xs font-black uppercase tracking-wide text-[#6A7A70]'>
                        Breakdown GeoScore
                      </p>
                      {(
                        Object.entries(place.geo_score_breakdown) as [
                          keyof GeoScoreBreakdown,
                          number,
                        ][]
                      ).map(([key, value]) => (
                        <ScoreBar
                          key={key}
                          label={scoreLabels[key]}
                          value={value}
                        />
                      ))}
                    </div>
                  ) : null}

                  {place.offerings_summary?.top_available?.length ? (
                    <div className='mt-4'>
                      <p className='mb-2 text-xs font-black uppercase tracking-wide text-[#6A7A70]'>
                        Produk / jasa tersedia
                      </p>
                      <div className='flex flex-wrap gap-2'>
                        {place.offerings_summary.top_available.map(
                          (offering) => (
                            <span
                              key={offering.id}
                              className={`rounded-full px-3 py-1 text-xs font-bold ${stockColor(offering.stock_status)}`}
                            >
                              {offering.name} · {offering.stock_label}
                            </span>
                          ),
                        )}
                      </div>
                    </div>
                  ) : null}

                  <div className='mt-4 rounded-2xl border border-[#E8DEC9] p-4'>
                    <div className='flex items-center gap-2 text-sm font-black text-[#087F6D]'>
                      <BaseIcon path={mdiRobotHappyOutline} size={18} />{' '}
                      {place.ai_recommendation?.label || 'AI Recommendation'}
                    </div>
                    <p className='mt-2 text-sm leading-6 text-[#5D6B62]'>
                      {place.ai_recommendation?.reason ||
                        'Rekomendasi dibuat dari sinyal lokal dan GeoScore.'}
                    </p>
                  </div>

                  <div className='mt-4 rounded-2xl bg-[#F7F2E8] p-4 text-sm text-[#5D6B62]'>
                    <p className='text-xs font-black uppercase tracking-wide text-[#087F6D]'>
                      Alamat / lokasi penjual
                    </p>
                    <p className='mt-1 font-semibold'>
                      {place.address ||
                        [place.city, place.province].filter(Boolean).join(', ') ||
                        (place.latitude && place.longitude
                          ? `${place.latitude}, ${place.longitude}`
                          : 'Alamat detail belum tersedia')}
                    </p>
                    <p className='mt-1 text-xs font-bold text-[#6A7A70]'>
                      Sumber:{' '}
                      {place.external_source === 'openstreetmap'
                        ? 'OpenStreetMap'
                        : 'Database GeoSeek'}
                    </p>
                  </div>
                  <div className='mt-auto pt-5'>
                    <Link
                      href={buildPlaceHref(place)}
                      target={
                        shouldOpenExternalPlace(place) ? '_blank' : undefined
                      }
                      rel={
                        shouldOpenExternalPlace(place)
                          ? 'noreferrer'
                          : undefined
                      }
                      className='inline-flex w-full items-center justify-center gap-2 rounded-2xl bg-[#073B3A] px-4 py-3 font-black text-white transition group-hover:bg-[#087F6D]'
                    >
                      {place.external_source === 'openstreetmap'
                        ? 'Buka rute di Maps'
                        : 'Lihat detail, stok & arah'}{' '}
                      <BaseIcon path={mdiArrowRight} size={18} />
                    </Link>
                  </div>
                </article>
              ))}
            </div>
          ) : (
            <div className='rounded-[2rem] border border-dashed border-[#CDBF9E] bg-white p-10 text-center'>
              <h3 className='text-2xl font-black'>
                Data asli belum ditemukan untuk kata kunci ini
              </h3>
              <p className='mx-auto mt-3 max-w-2xl text-[#5D6B62]'>
                GeoSeek sudah mencoba memperluas radius dan mencari dari database
                GeoSeek + OpenStreetMap. Sistem tidak membuat alamat palsu; jika
                sumber publik belum punya data, tambahkan listing resmi agar
                pencarian seperti “warteg terdekat” atau “toko bahan bangunan”
                tidak kosong.
              </p>
              <div className='mt-6 flex flex-wrap justify-center gap-3'>
                <button
                  type='button'
                  onClick={() => setRadiusKm(100)}
                  className='rounded-full bg-[#073B3A] px-5 py-3 text-sm font-black text-white transition hover:bg-[#087F6D]'
                >
                  Perluas radius 100 km
                </button>
                <BaseButton
                  href='/login'
                  label='Tambah listing resmi'
                  color='warning'
                  roundedFull
                />
              </div>
            </div>
          )}
        </section>

        <section id='keywords' className='mx-auto max-w-7xl px-6 py-16 lg:px-8'>
          <div className='mb-8 flex flex-col gap-4 md:flex-row md:items-end md:justify-between'>
            <div className='max-w-3xl'>
              <p className='text-sm font-black uppercase tracking-[0.25em] text-[#087F6D]'>
                Keyword Engine GeoSeek
              </p>
              <h2 className='mt-2 text-4xl font-black tracking-tight'>
                Kata kunci lokasi yang paling banyak dicari.
              </h2>
              <p className='mt-4 leading-7 text-[#5D6B62]'>
                Klik chip untuk langsung live search. GeoSeek mengenali intent
                seperti terdekat, dekat saya, near me, buka sekarang, 24 jam,
                radius, jenis usaha, kota, kecamatan, rating, populer, murah,
                terbaru, terverifikasi, produk, jasa, properti, kantor pemerintahan, dan BUMN/BUMD.
              </p>
            </div>
            <div className='rounded-[2rem] bg-white p-5 text-sm font-bold text-[#5D6B62] shadow-sm'>
              <span className='block text-3xl font-black text-[#F26A4B]'>
                {totalKeywordChips}
              </span>
              keyword siap klik + sinonim usaha
            </div>
          </div>

          <div className='grid gap-6 lg:grid-cols-[0.95fr_1.05fr]'>
            <div className='rounded-[2rem] bg-white p-6 shadow-sm'>
              <div className='mb-5 flex items-center gap-3'>
                <div className='inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-[#E8F6F1] text-[#087F6D]'>
                  <BaseIcon path={mdiMapMarkerRadiusOutline} size={26} />
                </div>
                <div>
                  <p className='text-xs font-black uppercase tracking-[0.2em] text-[#F26A4B]'>
                    Urut skor pencarian
                  </p>
                  <h3 className='text-2xl font-black'>
                    Kata kunci lokasi utama
                  </h3>
                </div>
              </div>
              <div className='flex flex-wrap gap-2'>
                {topLocationKeywords.map((keyword) => (
                  <KeywordButton
                    key={keyword.label}
                    keyword={keyword}
                    onClick={applyKeyword}
                    showScore
                  />
                ))}
              </div>
            </div>

            <div className='rounded-[2rem] bg-[#073B3A] p-6 text-white shadow-xl shadow-[#073B3A]/10'>
              <div className='mb-5 flex items-center gap-3'>
                <div className='inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-white/10 text-[#F2A541]'>
                  <BaseIcon path={mdiStorefrontOutline} size={26} />
                </div>
                <div>
                  <p className='text-xs font-black uppercase tracking-[0.2em] text-[#F2A541]'>
                    Kombinasi kata kunci
                  </p>
                  <h3 className='text-2xl font-black'>
                    Produk, jasa, kuliner, properti, logistik, pemerintahan
                    & semua intent hyperlocal
                  </h3>
                </div>
              </div>
              <div className='grid gap-4 md:grid-cols-2'>
                {categoryKeywordGroups.map((group) => (
                  <KeywordGroupCard
                    key={group.title}
                    group={group}
                    onKeywordClick={applyKeyword}
                  />
                ))}
              </div>
            </div>
          </div>

          <div className='mt-6 grid gap-6 lg:grid-cols-[1fr_1.1fr]'>
            <div className='rounded-[2rem] bg-white p-6 shadow-sm'>
              <div className='mb-4 flex items-center gap-2 font-black'>
                <BaseIcon
                  path={mdiShieldCheckOutline}
                  size={22}
                  className='text-[#087F6D]'
                />{' '}
                Keyword wajib GeoSeek
              </div>
              <div className='flex flex-wrap gap-2'>
                {requiredLocationKeywords.map((keyword) => (
                  <KeywordButton
                    key={keyword.label}
                    keyword={keyword}
                    onClick={applyKeyword}
                    compact
                  />
                ))}
              </div>
            </div>

            <div className='rounded-[2rem] bg-white p-6 shadow-sm'>
              <div className='mb-4 flex items-center gap-2 font-black'>
                <BaseIcon
                  path={mdiTrendingUp}
                  size={22}
                  className='text-[#087F6D]'
                />{' '}
                Keyword trafik tertinggi
              </div>
              <div className='flex flex-wrap gap-2'>
                {topTrafficKeywords.map((keyword, index) => (
                  <KeywordButton
                    key={`${keyword.label}-${index}`}
                    keyword={keyword}
                    onClick={applyKeyword}
                    compact
                    rank={index + 1}
                  />
                ))}
              </div>
            </div>
          </div>

          <div className='mt-6 rounded-[2rem] bg-white p-6 shadow-sm'>
            <div className='mb-5 flex items-center gap-3'>
              <div className='inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-[#FFF3D7] text-[#9A6500]'>
                <BaseIcon path={mdiLayersTripleOutline} size={26} />
              </div>
              <div>
                <p className='text-xs font-black uppercase tracking-[0.2em] text-[#F26A4B]'>
                  Pola hyperlocal
                </p>
                <h3 className='text-2xl font-black'>
                  Level 1 sampai Level 5 keyword lokasi
                </h3>
              </div>
            </div>
            <div className='grid gap-4 lg:grid-cols-5'>
              {hyperlocalPatternLevels.map((pattern) => (
                <div
                  key={pattern.level}
                  className='rounded-[1.5rem] bg-[#F7F2E8] p-4'
                >
                  <p className='text-xs font-black uppercase tracking-[0.2em] text-[#087F6D]'>
                    {pattern.level}
                  </p>
                  <p className='mt-1 text-sm font-black'>{pattern.formula}</p>
                  <div className='mt-3 flex flex-wrap gap-2'>
                    {pattern.examples.map((keyword) => (
                      <KeywordButton
                        key={keyword.label}
                        keyword={keyword}
                        onClick={applyKeyword}
                        compact
                      />
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>

        <section
          id='advantages'
          className='mx-auto max-w-7xl px-6 py-16 lg:px-8'
        >
          <div className='mb-8 grid gap-6 lg:grid-cols-[1.08fr_0.92fr] lg:items-end'>
            <div className='max-w-3xl'>
              <p className='text-sm font-black uppercase tracking-[0.25em] text-[#087F6D]'>
                Keunggulan Utama
              </p>
              <h2 className='mt-2 text-4xl font-black tracking-tight md:text-5xl'>
                Navigasi hyperlocal yang cepat, dinamis, dan berbasis pengguna.
              </h2>
              <p className='mt-4 leading-7 text-[#5D6B62]'>
                GeoSeek dibentuk sebagai aplikasi navigasi hyperlocal: pengguna
                mencari kebutuhan sekitar, melihat hasil live berdasarkan
                radius, lalu langsung memilih rute, WhatsApp, booking, atau
                kurir lokal dari satu layar.
              </p>
            </div>
            <div className='grid gap-3 rounded-[2rem] bg-[#073B3A] p-5 text-sm font-bold text-white shadow-xl shadow-[#073B3A]/10 sm:grid-cols-3 lg:grid-cols-1 xl:grid-cols-3'>
              <div className='rounded-2xl bg-white/10 p-4'>
                <span className='block text-3xl font-black text-[#F2A541]'>
                  Live
                </span>
                <span className='text-white/70'>
                  hasil berubah mengikuti query dan radius
                </span>
              </div>
              <div className='rounded-2xl bg-white/10 p-4'>
                <span className='block text-3xl font-black text-[#F2A541]'>
                  GeoScore
                </span>
                <span className='text-white/70'>
                  ranking dari jarak, relevansi, reputasi
                </span>
              </div>
              <div className='rounded-2xl bg-white/10 p-4'>
                <span className='block text-3xl font-black text-[#F2A541]'>
                  {mainAdvantages.length}x
                </span>
                <span className='text-white/70'>
                  fitur inti untuk mobilitas lokal
                </span>
              </div>
            </div>
          </div>

          <div className='grid gap-5 md:grid-cols-2 xl:grid-cols-4'>
            {mainAdvantages.map((advantage) => (
              <article
                key={advantage.title}
                className='group flex h-full flex-col overflow-hidden rounded-[2rem] bg-white p-6 shadow-sm transition hover:-translate-y-1 hover:shadow-2xl hover:shadow-[#073B3A]/10'
              >
                <div className='flex items-start justify-between gap-4'>
                  <div className='inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-[#E8F6F1] text-[#087F6D]'>
                    <BaseIcon path={advantage.icon} size={26} />
                  </div>
                  <div className='rounded-2xl bg-[#073B3A] px-4 py-3 text-right text-white transition group-hover:bg-[#087F6D]'>
                    <span className='block text-lg font-black text-[#F2A541]'>
                      {advantage.metric}
                    </span>
                    <span className='text-[11px] font-bold leading-4 text-white/70'>
                      {advantage.metricLabel}
                    </span>
                  </div>
                </div>
                <h3 className='mt-5 text-2xl font-black'>{advantage.title}</h3>
                <p className='mt-3 flex-1 text-sm leading-6 text-[#5D6B62]'>
                  {advantage.description}
                </p>
                <div className='mt-5 flex flex-wrap gap-2'>
                  {advantage.bullets.map((bullet) => (
                    <span
                      key={bullet}
                      className='rounded-full bg-[#F7F2E8] px-3 py-1 text-xs font-black text-[#073B3A]'
                    >
                      {bullet}
                    </span>
                  ))}
                </div>
              </article>
            ))}
          </div>

          <div className='mt-8 rounded-[2.5rem] bg-[#073B3A] p-6 text-white shadow-2xl shadow-[#073B3A]/15 md:flex md:items-center md:justify-between md:gap-6'>
            <div>
              <p className='text-sm font-black uppercase tracking-[0.25em] text-[#F2A541]'>
                Siap dipakai sebagai aplikasi
              </p>
              <h3 className='mt-2 text-2xl font-black'>
                Mulai dari box cari, radius lokasi, hasil live, sampai aksi
                lokal.
              </h3>
              <p className='mt-2 text-sm leading-6 text-white/70'>
                Alur pengguna dibuat ringkas: cari kebutuhan → pilih hasil
                terdekat → buka rute/kontak/booking → simpan aktivitas lokal.
              </p>
            </div>
            <div className='mt-5 flex flex-col gap-3 sm:flex-row md:mt-0'>
              <a
                href='#search'
                className='inline-flex items-center justify-center gap-2 rounded-2xl bg-[#F2A541] px-5 py-3 text-sm font-black text-[#073B3A] transition hover:bg-white'
              >
                Coba Live Search <BaseIcon path={mdiArrowRight} size={18} />
              </a>
              <Link
                href='/geoseek'
                className='inline-flex items-center justify-center gap-2 rounded-2xl border border-white/20 px-5 py-3 text-sm font-black text-white transition hover:bg-white/10'
              >
                Buka GeoSeek Pro <BaseIcon path={mdiArrowRight} size={18} />
              </Link>
            </div>
          </div>
        </section>

        <section id='comparison' className='bg-white/55 py-16'>
          <div className='mx-auto max-w-7xl px-6 lg:px-8'>
            <div className='grid gap-8 lg:grid-cols-[0.82fr_1.18fr] lg:items-start'>
              <div className='rounded-[2.5rem] bg-[#073B3A] p-8 text-white shadow-2xl shadow-[#073B3A]/15'>
                <p className='text-sm font-black uppercase tracking-[0.25em] text-[#F2A541]'>
                  GeoSeek vs Google Maps
                </p>
                <h2 className='mt-3 text-4xl font-black tracking-tight'>
                  Bukan hanya mencari lokasi, tapi menemukan produk, jasa, dan
                  transaksi lokal terdekat.
                </h2>
                <p className='mt-5 leading-7 text-white/75'>
                  Google Maps kuat untuk peta, navigasi, dan informasi bisnis.
                  GeoSeek melengkapinya sebagai mesin pencari hyperlocal yang
                  memprioritaskan jarak nyata, katalog produk, jasa
                  terverifikasi, dan aksi transaksi dalam satu ekosistem lokal.
                </p>

                <div className='mt-7 grid gap-3 sm:grid-cols-2 lg:grid-cols-1'>
                  <div className='rounded-[1.5rem] bg-white/10 p-4'>
                    <span className='block text-3xl font-black text-[#F2A541]'>
                      RT/RW
                    </span>
                    <span className='text-sm font-bold text-white/75'>
                      cakupan pencarian lingkungan mikro
                    </span>
                  </div>
                  <div className='rounded-[1.5rem] bg-white/10 p-4'>
                    <span className='block text-3xl font-black text-[#F2A541]'>
                      Produk + Jasa
                    </span>
                    <span className='text-sm font-bold text-white/75'>
                      dengan harga, stok, jadwal, dan status tersedia
                    </span>
                  </div>
                </div>

                <div className='mt-7 rounded-[1.75rem] border border-white/10 bg-black/10 p-4'>
                  <p className='text-xs font-black uppercase tracking-[0.22em] text-[#F2A541]'>
                    Peran dalam aplikasi
                  </p>
                  <div className='mt-4 space-y-4'>
                    {comparisonMatrix.map((row) => (
                      <div
                        key={row.label}
                        className='rounded-2xl bg-white/10 p-4'
                      >
                        <p className='text-sm font-black text-white'>
                          {row.label}
                        </p>
                        <div className='mt-3 grid gap-3 text-xs leading-5 sm:grid-cols-2 lg:grid-cols-1'>
                          <div>
                            <span className='font-black uppercase tracking-wide text-white/45'>
                              Maps
                            </span>
                            <p className='mt-1 text-white/70'>{row.maps}</p>
                          </div>
                          <div>
                            <span className='font-black uppercase tracking-wide text-[#F2A541]'>
                              GeoSeek
                            </span>
                            <p className='mt-1 text-white'>{row.geoseek}</p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              <div className='grid gap-5 md:grid-cols-2'>
                {comparisonAdvantages.map((advantage, index) => (
                  <article
                    key={advantage.title}
                    className={`rounded-[2rem] p-6 shadow-sm transition hover:-translate-y-1 hover:shadow-2xl hover:shadow-[#073B3A]/10 ${index === comparisonAdvantages.length - 1 ? 'bg-[#F2A541] text-[#073B3A] md:col-span-2' : 'bg-white'}`}
                  >
                    <div
                      className={`inline-flex h-12 w-12 items-center justify-center rounded-2xl ${index === comparisonAdvantages.length - 1 ? 'bg-[#073B3A] text-white' : 'bg-[#E8F6F1] text-[#087F6D]'}`}
                    >
                      <BaseIcon path={advantage.icon} size={26} />
                    </div>
                    <h3 className='mt-5 text-2xl font-black'>
                      {advantage.title}
                    </h3>
                    <p
                      className={`mt-3 text-sm leading-6 ${index === comparisonAdvantages.length - 1 ? 'text-[#073B3A]/80' : 'text-[#5D6B62]'}`}
                    >
                      {advantage.description}
                    </p>
                    <div className='mt-5 flex flex-wrap gap-2'>
                      {advantage.points.map((point) => (
                        <span
                          key={point}
                          className={`rounded-full px-3 py-1 text-xs font-black ${index === comparisonAdvantages.length - 1 ? 'bg-[#073B3A]/10 text-[#073B3A]' : 'bg-[#F7F2E8] text-[#073B3A]'}`}
                        >
                          {point}
                        </span>
                      ))}
                    </div>
                  </article>
                ))}
              </div>
            </div>

            <div className='mt-8 rounded-[2.5rem] bg-[#F7F2E8] p-6 shadow-xl shadow-[#073B3A]/5'>
              <div className='grid gap-6 lg:grid-cols-[0.78fr_1.22fr] lg:items-start'>
                <div>
                  <p className='text-sm font-black uppercase tracking-[0.25em] text-[#087F6D]'>
                    Ekosistem GeoSeek
                  </p>
                  <h3 className='mt-2 text-3xl font-black tracking-tight md:text-4xl'>
                    Dari pencarian RT/RW sampai transaksi dan dashboard bisnis.
                  </h3>
                  <p className='mt-4 leading-7 text-[#5D6B62]'>
                    Alur aplikasi dibuat untuk kebutuhan nyata warga dan UMKM:
                    cari kebutuhan terdekat, lihat data produk/jasa yang
                    tersedia, lakukan aksi transaksi, lalu pemilik usaha
                    mendapat insight performa lokal.
                  </p>
                  <div className='mt-6 grid gap-3 sm:grid-cols-2'>
                    {dashboardMetrics.map((item) => (
                      <div
                        key={item.metric}
                        className='rounded-2xl bg-white p-4 shadow-sm'
                      >
                        <span className='block text-2xl font-black text-[#F26A4B]'>
                          {item.metric}
                        </span>
                        <span className='text-xs font-bold leading-5 text-[#5D6B62]'>
                          {item.label}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>

                <div className='grid gap-4 md:grid-cols-2'>
                  {ecosystemSteps.map((step) => (
                    <article
                      key={step.title}
                      className='rounded-[2rem] bg-white p-5 shadow-sm'
                    >
                      <div className='flex items-start gap-4'>
                        <div className='inline-flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl bg-[#E8F6F1] text-[#087F6D]'>
                          <BaseIcon path={step.icon} size={26} />
                        </div>
                        <div>
                          <h4 className='text-lg font-black'>{step.title}</h4>
                          <p className='mt-2 text-sm leading-6 text-[#5D6B62]'>
                            {step.description}
                          </p>
                        </div>
                      </div>
                      <div className='mt-4 flex flex-wrap gap-2'>
                        {step.tags.map((tag) => (
                          <span
                            key={tag}
                            className='rounded-full bg-[#073B3A] px-3 py-1 text-xs font-black text-white'
                          >
                            {tag}
                          </span>
                        ))}
                      </div>
                    </article>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </section>

        <section id='automation' className='bg-[#073B3A] py-16 text-white'>
          <div className='mx-auto max-w-7xl px-6 lg:px-8'>
            <div className='grid gap-8 lg:grid-cols-[0.9fr_1.1fr] lg:items-start'>
              <div>
                <p className='text-sm font-black uppercase tracking-[0.25em] text-[#F2A541]'>
                  Otomatisasi & Input Cerdas
                </p>
                <h2 className='mt-3 text-4xl font-black tracking-tight'>
                  Input sekali, GeoSeek mengubahnya menjadi data lokal yang bisa
                  dicari, diverifikasi, dan ditransaksikan.
                </h2>
                <p className='mt-5 leading-7 text-white/75'>
                  Google Maps kuat untuk peta dan Waze kuat untuk laporan jalan.
                  GeoSeek naik level dengan input otomatis untuk lalu lintas,
                  UMKM, stok produk, jasa, booking, dan transaksi lokal dalam
                  satu ekosistem hyperlocal.
                </p>

                <div className='mt-8 grid gap-4 sm:grid-cols-3'>
                  <div className='rounded-[1.5rem] bg-white/10 p-5'>
                    <span className='block text-3xl font-black text-[#F2A541]'>
                      1x
                    </span>
                    <span className='text-sm font-bold text-white/75'>
                      input cepat dari warga atau pemilik usaha
                    </span>
                  </div>
                  <div className='rounded-[1.5rem] bg-white/10 p-5'>
                    <span className='block text-3xl font-black text-[#F2A541]'>
                      Auto
                    </span>
                    <span className='text-sm font-bold text-white/75'>
                      kategori, tag, radius, dan status tersedia
                    </span>
                  </div>
                  <div className='rounded-[1.5rem] bg-white/10 p-5'>
                    <span className='block text-3xl font-black text-[#F2A541]'>
                      Live
                    </span>
                    <span className='text-sm font-bold text-white/75'>
                      draft siap validasi komunitas dan dashboard bisnis
                    </span>
                  </div>
                </div>
              </div>

              <div className='rounded-[2.5rem] bg-white p-6 text-[#17231B] shadow-2xl shadow-black/20'>
                <div className='flex items-start justify-between gap-4'>
                  <div>
                    <p className='text-xs font-black uppercase tracking-[0.22em] text-[#F26A4B]'>
                      Demo Input Pintar
                    </p>
                    <h3 className='mt-2 text-2xl font-black'>
                      Coba alur otomatisasi GeoSeek
                    </h3>
                  </div>
                  <div className='inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-[#E8F6F1] text-[#087F6D]'>
                    <BaseIcon path={mdiRobotHappyOutline} size={28} />
                  </div>
                </div>

                <div className='mt-5 flex flex-wrap gap-2'>
                  {smartInputOptions.map((option) => (
                    <button
                      type='button'
                      key={option.id}
                      onClick={() => {
                        setSmartInputType(option.id);
                        setSmartInputText(option.placeholder);
                      }}
                      className={`rounded-full px-4 py-2 text-xs font-black transition ${option.id === selectedSmartInput.id ? 'bg-[#073B3A] text-white shadow-lg shadow-[#073B3A]/20' : 'bg-[#F7F2E8] text-[#073B3A] hover:bg-[#E8F6F1]'}`}
                    >
                      {option.label}
                    </button>
                  ))}
                </div>

                <p className='mt-5 rounded-2xl bg-[#F7F2E8] p-4 text-sm font-semibold leading-6 text-[#5D6B62]'>
                  {selectedSmartInput.title}
                </p>

                <label className='mt-4 block'>
                  <span className='mb-2 block text-sm font-black text-[#073B3A]'>
                    Tulis laporan, stok, produk, jasa, atau promo
                  </span>
                  <textarea
                    value={smartInputText}
                    onChange={(event) => setSmartInputText(event.target.value)}
                    rows={5}
                    className='w-full rounded-2xl border border-[#E0D6C3] bg-[#FCFAF5] p-4 text-sm leading-6 outline-none transition focus:border-[#2CA58D] focus:ring-4 focus:ring-[#2CA58D]/15'
                  />
                </label>

                <div className='mt-4 rounded-[1.75rem] border border-[#E0D6C3] bg-[#FCFAF5] p-5'>
                  <div className='flex items-center gap-2 text-xs font-black uppercase tracking-[0.2em] text-[#087F6D]'>
                    <BaseIcon path={mdiFire} size={18} />
                    Preview otomatis
                  </div>
                  <p className='mt-3 text-lg font-black text-[#073B3A]'>
                    {smartInputSummary}
                  </p>
                  <div className='mt-4 flex flex-wrap gap-2'>
                    {selectedSmartInput.tags.map((tag) => (
                      <span
                        key={tag}
                        className='rounded-full bg-[#E8F6F1] px-3 py-1 text-xs font-black text-[#087F6D]'
                      >
                        {tag}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className='mt-8 grid gap-5 md:grid-cols-2 xl:grid-cols-3'>
              {automationInputFeatures.map((feature) => (
                <article
                  key={feature.title}
                  className='group rounded-[2rem] bg-white/10 p-6 shadow-sm transition hover:-translate-y-1 hover:bg-white hover:text-[#17231B] hover:shadow-2xl hover:shadow-black/20'
                >
                  <div className='inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-[#F2A541] text-[#073B3A]'>
                    <BaseIcon path={feature.icon} size={26} />
                  </div>
                  <h3 className='mt-5 text-2xl font-black'>{feature.title}</h3>
                  <p className='mt-3 text-sm leading-6 text-white/75 group-hover:text-[#5D6B62]'>
                    {feature.description}
                  </p>
                  <div className='mt-5 flex flex-wrap gap-2'>
                    {feature.points.map((point) => (
                      <span
                        key={point}
                        className='rounded-full bg-white/10 px-3 py-1 text-xs font-black text-[#F2A541] group-hover:bg-[#F7F2E8] group-hover:text-[#073B3A]'
                      >
                        {point}
                      </span>
                    ))}
                  </div>
                </article>
              ))}
            </div>
          </div>
        </section>

        <section
          id='geoscore'
          className='mx-auto grid max-w-7xl gap-6 px-6 py-14 lg:grid-cols-[0.9fr_1.1fr] lg:px-8'
        >
          <div className='rounded-[2rem] bg-white p-8 shadow-sm'>
            <div className='inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-[#E8F6F1] text-[#087F6D]'>
              <BaseIcon path={mdiChartTimelineVariant} size={26} />
            </div>
            <p className='mt-5 text-sm font-black uppercase tracking-[0.25em] text-[#087F6D]'>
              Formula Ranking Baru
            </p>
            <h2 className='mt-2 text-4xl font-black tracking-tight'>
              GeoScore tidak hanya jarak.
            </h2>
            <p className='mt-4 leading-7 text-[#5D6B62]'>
              Toko yang sangat dekat belum tentu menang jika rating rendah, stok
              tidak aktif, dan data jarang diperbarui.
            </p>
          </div>
          <div className='grid gap-4 md:grid-cols-2'>
            {formulaEntries.map(([key, value]) => (
              <div
                key={key}
                className='rounded-[1.6rem] bg-white p-5 shadow-sm'
              >
                <div className='flex items-center justify-between'>
                  <p className='font-black capitalize'>
                    {scoreLabels[key as keyof GeoScoreBreakdown] || key}
                  </p>
                  <span className='rounded-full bg-[#073B3A] px-3 py-1 text-sm font-black text-white'>
                    {value}%
                  </span>
                </div>
                <div className='mt-4 h-3 overflow-hidden rounded-full bg-[#F0E6D3]'>
                  <div
                    className='h-full rounded-full bg-[#2CA58D]'
                    style={{ width: `${value}%` }}
                  />
                </div>
              </div>
            ))}
          </div>
        </section>

        <section
          id='trending'
          className='bg-[#073B3A] px-6 py-16 text-white lg:px-8'
        >
          <div className='mx-auto max-w-7xl'>
            <div className='mb-8 flex flex-col gap-4 md:flex-row md:items-end md:justify-between'>
              <div>
                <p className='text-sm font-black uppercase tracking-[0.25em] text-[#F2A541]'>
                  Hyperlocal Trending
                </p>
                <h2 className='mt-2 text-4xl font-black tracking-tight'>
                  Yang sedang berguna di sekitar Anda.
                </h2>
              </div>
              <div className='rounded-full bg-white/10 px-4 py-2 text-sm font-bold text-white/80'>
                {openNow} buka sekarang dari{' '}
                {places.length || searchMeta.trending?.live?.total || 0} hasil
              </div>
            </div>

            <div className='grid gap-5 lg:grid-cols-3'>
              <TrendingCard
                icon={mdiTrendingUp}
                title='Topik lokal'
                items={(searchMeta.trending?.local_topics || []).map(
                  (item) => `${item.name} · ${item.label}`,
                )}
                fallback='Kategori lokal akan muncul setelah data terindeks.'
              />
              <TrendingCard
                icon={mdiFire}
                title='Produk & jasa tersedia'
                items={(searchMeta.trending?.products || [])
                  .slice(0, 5)
                  .map(
                    (item) =>
                      `${item.name} di ${item.place_name} · ${item.stock_label}`,
                  )}
                fallback='Produk/stok UMKM akan muncul setelah listing diperbarui.'
              />
              <TrendingCard
                icon={mdiMapSearchOutline}
                title='Event, berita, video lokal'
                items={searchMeta.trending?.events || []}
                fallback='Crawler berita, video, gambar, podcast, dan PDF siap ditambahkan.'
              />
            </div>
          </div>
        </section>

        <section className='mx-auto max-w-7xl px-6 py-16 lg:px-8'>
          <div className='mb-8 max-w-3xl'>
            <p className='text-sm font-black uppercase tracking-[0.25em] text-[#087F6D]'>
              Data yang diindeks
            </p>
            <h2 className='mt-2 text-4xl font-black tracking-tight'>
              Fondasi menuju Hyperlocal Search Ecosystem.
            </h2>
            <p className='mt-4 leading-7 text-[#5D6B62]'>
              MVP saat ini sudah mengindeks tempat, kategori, produk, jasa,
              stok, rating, dan lokasi. Struktur UI disiapkan untuk memperluas
              ke website, media, PDF, crawler, PostGIS, dan Elasticsearch.
            </p>
          </div>
          <div className='grid gap-5 md:grid-cols-3'>
            {indexedLevels.map((level) => (
              <div
                key={level.level}
                className='rounded-[2rem] bg-white p-6 shadow-sm'
              >
                <div className='inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-[#E8F6F1] text-[#087F6D]'>
                  <BaseIcon path={level.icon} size={26} />
                </div>
                <p className='mt-5 text-sm font-black uppercase tracking-[0.2em] text-[#F26A4B]'>
                  {level.level}
                </p>
                <h3 className='mt-2 text-2xl font-black'>{level.title}</h3>
                <div className='mt-4 flex flex-wrap gap-2'>
                  {level.items.map((item) => (
                    <span
                      key={item}
                      className='rounded-full bg-[#F7F2E8] px-3 py-1 text-xs font-bold text-[#5D6B62]'
                    >
                      {item}
                    </span>
                  ))}
                </div>
              </div>
            ))}
          </div>

          <div className='mt-8 grid gap-5 lg:grid-cols-3'>
            <FeatureBox
              icon={mdiDatabaseSearchOutline}
              title='PostgreSQL sekarang, PostGIS berikutnya'
              text='Latitude/longitude sudah dipakai. Tahap berikutnya bisa menambah PostGIS untuk radius, polygon RT/RW, dan jutaan data.'
            />
            <FeatureBox
              icon={mdiRadar}
              title='Elasticsearch-ready'
              text='Query, sinonim, radius, dan scoring sudah dipisah sehingga bisa dipindahkan ke Elasticsearch saat volume data besar.'
            />
            <FeatureBox
              icon={mdiCash}
              title='Monetisasi lokal'
              text='Listing gratis, prioritas tampil, analitik, iklan hyperlocal, booking, pembayaran, dan kurir bisa dibangun di atas GeoScore.'
            />
          </div>
        </section>
      </main>
    </>
  );
}

const KeywordButton = ({
  keyword,
  onClick,
  showScore = false,
  compact = false,
  rank,
}: {
  keyword: KeywordChip;
  onClick: (keyword: KeywordChip) => void;
  showScore?: boolean;
  compact?: boolean;
  rank?: number;
}) => (
  <button
    type='button'
    onClick={() => onClick(keyword)}
    className={`group inline-flex items-center gap-2 rounded-full border border-[#E0D6C3] bg-white px-3 font-black text-[#073B3A] shadow-sm transition hover:-translate-y-0.5 hover:border-[#2CA58D] hover:bg-[#E8F6F1] ${compact ? 'py-1.5 text-xs' : 'py-2 text-sm'}`}
    title={`Cari: ${keyword.query}`}
  >
    {rank ? (
      <span className='rounded-full bg-[#073B3A] px-2 py-0.5 text-[10px] text-white'>
        {rank}
      </span>
    ) : null}
    <span>{keyword.label}</span>
    {showScore && keyword.score ? (
      <span className='rounded-full bg-[#F26A4B] px-2 py-0.5 text-[10px] text-white'>
        {keyword.score}
      </span>
    ) : null}
  </button>
);

const KeywordGroupCard = ({
  group,
  onKeywordClick,
}: {
  group: KeywordGroup;
  onKeywordClick: (keyword: KeywordChip) => void;
}) => (
  <div className='rounded-[1.5rem] bg-white/10 p-4'>
    <h4 className='font-black'>{group.title}</h4>
    <p className='mt-1 text-xs leading-5 text-white/65'>{group.description}</p>
    <div className='mt-3 flex flex-wrap gap-2'>
      {group.keywords.map((keyword) => (
        <button
          type='button'
          key={keyword.label}
          onClick={() => onKeywordClick(keyword)}
          className='rounded-full bg-white px-3 py-1.5 text-xs font-black text-[#073B3A] transition hover:-translate-y-0.5 hover:bg-[#F2A541]'
          title={`Cari: ${keyword.query}`}
        >
          {keyword.label}
        </button>
      ))}
    </div>
  </div>
);

const MetricCard = ({ value, label }: { value: string; label: string }) => (
  <div className='rounded-2xl bg-white p-4'>
    <p className='text-2xl font-black'>{value}</p>
    <p className='text-xs text-[#6A7A70]'>{label}</p>
  </div>
);

const InfoTile = ({
  label,
  value,
  icon,
}: {
  label: string;
  value: string;
  icon: string;
}) => (
  <div className='rounded-2xl bg-[#F7F2E8] p-3'>
    <p className='flex items-center gap-1 text-xs text-[#6A7A70]'>
      <BaseIcon path={icon} size={14} /> {label}
    </p>
    <p className='mt-1 font-black'>{value}</p>
  </div>
);

const ScoreBar = ({ label, value }: { label: string; value: number }) => (
  <div className='mb-2 last:mb-0'>
    <div className='mb-1 flex items-center justify-between text-xs text-[#5D6B62]'>
      <span>{label}</span>
      <span className='font-black'>{Math.round(value)}</span>
    </div>
    <div className='h-2 overflow-hidden rounded-full bg-white'>
      <div
        className='h-full rounded-full bg-[#2CA58D]'
        style={{ width: `${Math.max(0, Math.min(100, value))}%` }}
      />
    </div>
  </div>
);

const TrendingCard = ({
  icon,
  title,
  items,
  fallback,
}: {
  icon: string;
  title: string;
  items: string[];
  fallback: string;
}) => (
  <div className='rounded-[2rem] border border-white/10 bg-white/10 p-6 backdrop-blur'>
    <BaseIcon path={icon} size={30} className='text-[#F2A541]' />
    <h3 className='mt-4 text-2xl font-black'>{title}</h3>
    <div className='mt-4 space-y-3'>
      {(items.length ? items : [fallback]).map((item) => (
        <p
          key={item}
          className='rounded-2xl bg-white/10 p-3 text-sm leading-6 text-white/80'
        >
          {item}
        </p>
      ))}
    </div>
  </div>
);

const FeatureBox = ({
  icon,
  title,
  text,
}: {
  icon: string;
  title: string;
  text: string;
}) => (
  <div className='rounded-[2rem] bg-[#073B3A] p-6 text-white shadow-xl shadow-[#073B3A]/10'>
    <BaseIcon path={icon} size={30} className='text-[#F2A541]' />
    <h3 className='mt-4 text-xl font-black'>{title}</h3>
    <p className='mt-3 text-sm leading-6 text-white/75'>{text}</p>
  </div>
);

Starter.getLayout = function getLayout(page: ReactElement) {
  return <LayoutGuest>{page}</LayoutGuest>;
};
