import { useState, useEffect, useMemo } from 'react';
import { Plus, Search, Edit, ChevronDown, ChevronUp, MapPin, LayoutGrid } from 'lucide-react';
import { Button } from '@astryxdesign/core/Button';
import { Card } from '@astryxdesign/core/Card';
import { Table, proportional, pixel } from '@astryxdesign/core/Table';
import { Badge } from '@astryxdesign/core/Badge';
import { Text, Heading } from '@astryxdesign/core/Text';
import { IconButton } from '@astryxdesign/core/IconButton';
import { TextInput } from '@astryxdesign/core/TextInput';
import { Selector } from '@astryxdesign/core/Selector';
import { Dialog, DialogHeader } from '@astryxdesign/core/Dialog';
import { Layout, LayoutContent, LayoutFooter } from '@astryxdesign/core/Layout';
import { FormLayout } from '@astryxdesign/core/FormLayout';
import { Banner } from '@astryxdesign/core/Banner';
import { Item } from '@astryxdesign/core/Item';
import { Icon } from '@astryxdesign/core/Icon';

import PageHeader from '@/components/PageHeader';
import EmptyState from '@/components/EmptyState';
import { fetchUsers } from '@/utils/apiClient';

const API_BASE = import.meta.env.VITE_API_BASE || 'https://api.doormile.com/api/v1';

const getHeaders = () => {
  const token = localStorage.getItem('auth_token');
  return {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
};

async function apiFetchPricing() {
  const res = await fetch(`${API_BASE}/admin/carrier-pricing?limit=1000`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch pricing');
  const json = await res.json();
  return Array.isArray(json) ? { data: json } : json;
}

async function apiSavePricing(data) {
  const isUpdate = !!data.id;
  const url = isUpdate ? `${API_BASE}/admin/carrier-pricing/${data.id}` : `${API_BASE}/admin/carrier-pricing`;
  const method = isUpdate ? 'PUT' : 'POST';
  const res = await fetch(url, {
    method,
    headers: getHeaders(),
    body: JSON.stringify({
      company: data.company,
      weight_slab: data.weight_slab,
      zone: data.zone || '',
      service_type: data.service_type || '',
      rate: String(data.rate)
    })
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.error || err.message || 'Failed to save pricing');
  }
  return res.status === 204 ? {} : res.json().catch(() => ({}));
}

const ZONES = ['Local / Same', 'Within Tamilnadu', 'Interstate India'];
const WEIGHT_SLABS = ['< 500g', '500g - 1kg', '1kg - 2kg', '2kg - 5kg', '> 5kg'];

function PricingFormDialog({ open, onClose, onSave, initialData, isCell = false, pricingList = [], providerColumns = [], providerUsesServiceType = false }) {
  const [formData, setFormData] = useState({});
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (open) {
      setFormData(initialData || { company: '', weight_slab: '', zone: '', rate: '' });
      setError(null);
    }
  }, [open, initialData]);

  const colKey = (p) => ((p.zone || '').trim() || (p.service_type || '').trim());

  const findExistingRecord = (data) => {
    const company = (data.company || '').trim();
    const slab = (data.weight_slab || '').trim();
    const col = (data.zone || data.service_type || '').trim();
    return pricingList.find(p =>
      (p.company || '').trim() === company &&
      (p.weight_slab || '').trim() === slab &&
      colKey(p) === col
    ) || null;
  };

  const handleSave = async () => {
    const colValue = (formData.zone || formData.service_type || '').trim();
    if (!isCell) {
      if (!formData.company?.trim()) { setError('Company is required.'); return; }
      if (!formData.weight_slab?.trim()) { setError('Weight slab is required.'); return; }
      if (!colValue) { setError('Zone / Service Type is required.'); return; }
    }
    if (!String(formData.rate ?? '').trim()) { setError('Rate is required.'); return; }

    setSaving(true);
    setError(null);
    try {
      let dataToSave = { ...formData };
      if (!isCell) {
        dataToSave = {
          ...dataToSave,
          zone: providerUsesServiceType ? '' : colValue,
          service_type: providerUsesServiceType ? colValue : (dataToSave.service_type || ''),
        };
      }
      if (!dataToSave.id) {
        const existing = findExistingRecord(dataToSave);
        if (existing) dataToSave = { ...dataToSave, id: existing.id };
      }
      await apiSavePricing(dataToSave);
      onSave();
      onClose();
    } catch (err) {
      console.error(err);
      setError(err.message || 'Failed to save. Please try again.');
    } finally {
      setSaving(false);
    }
  };

  if (!open) return null;

  const zoneOptions = providerColumns.length > 0 ? providerColumns : ZONES;

  return (
    <Dialog isOpen={open} onOpenChange={(o) => { if (!o) onClose(); }} width={440} purpose="form">
      <Layout
        header={
          <DialogHeader
            title={initialData?.id ? 'Edit Rate' : (isCell ? 'Add Rate' : 'Add New Rate')}
            onOpenChange={(o) => { if (!o) onClose(); }}
          />
        }
        content={
          <LayoutContent>
            <FormLayout>
              {error && <Banner status="error" title={error} />}

              {isCell ? (
                <Card style={{ padding: '12px 16px', backgroundColor: 'rgba(10, 19, 23, 0.04)', border: '1px solid rgba(10, 19, 23, 0.15)' }}>
                  <Text type="label" color="secondary">Updating rate for</Text>
                  <div style={{ marginTop: '4px' }}>
                    <Heading level={5}>{formData.company}</Heading>
                  </div>
                  <div style={{ marginTop: '2px' }}>
                    <Text type="supporting" color="secondary">{formData.weight_slab} · {formData.zone || formData.service_type}</Text>
                  </div>
                </Card>
              ) : (
                <>
                  <TextInput
                    label="Company"
                    isRequired
                    value={formData.company || ''}
                    onChange={(v) => setFormData((prev) => ({ ...prev, company: v }))}
                  />
                  <Selector
                    label="Weight Slab"
                    isRequired
                    placeholder="Select Weight Slab"
                    options={WEIGHT_SLABS}
                    value={formData.weight_slab || ''}
                    onChange={(v) => setFormData((prev) => ({ ...prev, weight_slab: v || '' }))}
                  />
                  <Selector
                    label={providerUsesServiceType ? 'Service Type' : 'Zone / Service Type'}
                    isRequired
                    placeholder="Select Zone / Service"
                    options={zoneOptions}
                    value={formData.zone || formData.service_type || ''}
                    onChange={(v) => setFormData((prev) => ({
                      ...prev,
                      zone: providerUsesServiceType ? '' : (v || ''),
                      service_type: providerUsesServiceType ? (v || '') : ''
                    }))}
                  />
                </>
              )}

              <TextInput
                label="Rate (₹)"
                isRequired
                hasClear
                hasAutoFocus
                placeholder="e.g. 25 or 25-35"
                value={formData.rate || ''}
                onChange={(v) => setFormData((prev) => ({ ...prev, rate: v }))}
              />
            </FormLayout>
          </LayoutContent>
        }
        footer={
          <LayoutFooter hasDivider>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px' }}>
              <Button label="Cancel" variant="ghost" onClick={onClose} isDisabled={saving} />
              <Button
                label="Save Rate"
                variant="primary"
                onClick={handleSave}
                isDisabled={saving}
                isLoading={saving}
              />
            </div>
          </LayoutFooter>
        }
      />
    </Dialog>
  );
}

async function apiFetchSurveys() {
  const res = await fetch(`${API_BASE}/admin/competitor-branches?limit=1000`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch surveys');
  const json = await res.json();
  const data = Array.isArray(json) ? json : (json.data || []);
  return { data, total: data.length };
}

export default function Pricing() {
  const [pricingList, setPricingList] = useState([]);
  const [surveysList, setSurveysList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedProvider, setSelectedProvider] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [locationsOpen, setLocationsOpen] = useState(false);
  const [locationSearch, setLocationSearch] = useState('');
  const [formOpen, setFormOpen] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [isCellEdit, setIsCellEdit] = useState(false);
  const [users, setUsers] = useState([]);

  const loadData = () => {
    let cancelled = false;
    setLoading(true);
    Promise.all([
      apiFetchPricing().catch(() => ({ data: [] })),
      apiFetchSurveys().catch(() => ({ data: [] })),
      fetchUsers().catch(() => [])
    ]).then(([pRes, sRes, userRes]) => {
      if (!cancelled) {
        setPricingList(Array.isArray(pRes) ? pRes : (pRes.data || []));
        setSurveysList(sRes.data || sRes || []);
        setUsers(Array.isArray(userRes) ? userRes : (userRes.data || []));
      }
    }).catch(err => console.error("Failed to fetch data", err))
    .finally(() => {
      if (!cancelled) setLoading(false);
    });
    return () => { cancelled = true; };
  };

  useEffect(() => {
    return loadData();
  }, []);

  const companies = [...new Set(pricingList.map(p => p.company).filter(Boolean))];
  useEffect(() => {
    if (!selectedProvider && companies.length > 0) {
      setSelectedProvider(companies[0]);
    }
  }, [companies, selectedProvider]);

  const providerRates = pricingList.filter(p => p.company === selectedProvider);
  const normCompany = (s) => (s || '').toLowerCase().trim().replace(/\s+/g, ' ');
  const normProvider = normCompany(selectedProvider);
  const providerSurveys = surveysList.filter(p => {
    const pn = normCompany(p.company);
    return pn === normProvider || pn.startsWith(normProvider) || normProvider.startsWith(pn);
  });

  const filteredSurveys = useMemo(() => {
    if (!locationSearch.trim()) return providerSurveys;
    const q = locationSearch.toLowerCase();
    return providerSurveys.filter((s) =>
      (s.area || '').toLowerCase().includes(q) || (s.address || '').toLowerCase().includes(q)
    );
  }, [providerSurveys, locationSearch]);

  const sortedProviderRates = [...providerRates].sort((a, b) => (b.id || 0) - (a.id || 0));

  const slabSortWeight = (slab) => {
    const s = (slab || '').toLowerCase().replace(/\s+/g, '');
    const nums = s.match(/[\d.]+/g);
    if (!nums) return 9999;
    const first = parseFloat(nums[0]);
    const grams = s.includes('kg') ? first * 1000 : first;
    if (s.startsWith('<') || s.startsWith('upto')) return grams - 0.5;
    if (s.startsWith('>') || s.includes('above') || s.endsWith('+')) return grams + 0.5;
    return grams;
  };

  const normalizeZone = (z) => {
    if (!z) return '';
    let val = z.trim();
    const lower = val.toLowerCase().replace(/\s+/g, '');
    if (lower === 'tamilnadu') return 'Tamil Nadu';
    if (lower === 'karanataka' || lower === 'karnataka') return 'Karnataka';
    if (lower === 'local' || lower === 'localsame' || lower === 'local/same') return 'Local';
    if (lower === 'central/northindia' || lower === 'central/north') return 'Central/North India';
    return val;
  };

  const getColKey = (r) => normalizeZone((r.zone || '').trim() || (r.service_type || '').trim());
  const providerUsesServiceType = sortedProviderRates.length > 0 &&
    sortedProviderRates.every(r => !(r.zone || '').trim());

  const providerZones = [...new Set(sortedProviderRates.map(getColKey).filter(Boolean))].sort();

  const allProviderSlabs = [...new Set(sortedProviderRates.map(r => (r.weight_slab || '').trim()).filter(Boolean))]
    .sort((a, b) => slabSortWeight(a) - slabSortWeight(b));

  const displaySlabs = searchQuery
    ? allProviderSlabs.filter(s => s.toLowerCase().includes(searchQuery.toLowerCase()))
    : allProviderSlabs;

  const matrixData = useMemo(
    () => displaySlabs.map((slab) => ({
      slab,
      rates: Object.fromEntries(
        providerZones.map((zone) => [
          zone,
          sortedProviderRates.find(r => (r.weight_slab || '').trim() === slab && getColKey(r) === zone) || null
        ])
      )
    })),
    [displaySlabs, providerZones, sortedProviderRates]
  );

  const matrixColumns = useMemo(() => {
    const openCellEdit = (slab, zone, match) => {
      setEditingRecord({
        id: match ? match.id : undefined,
        company: selectedProvider,
        weight_slab: slab,
        zone: providerUsesServiceType ? '' : zone,
        service_type: providerUsesServiceType ? zone : (match?.service_type || ''),
        rate: match ? String(match.rate) : ''
      });
      setIsCellEdit(true);
      setFormOpen(true);
    };

    return [
      {
        key: 'slab',
        header: <div style={{ paddingLeft: '12px' }}>Weight Slab</div>,
        width: pixel(180),
        renderCell: (row) => (
          <div style={{ paddingLeft: '12px' }}>
            <Text type="body" weight="semibold">{row.slab}</Text>
          </div>
        )
      },
      ...providerZones.map((zone) => ({
        key: zone,
        header: zone,
        width: proportional(1),
        align: 'center',
        renderCell: (row) => {
          const match = row.rates[zone];
          const hasRate = !!match;
          return (
            <div
              className="matrix-cell"
              style={{
                position: 'relative',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '4px',
                borderRadius: '6px',
                width: '100%',
                boxSizing: 'border-box'
              }}
            >
              {hasRate ? (
                <Badge variant="red" label={`₹${match.rate}`} />
              ) : (
                <Text type="supporting" color="disabled">—</Text>
              )}
              <button
                type="button"
                className="matrix-cell-edit"
                onClick={() => openCellEdit(row.slab, zone, match)}
                aria-label={`Edit rate for ${row.slab} in ${zone}`}
                title={hasRate ? 'Edit rate' : 'Add rate'}
              >
                <Edit size={12} />
              </button>
            </div>
          );
        }
      }))
    ];
  }, [providerZones, selectedProvider, providerUsesServiceType]);

  return (
    <div style={{ fontFamily: 'system-ui, sans-serif' }}>
      <PageHeader
        title="Logistics Pricing Board"
        action={
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'nowrap' }}>
            <div style={{ flex: '0 1 280px', minWidth: '200px' }}>
              <Selector
                label="Active Logistics Provider"
                isLabelHidden
                placeholder={companies.length === 0 ? 'Loading providers…' : 'Select provider'}
                hasSearch
                hasClear={false}
                isDisabled={companies.length === 0}
                options={companies}
                value={selectedProvider || ''}
                onChange={(v) => setSelectedProvider(v || '')}
              />
            </div>
            <div style={{ flex: '0 1 260px', minWidth: '180px' }}>
              <TextInput
                label="Search weight slabs"
                isLabelHidden
                placeholder="Search weight slabs…"
                startIcon={<Search size={16} />}
                hasClear
                value={searchQuery}
                onChange={(v) => setSearchQuery(v)}
              />
            </div>
            <Button
              variant="primary"
              icon={<Plus size={14} />}
              onClick={() => { setEditingRecord({ company: selectedProvider, weight_slab: '', zone: '', rate: '' }); setIsCellEdit(false); setFormOpen(true); }}
              label="Add Rate"
              style={{ flexShrink: 0 }}
            />
          </div>
        }
      />

      <div style={{ display: 'flex', flexDirection: 'column', gap: '32px', marginTop: '24px' }}>

        {/* Collapsible Provider Profile */}
        {selectedProvider && providerSurveys.length > 0 && (
          <Card
            style={{
              borderRadius: '16px',
              border: locationsOpen ? '1px solid rgba(10, 19, 23, 0.25)' : '1px solid rgba(5, 54, 89, 0.08)',
              backgroundColor: '#ffffff',
              padding: '0',
              overflow: 'hidden',
              boxShadow: '0 10px 30px -5px rgba(0,0,0,0.02), 0 4px 12px -3px rgba(0,0,0,0.02)'
            }}
          >
            <div
              style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', padding: '12px 16px', cursor: 'pointer', justifyContent: 'space-between', flexWrap: 'wrap', gap: '12px' }}
              onClick={() => setLocationsOpen(!locationsOpen)}
            >
              <div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
                <div style={{ width: '32px', height: '32px', borderRadius: '8px', backgroundColor: 'rgba(10, 19, 23, 0.08)', color: '#0a1317', fontWeight: 800, fontSize: '0.875rem', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  {(selectedProvider || 'A')[0].toUpperCase()}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                  <Text type="body" weight="semibold">{selectedProvider}</Text>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                    <MapPin size={12} style={{ color: '#94a3b8' }} />
                    <Text type="supporting" color="secondary">{providerSurveys.length} location{providerSurveys.length !== 1 && 's'}</Text>
                  </div>
                </div>
              </div>

              <IconButton
                label={locationsOpen ? 'Hide coverage map' : 'View coverage map'}
                tooltip={locationsOpen ? 'Hide coverage map' : 'View coverage map'}
                variant="secondary"
                size="sm"
                icon={locationsOpen ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
              />
            </div>

            {locationsOpen && (
              <div style={{ padding: '16px 24px 24px 24px', backgroundColor: '#f8fafc', borderTop: '1px dashed rgba(5, 54, 89, 0.1)' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '16px', marginBottom: '14px', flexWrap: 'wrap' }}>
                  <div style={{ maxWidth: '400px', flexGrow: 1, minWidth: '240px' }}>
                    <TextInput
                      label="Search locations"
                      isLabelHidden
                      placeholder="Search areas or addresses…"
                      startIcon={<Search size={16} />}
                      hasClear
                      value={locationSearch}
                      onChange={(v) => setLocationSearch(v)}
                    />
                  </div>
                  <Text type="supporting" color="secondary">
                    {filteredSurveys.length} of {providerSurveys.length} serviced location{providerSurveys.length !== 1 ? 's' : ''}
                  </Text>
                </div>

                {filteredSurveys.length === 0 ? (
                  <Card style={{ borderRadius: '12px', border: '1px solid rgba(5, 54, 89, 0.08)', backgroundColor: '#ffffff' }}>
                    <EmptyState title="No matching locations" caption="Try a different search term." />
                  </Card>
                ) : (
                  <div
                    style={{
                      display: 'grid',
                      gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
                      gap: '12px',
                      maxHeight: '420px',
                      overflowY: 'auto',
                      paddingRight: '4px'
                    }}
                  >
                    {filteredSurveys.map((s, idx) => {
                      const title = s.area || s.address || 'Unknown area';
                      const subtitle = s.area && s.address ? s.address : null;
                      const mapQuery = s.plus_code ? `${s.plus_code} ${s.address || ''}`.trim() : (s.address || s.area);
                      const mapUrl = mapQuery ? `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(mapQuery)}` : undefined;
                      return (
                        <div
                          key={s.id ?? idx}
                          style={{
                            borderRadius: '10px',
                            border: '1px solid rgba(5, 54, 89, 0.08)',
                            backgroundColor: '#ffffff',
                            overflow: 'hidden'
                          }}
                          className={mapUrl ? 'location-card' : ''}
                        >
                          <Item
                            label={title}
                            description={subtitle}
                            labelLines={1}
                            descriptionLines={2}
                            align="start"
                            startContent={<Icon icon={MapPin} size="sm" color="secondary" />}
                            endContent={mapUrl ? <Icon icon="externalLink" size="xsm" color="secondary" /> : undefined}
                            href={mapUrl}
                            target={mapUrl ? '_blank' : undefined}
                            rel={mapUrl ? 'noopener noreferrer' : undefined}
                          />
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            )}
          </Card>
        )}

        {/* Pricing Data Matrix */}
        <Card style={{ padding: '0', borderRadius: '16px', border: '1px solid rgba(5, 54, 89, 0.08)', backgroundColor: '#ffffff', overflow: 'hidden', boxShadow: '0 10px 30px -5px rgba(0,0,0,0.02), 0 4px 12px -3px rgba(0,0,0,0.02)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '12px', padding: '20px 24px', borderBottom: '1px solid rgba(5, 54, 89, 0.06)', background: 'linear-gradient(90deg, rgba(10, 19, 23, 0.03) 0%, #ffffff 70%)', flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <div style={{ width: '40px', height: '40px', borderRadius: '8px', backgroundColor: 'rgba(10, 19, 23, 0.08)', color: '#0A1317', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <LayoutGrid size={18} />
              </div>
              <div>
                <Heading level={4}>Rate Matrix</Heading>
                <Text type="supporting" color="secondary">Weight slab × zone pricing grid{selectedProvider ? ` for ${selectedProvider}` : ''}</Text>
              </div>
            </div>
            {!loading && providerZones.length > 0 && (
              <div style={{ display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' }}>
                <Badge variant="info" label={`${displaySlabs.length} slab${displaySlabs.length !== 1 ? 's' : ''}`} />
                <Badge variant="neutral" label={`${providerZones.length} zone${providerZones.length !== 1 ? 's' : ''}`} />
              </div>
            )}
          </div>

          {loading ? (
            <div style={{ display: 'flex', justifyContent: 'center', padding: '48px 0' }}>
              <div className="spinner" style={{ width: '32px', height: '32px', border: '3px solid #f1f5f9', borderTop: '3px solid #0A1317', borderRadius: '50%', animation: 'spin 1s linear infinite' }} />
            </div>
          ) : providerZones.length === 0 ? (
            <EmptyState title="No pricing data for this provider yet" caption="Add a rate to start building the pricing matrix." />
          ) : displaySlabs.length === 0 ? (
            <EmptyState title="No weight slabs match your search" caption="Try a different search term." />
          ) : (
            <Table
              data={matrixData}
              columns={matrixColumns}
              idKey="slab"
              density="spacious"
              dividers="grid"
              hasHover
              isStriped
            />
          )}
        </Card>
      </div>

      <PricingFormDialog
        open={formOpen}
        onClose={() => setFormOpen(false)}
        onSave={() => loadData()}
        initialData={editingRecord}
        isCell={isCellEdit}
        pricingList={pricingList}
        providerColumns={providerZones}
        providerUsesServiceType={providerUsesServiceType}
      />
      <style>{`
        /* Rate matrix cells: no global "edit mode" toggle anymore — hovering
           a specific slab/zone cell reveals a small edit button just for
           that cell, so editing is always inline and per-cell. No background
           tint on hover, just the icon. */
        .matrix-cell-edit {
          position: absolute;
          right: 4px;
          top: 50%;
          transform: translateY(-50%);
          display: flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          border-radius: 6px;
          border: 1px solid rgba(5, 54, 89, 0.1);
          background-color: #ffffff;
          box-shadow: 0 2px 6px rgba(15, 23, 42, 0.12);
          color: #0A1317;
          cursor: pointer;
          opacity: 0;
          pointer-events: none;
          transition: opacity 0.15s ease, background-color 0.15s ease;
        }
        .matrix-cell:hover .matrix-cell-edit {
          opacity: 1;
          pointer-events: auto;
        }
        .matrix-cell-edit:hover {
          background-color: rgba(10, 19, 23, 0.08) !important;
        }
        .location-card {
          transition: border-color 0.15s ease, box-shadow 0.15s ease;
        }
        .location-card:hover {
          border-color: rgba(10, 19, 23, 0.3) !important;
          box-shadow: 0 4px 12px rgba(10, 19, 23, 0.08);
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}
