'use client';
import { useEffect, useState, Suspense, useCallback } from 'react';
import { slugify } from '@/lib/slugify';
import { useSearchParams, useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import SearchableSelect from '@/components/ui/SearchableSelect';
import api from '@/lib/api';
import { isLoggedIn } from '@/lib/auth';

const TYPES = ['Todos', 'Servicio', 'Producto', 'Urgente'];

const MODALITY_OPTIONS = [
  { val: 'presencial', label: 'Presencial' },
  { val: 'remoto',     label: 'Remoto' },
  { val: 'ambas',      label: 'Ambas' },
];

const SORT_OPTIONS = [
  { val: 'recent',      label: 'Más recientes' },
  { val: 'budget_high', label: 'Mayor presupuesto' },
  { val: 'budget_low',  label: 'Menor presupuesto' },
  { val: 'proposals',   label: 'Más propuestas' },
];

function ExplorarContent() {
  const params = useSearchParams();
  const router = useRouter();
  const routeParams = useParams();
  const catFromRoute = routeParams?.slug    || '';
  const subFromRoute = routeParams?.subslug || '';

  const [reqs, setReqs]         = useState([]);
  const [loading, setLoading]   = useState(true);
  const [tab, setTab]           = useState('Todos');
  const [search, setSearch]           = useState(params.get('q') || '');
  const [appliedSearch, setAppliedSearch] = useState(params.get('q') || '');
  const [drawerOpen, setDrawerOpen] = useState(false);

  // Sync all URL-driven filters when params change (navbar clicks, back/forward)
  useEffect(() => {
    const q = params.get('q') || '';
    setSearch(q);
    setAppliedSearch(q);
    setFilterCategory(catFromRoute);
    setFilterSubcategory(subFromRoute);
    if (categories.length > 0) {
      setPage(1);
      load(1, q, catFromRoute, subFromRoute);
    }
  }, [params, catFromRoute, subFromRoute]); // eslint-disable-line react-hooks/exhaustive-deps
  const [page, setPage]         = useState(1);
  const [total, setTotal]       = useState(0);
  const [sort, setSort]         = useState('recent');

  // Categories — filterCategory/filterSubcategory hold slugs for SEO-friendly URLs
  const [categories, setCategories]       = useState([]);
  const [subcategories, setSubcategories] = useState([]);
  const [filterCategory, setFilterCategory]       = useState(catFromRoute);
  const [filterSubcategory, setFilterSubcategory] = useState(subFromRoute);

  // Resolve a slug to a numeric category ID for API calls
  const slugToId = (slug) => {
    if (!slug) return null;
    for (const c of categories) {
      if (c.slug === slug) return c.id;
      for (const s of (c.children || [])) {
        if (s.slug === slug) return s.id;
      }
    }
    return null;
  };

  // Sidebar filters
  const [filterType, setFilterType]           = useState('');
  const [filterBudgetMin, setFilterBudgetMin] = useState('');
  const [filterBudgetMax, setFilterBudgetMax] = useState('');
  const [filterModality, setFilterModality]   = useState('');
  const [loggedIn, setLoggedIn]               = useState(false);

  // Location filters (cascading)
  const [filterState, setFilterState]         = useState('');
  const [filterCity, setFilterCity]           = useState('');
  const [filterCp, setFilterCp]               = useState('');
  const [filterColonia, setFilterColonia]     = useState('');
  const [stateOptions, setStateOptions]       = useState([]);
  const [cityOptions, setCityOptions]         = useState([]);
  const [cpOptions, setCpOptions]             = useState([]);
  const [coloniaOptions, setColoniaOptions]   = useState([]);

  const limit = 12;

  useEffect(() => { setLoggedIn(isLoggedIn()); }, []);

  // Load states once on mount
  useEffect(() => {
    api.get('/location/states').then(r => setStateOptions(r.data.data || [])).catch(() => {});
  }, []);

  // When estado changes → load cities, reset downstream
  useEffect(() => {
    setCityOptions([]); setFilterCity('');
    setCpOptions([]);   setFilterCp('');
    setColoniaOptions([]); setFilterColonia('');
    if (!filterState) return;
    api.get('/location/cities', { params: { estado: filterState } })
      .then(r => setCityOptions(r.data.data || [])).catch(() => {});
  }, [filterState]); // eslint-disable-line react-hooks/exhaustive-deps

  // When ciudad changes → load CPs, reset downstream
  useEffect(() => {
    setCpOptions([]);   setFilterCp('');
    setColoniaOptions([]); setFilterColonia('');
    if (!filterCity || !filterState) return;
    api.get('/location/cps', { params: { estado: filterState, municipio: filterCity } })
      .then(r => setCpOptions(r.data.data || [])).catch(() => {});
  }, [filterCity]); // eslint-disable-line react-hooks/exhaustive-deps

  // When CP changes → load colonias
  useEffect(() => {
    setColoniaOptions([]); setFilterColonia('');
    if (!filterCp) return;
    api.get(`/location/info/${filterCp}`)
      .then(r => setColoniaOptions(r.data.data?.colonias || [])).catch(() => {});
  }, [filterCp]); // eslint-disable-line react-hooks/exhaustive-deps

  // Load categories once; re-trigger load if a cat filter was in the URL
  useEffect(() => {
    api.get('/categories/tree').then(r => {
      const cats = r.data.data || [];
      setCategories(cats);
      // Now that we have slugs, re-run load so the initial ?cat= filter resolves
      if (filterCategory || filterSubcategory) {
        const resolve = (slug) => {
          for (const c of cats) {
            if (c.slug === slug) return c.id;
            for (const s of (c.children || [])) if (s.slug === slug) return s.id;
          }
          return null;
        };
        const catId = resolve(filterSubcategory) || resolve(filterCategory);
        if (catId) {
          setLoading(true);
          const qParams = { page: 1, limit, sort };
          if (search) qParams.search = search;
          qParams.category_id = catId;
          api.get('/requirements', { params: qParams }).then(r => {
            const d = r.data.data;
            setReqs(Array.isArray(d?.requirements) ? d.requirements : []);
            setTotal(d?.total || 0);
          }).catch(() => setReqs([])).finally(() => setLoading(false));
        }
      }
    }).catch(console.error);
  }, []);

  // When parent category changes, update subcategory list.
  // Skip while categories haven't loaded yet — otherwise this fires on mount before
  // the category tree arrives and wipes a subcategory that came from the URL.
  useEffect(() => {
    if (!filterCategory) { setSubcategories([]); setFilterSubcategory(''); return; }
    if (categories.length === 0) return;
    const parent = categories.find(c => c.slug === filterCategory);
    const subs = parent?.children || [];
    setSubcategories(subs);
    setFilterSubcategory(prev => (prev && subs.some(s => s.slug === prev)) ? prev : '');
  }, [filterCategory, categories]);

  const load = useCallback((p = 1, searchQ, catSlug, subSlug) => {
    const q   = searchQ !== undefined ? searchQ   : search;
    const cat = catSlug !== undefined ? catSlug   : filterCategory;
    const sub = subSlug !== undefined ? subSlug   : filterSubcategory;
    setLoading(true);
    const qParams = { page: p, limit, sort };

    if (q)                qParams.search = q;
    if (tab === 'Servicio') qParams.type = 'service';
    if (tab === 'Producto') qParams.type = 'product';
    if (tab === 'Urgente')  qParams.urgent = true;
    if (filterType)         qParams.type = filterType;

    // Resolve slug → numeric ID for the API
    const catId = slugToId(sub) || slugToId(cat);
    if (catId) qParams.category_id = catId;

    if (filterBudgetMin) qParams.budget_min = filterBudgetMin;
    if (filterBudgetMax) qParams.budget_max = filterBudgetMax;
    if (filterModality)  qParams.modality   = filterModality;
    if (filterState)     qParams.state      = filterState;
    if (filterCity)      qParams.city       = filterCity;
    if (filterCp)        qParams.cp         = filterCp;
    if (filterColonia)   qParams.colonia    = filterColonia;

    api.get('/requirements', { params: qParams })
      .then(r => {
        const d = r.data.data;
        setReqs(Array.isArray(d?.requirements) ? d.requirements : []);
        setTotal(d?.total || 0);
      })
      .catch(() => setReqs([]))
      .finally(() => setLoading(false));
  }, [tab, search, sort, filterCategory, filterSubcategory, filterType, filterBudgetMin, filterBudgetMax, filterModality, filterState, filterCity, filterCp, filterColonia]);

  useEffect(() => { setPage(1); load(1); }, [tab, sort]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => { setPage(1); load(1); }, [filterState, filterCity, filterCp, filterColonia]); // eslint-disable-line react-hooks/exhaustive-deps

  const pushUrl = (cat = filterCategory, sub = filterSubcategory, q = search) => {
    const qs = new URLSearchParams();
    if (q) qs.set('q', q);
    const base = cat ? (sub ? `/explorar/${cat}/${sub}` : `/explorar/${cat}`) : '/explorar';
    router.replace(`${base}${qs.toString() ? '?' + qs.toString() : ''}`, { scroll: false });
  };

  const handleSearch = (e) => { e.preventDefault(); setAppliedSearch(search); pushUrl(filterCategory, filterSubcategory, search); setPage(1); load(1); };
  const clearSearch  = () => { setSearch(''); setAppliedSearch(''); pushUrl(filterCategory, filterSubcategory, ''); setPage(1); load(1, ''); };
  const handleFilter = () => { pushUrl(); setPage(1); load(1); setDrawerOpen(false); };
  const handleClear  = () => {
    setFilterCategory(''); setFilterSubcategory(''); setFilterType('');
    setFilterBudgetMin(''); setFilterBudgetMax(''); setFilterModality('');
    setFilterState(''); setFilterCity(''); setFilterCp(''); setFilterColonia('');
    setCityOptions([]); setCpOptions([]); setColoniaOptions([]);
    setSearch(''); setAppliedSearch('');
    router.replace('/explorar', { scroll: false });
    setTimeout(() => load(1), 0);
  };

  const timeSince = (date) => {
    const m = Math.floor((Date.now() - new Date(date)) / 60000);
    if (m < 60) return `Hace ${m} min`;
    if (m < 1440) return `Hace ${Math.floor(m / 60)}h`;
    return `Hace ${Math.floor(m / 1440)}d`;
  };

  const totalPages = Math.ceil(total / limit);

  return (
    <div className="flex flex-col min-h-screen" style={{ background: '#f0f4f9' }}>
      <Navbar />

      {/* Page header */}
      <div style={{ background: 'linear-gradient(135deg, #1B3A8C 0%, #2a52b8 100%)', color: '#fff', padding: '28px 20px' }}>
        <div className="max-w-6xl mx-auto">
          <h1 className="font-extrabold mb-2" style={{ fontSize: '1.4rem' }}>Explorar solicitudes</h1>
          <p style={{ opacity: .85, fontSize: '.88rem', marginBottom: 16 }}>Encuentra lo que los compradores necesitan y envía tu propuesta</p>
          {/* Search bar */}
          <form onSubmit={handleSearch} style={{ display: 'flex', gap: 10, maxWidth: 560 }}>
            <input
              type="text"
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Buscar por título, descripción o palabras clave…"
              style={{ flex: 1, padding: '10px 16px', borderRadius: 8, border: 'none', fontSize: '.9rem', fontFamily: 'inherit', outline: 'none', color: '#1a1a2e' }}
            />
            <button type="submit" style={{ background: '#F5D800', color: '#1B3A8C', border: 'none', borderRadius: 8, padding: '10px 20px', fontWeight: 800, fontSize: '.88rem', cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>
              Buscar
            </button>
          </form>
        </div>
      </div>

      {/* Quota banner — only for logged-in sellers */}
      {loggedIn && (
        <div className="bg-white border-b border-gray-200">
          <div className="max-w-6xl mx-auto px-5 py-2.5 flex items-center gap-4 flex-wrap">
            <div className="flex items-center gap-2 text-sm font-semibold">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#3dbfbf" strokeWidth="2">
                <line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
              </svg>
              <span>Propuestas hoy: <strong>2 / 5</strong></span>
            </div>
            <div className="flex-1 max-w-44 h-1.5 bg-gray-200 rounded-full overflow-hidden">
              <div className="h-full rounded-full" style={{ width: '40%', background: '#E85C1A' }} />
            </div>
            <span className="text-xs" style={{ color: '#64748b' }}>Plan: <strong>Gratis</strong></span>
            <button onClick={() => router.push('/planes')}
              className="ml-auto text-white font-bold text-xs px-3.5 py-1.5 rounded-lg"
              style={{ background: '#E85C1A', border: 'none', cursor: 'pointer' }}>
              ⚡ Mejorar plan
            </button>
          </div>
        </div>
      )}

      {/* Mobile filter drawer backdrop */}
      {drawerOpen && (
        <div className="fixed inset-0 z-40 md:hidden" style={{ background: 'rgba(0,0,0,.45)' }} onClick={() => setDrawerOpen(false)} />
      )}

      {/* Layout */}
      <style>{`@media(min-width:768px){.explorar-grid{display:grid;grid-template-columns:260px 1fr;gap:20px;align-items:start}}`}</style>
      <div className="explorar-grid max-w-6xl mx-auto w-full px-4 py-6">

        {/* Sidebar — fixed drawer on mobile, static on desktop */}
        <aside className={`fixed top-0 left-0 h-full z-50 overflow-y-auto flex flex-col gap-3.5 transition-transform duration-300 md:static md:translate-x-0 md:h-auto md:z-auto md:overflow-visible ${drawerOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'}`}
          style={{ width: 280, background: '#f0f4f9', padding: '0' }}>
          {/* Drawer header — mobile only */}
          <div className="flex items-center justify-between px-4 py-3 md:hidden" style={{ background: '#1B3A8C', color: '#fff' }}>
            <span style={{ fontWeight: 700, fontSize: '.95rem' }}>Filtros</span>
            <button onClick={() => setDrawerOpen(false)} style={{ background: 'none', border: 'none', color: '#fff', fontSize: '1.3rem', cursor: 'pointer', lineHeight: 1 }}>×</button>
          </div>
          <div className="bg-white rounded-xl border border-gray-200" style={{ padding: 18 }}>
            <h3 className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: '#1B3A8C', letterSpacing: '.04em' }}>
              Filtros
            </h3>

            {/* Tipo */}
            <div className="mb-3.5">
              <label className="block text-xs font-semibold mb-1.5" style={{ color: '#64748b' }}>Tipo</label>
              <select value={filterType} onChange={e => setFilterType(e.target.value)}
                className="w-full text-sm outline-none"
                style={{ border: '1.5px solid #e2e8f0', borderRadius: 7, padding: '7px 10px', fontFamily: 'inherit', width: '100%' }}>
                <option value="">Todos</option>
                <option value="service">Servicios</option>
                <option value="product">Productos</option>
              </select>
            </div>

            {/* Categoría principal */}
            <div className="mb-2">
              <label className="block text-xs font-semibold mb-1.5" style={{ color: '#64748b' }}>Categoría</label>
              <select value={filterCategory} onChange={e => setFilterCategory(e.target.value)}
                className="w-full text-sm outline-none"
                style={{ border: '1.5px solid #e2e8f0', borderRadius: 7, padding: '7px 10px', fontFamily: 'inherit', width: '100%' }}>
                <option value="">Todas las categorías</option>
                {categories.map(c => (
                  <option key={c.id} value={c.slug}>{c.name}</option>
                ))}
              </select>
            </div>

            {/* Subcategoría — aparece cuando hay categoría seleccionada con hijos */}
            {subcategories.length > 0 && (
              <div className="mb-3.5">
                <label className="block text-xs font-semibold mb-1.5" style={{ color: '#64748b' }}>Subcategoría</label>
                <select value={filterSubcategory} onChange={e => setFilterSubcategory(e.target.value)}
                  className="w-full text-sm outline-none"
                  style={{ border: '1.5px solid #1B3A8C', borderRadius: 7, padding: '7px 10px', fontFamily: 'inherit', width: '100%' }}>
                  <option value="">Todas las subcategorías</option>
                  {subcategories.map(s => (
                    <option key={s.id} value={s.slug}>{s.name}</option>
                  ))}
                </select>
              </div>
            )}

            {/* Presupuesto */}
            <div className="mb-3.5">
              <label className="block text-xs font-semibold mb-1.5" style={{ color: '#64748b' }}>Presupuesto (MXN)</label>
              <div className="grid grid-cols-2 gap-2">
                <input type="number" placeholder="Mín" value={filterBudgetMin} onChange={e => setFilterBudgetMin(e.target.value)}
                  className="text-sm outline-none"
                  style={{ border: '1.5px solid #e2e8f0', borderRadius: 7, padding: '7px 10px', fontFamily: 'inherit', width: '100%' }} />
                <input type="number" placeholder="Máx" value={filterBudgetMax} onChange={e => setFilterBudgetMax(e.target.value)}
                  className="text-sm outline-none"
                  style={{ border: '1.5px solid #e2e8f0', borderRadius: 7, padding: '7px 10px', fontFamily: 'inherit', width: '100%' }} />
              </div>
            </div>

            {/* Modalidad */}
            <div className="mb-4">
              <label className="block text-xs font-semibold mb-1.5" style={{ color: '#64748b' }}>Modalidad</label>
              <div className="flex flex-col gap-1.5">
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <input type="radio" name="modality" value="" checked={filterModality === ''}
                    onChange={() => setFilterModality('')}
                    style={{ accentColor: '#1B3A8C' }} />
                  Todas
                </label>
                {MODALITY_OPTIONS.map(m => (
                  <label key={m.val} className="flex items-center gap-2 text-sm cursor-pointer">
                    <input type="radio" name="modality" value={m.val} checked={filterModality === m.val}
                      onChange={() => setFilterModality(m.val)}
                      style={{ accentColor: '#1B3A8C' }} />
                    {m.label}
                  </label>
                ))}
              </div>
            </div>

            {/* Ubicación — cascading */}
            <div className="mb-3.5">
              <label className="block text-xs font-bold uppercase tracking-wider mb-2" style={{ color: '#1B3A8C', letterSpacing: '.04em' }}>Ubicación</label>

              {/* Estado */}
              <div className="mb-2">
                <label className="block text-xs font-semibold mb-1" style={{ color: '#64748b' }}>Estado</label>
                <SearchableSelect value={filterState} onChange={setFilterState} options={stateOptions}
                  placeholder="Todos los estados"
                  style={{ border: '1.5px solid #e2e8f0', borderRadius: 7, padding: '7px 10px', fontSize: '.87rem' }} />
              </div>

              {/* Ciudad — only when estado selected */}
              {filterState && (
                <div className="mb-2">
                  <label className="block text-xs font-semibold mb-1" style={{ color: '#64748b' }}>Ciudad / Municipio</label>
                  <SearchableSelect value={filterCity} onChange={setFilterCity} options={cityOptions}
                    disabled={cityOptions.length === 0}
                    placeholder={cityOptions.length === 0 ? 'Cargando…' : 'Todas las ciudades'}
                    style={{ border: `1.5px solid ${filterCity ? '#1B3A8C' : '#e2e8f0'}`, borderRadius: 7, padding: '7px 10px', fontSize: '.87rem' }} />
                </div>
              )}

              {/* Código Postal — only when ciudad selected */}
              {filterCity && (
                <div className="mb-2">
                  <label className="block text-xs font-semibold mb-1" style={{ color: '#64748b' }}>Código Postal</label>
                  <SearchableSelect value={filterCp} onChange={setFilterCp} options={cpOptions}
                    disabled={cpOptions.length === 0}
                    placeholder={cpOptions.length === 0 ? 'Cargando…' : 'Todos los CPs'}
                    style={{ border: `1.5px solid ${filterCp ? '#1B3A8C' : '#e2e8f0'}`, borderRadius: 7, padding: '7px 10px', fontSize: '.87rem' }} />
                </div>
              )}

              {/* Colonia — only when CP selected and has options */}
              {filterCp && coloniaOptions.length > 0 && (
                <div className="mb-2">
                  <label className="block text-xs font-semibold mb-1" style={{ color: '#64748b' }}>Colonia</label>
                  <SearchableSelect value={filterColonia} onChange={setFilterColonia} options={coloniaOptions}
                    placeholder="Todas las colonias"
                    style={{ border: `1.5px solid ${filterColonia ? '#1B3A8C' : '#e2e8f0'}`, borderRadius: 7, padding: '7px 10px', fontSize: '.87rem' }} />
                </div>
              )}
            </div>

            <button onClick={handleFilter}
              className="w-full text-white font-bold text-sm py-2.5 rounded-lg mb-2"
              style={{ background: '#1B3A8C', border: 'none', cursor: 'pointer' }}>
              Aplicar filtros
            </button>
            <button onClick={handleClear}
              className="w-full text-sm underline"
              style={{ background: 'none', border: 'none', color: '#64748b', cursor: 'pointer', fontFamily: 'inherit' }}>
              Limpiar filtros
            </button>
          </div>
        </aside>

        {/* Main content */}
        <main>
          {/* Mobile filter button */}
          <button onClick={() => setDrawerOpen(true)} className="md:hidden w-full mb-3 flex items-center justify-center gap-2 text-sm font-bold py-2.5 rounded-lg"
            style={{ background: '#1B3A8C', color: '#fff', border: 'none', cursor: 'pointer' }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="4" y1="6" x2="20" y2="6"/><line x1="8" y1="12" x2="16" y2="12"/><line x1="10" y1="18" x2="14" y2="18"/></svg>
            Filtros {(filterCategory || filterSubcategory || filterType || filterBudgetMin || filterBudgetMax) ? '·' : ''} {[filterCategory && categories.find(c=>c.slug===filterCategory)?.name, filterType && (filterType==='service'?'Servicios':'Productos')].filter(Boolean).join(', ')}
          </button>

          {/* Tabs */}
          <div className="flex gap-1 mb-4 bg-white rounded-lg p-1 border border-gray-200">
            {TYPES.map(t => (
              <button key={t} onClick={() => setTab(t)}
                className="flex-1 text-center py-1.5 rounded-md text-sm font-semibold transition"
                style={{
                  background: tab === t ? '#1B3A8C' : 'none',
                  color: tab === t ? '#fff' : '#64748b',
                  border: 'none', cursor: 'pointer', fontFamily: 'inherit',
                }}>
                {t}
              </button>
            ))}
          </div>

          {/* Active filter pills — search + category */}
          {(filterCategory || filterSubcategory || appliedSearch) && (
            <div className="flex items-center gap-2 mb-3 flex-wrap">
              {appliedSearch && (
                <span className="inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-full"
                  style={{ background: '#1B3A8C', color: '#fff' }}>
                  🔍 "{appliedSearch}"
                  <button onClick={clearSearch} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#fff', padding: 0, lineHeight: 1, fontSize: '1rem' }}>×</button>
                </span>
              )}
              {filterCategory && (
                <span className="inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-full"
                  style={{ background: 'rgba(27,58,140,.1)', color: '#1B3A8C' }}>
                  {categories.find(c => c.slug === filterCategory)?.name}
                  {!filterSubcategory && (
                    <button onClick={() => { setFilterCategory(''); setFilterSubcategory(''); pushUrl('', '', appliedSearch); setPage(1); load(1, undefined, '', ''); }}
                      style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#1B3A8C', padding: 0, lineHeight: 1 }}>×</button>
                  )}
                </span>
              )}
              {filterSubcategory && (
                <span className="inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-full"
                  style={{ background: '#1B3A8C', color: '#fff' }}>
                  {subcategories.find(s => s.slug === filterSubcategory)?.name}
                  <button onClick={() => { setFilterSubcategory(''); pushUrl(filterCategory, '', appliedSearch); setPage(1); load(1, undefined, filterCategory, ''); }}
                    style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#fff', padding: 0, lineHeight: 1 }}>×</button>
                </span>
              )}
            </div>
          )}

          {/* Results bar */}
          <div className="flex items-center justify-between mb-3.5 flex-wrap gap-2">
            <div className="text-sm font-semibold" style={{ color: '#64748b' }}>
              Mostrando <span style={{ color: '#1B3A8C' }}>{loading ? '…' : total}</span> solicitudes
            </div>
            <div className="flex items-center gap-2">
              <label className="text-xs font-semibold" style={{ color: '#64748b' }}>Ordenar:</label>
              <select value={sort} onChange={e => setSort(e.target.value)}
                className="text-xs outline-none"
                style={{ border: '1.5px solid #e2e8f0', borderRadius: 7, padding: '6px 10px', fontFamily: 'inherit' }}>
                {SORT_OPTIONS.map(s => <option key={s.val} value={s.val}>{s.label}</option>)}
              </select>
            </div>
          </div>

          {/* Cards */}
          {loading ? (
            <div className="flex flex-col gap-3">
              {Array(6).fill(0).map((_, i) => (
                <div key={i} className="h-28 bg-gray-200 animate-pulse rounded-xl" />
              ))}
            </div>
          ) : reqs.length === 0 ? (
            <div className="text-center py-16" style={{ color: '#64748b' }}>
              <svg className="mx-auto mb-3 opacity-40" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
              </svg>
              <p className="text-sm font-medium">No se encontraron solicitudes</p>
              <p className="text-xs mt-1 opacity-70">Intenta con otros filtros o términos de búsqueda</p>
              {(filterCategory || filterSubcategory || filterBudgetMin || filterBudgetMax) && (
                <button onClick={handleClear} className="mt-4 text-sm font-semibold underline"
                  style={{ color: '#1B3A8C', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
                  Limpiar filtros
                </button>
              )}
            </div>
          ) : (
            <div className="flex flex-col gap-3">
              {reqs.map(r => (
                <div key={r.id}
                  className="bg-white rounded-xl border border-gray-200 transition-all cursor-pointer"
                  style={{ padding: 20 }}
                  onClick={() => router.push(`/solicitud/${r.id}/${slugify(r.title)}`)}
                  onMouseEnter={e => { e.currentTarget.style.borderColor = '#1B3A8C'; e.currentTarget.style.boxShadow = '0 4px 20px rgba(27,58,140,.1)'; }}
                  onMouseLeave={e => { e.currentTarget.style.borderColor = '#e2e8f0'; e.currentTarget.style.boxShadow = 'none'; }}>

                  {/* Top row */}
                  <div className="flex items-start gap-3 mb-3">
                    <div className="flex-shrink-0 flex items-center justify-center rounded-xl text-xl"
                      style={{ width: 44, height: 44, background: '#f4f6fb' }}>
                      📋
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="font-bold text-sm leading-snug mb-0.5" style={{ color: '#1a1a2e' }}>{r.title}</div>
                      <div className="text-xs font-medium" style={{ color: '#64748b' }}>
                        {r.category_name || 'General'}
                      </div>
                    </div>
                    {r.is_urgent && (
                      <span className="text-xs font-extrabold px-2 py-0.5 rounded-full flex-shrink-0"
                        style={{ background: '#fee2e2', color: '#dc2626' }}>
                        URGENTE
                      </span>
                    )}
                  </div>

                  {/* Description */}
                  <p className="text-sm mb-3 leading-relaxed overflow-hidden"
                    style={{ color: '#4a5568', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
                    {r.description}
                  </p>

                  {/* Footer */}
                  <div className="flex items-center gap-2.5 flex-wrap">
                    {r.type && (
                      <span className="text-xs font-semibold px-2.5 py-1 rounded-full"
                        style={r.type === 'service'
                          ? { background: '#eff6ff', color: '#2563eb' }
                          : { background: '#fef3c7', color: '#d97706' }}>
                        {r.type === 'service' ? 'Servicio' : 'Producto'}
                      </span>
                    )}
                    {r.modality && (
                      <span className="text-xs font-semibold px-2.5 py-1 rounded-full"
                        style={{ background: '#f4f6fb', color: '#64748b' }}>
                        {r.modality === 'presencial' ? 'Presencial' : r.modality === 'remoto' ? 'Remoto' : 'Ambas'}
                      </span>
                    )}
                    {(r.city || r.state) && (
                      <div className="flex items-center gap-1 text-xs" style={{ color: '#64748b' }}>
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                          <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/>
                        </svg>
                        {[r.city, r.state].filter(Boolean).join(', ')}
                      </div>
                    )}
                    {r.cp && (
                      <div className="flex items-center gap-1 text-xs" style={{ color: '#64748b' }}>
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                          <rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/>
                        </svg>
                        CP {r.cp}
                      </div>
                    )}
                    <div className="flex items-center gap-1 text-xs" style={{ color: '#64748b' }}>
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
                      </svg>
                      {timeSince(r.created_at)}
                    </div>

                    {r.offer_count > 0 && (
                      <div className="flex items-center gap-1 text-xs" style={{ color: '#64748b' }}>
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                          <line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
                        </svg>
                        {r.offer_count} propuesta{r.offer_count !== 1 ? 's' : ''}
                      </div>
                    )}

                    <div className="ml-auto flex items-center gap-3">
                      {r.budget_min && (
                        <span className="font-extrabold text-sm" style={{ color: '#1B3A8C' }}>
                          ${Number(r.budget_min).toLocaleString('es-MX')}
                          {r.budget_max ? ` – $${Number(r.budget_max).toLocaleString('es-MX')}` : '+'}
                          {' '}MXN
                        </span>
                      )}
                      <Link href={`/solicitud/${r.id}/${slugify(r.title)}`}
                        onClick={e => e.stopPropagation()}
                        className="text-white font-bold text-xs px-4 py-2 rounded-lg transition"
                        style={{ background: '#1B3A8C', textDecoration: 'none', whiteSpace: 'nowrap' }}>
                        Ver y proponer →
                      </Link>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Pagination */}
          {!loading && totalPages > 1 && (
            <div className="flex items-center justify-center gap-1.5 mt-6">
              <button
                onClick={() => { const p = page - 1; setPage(p); load(p); }}
                disabled={page === 1}
                style={{ width: 34, height: 34, borderRadius: 7, border: '1.5px solid #e2e8f0', background: '#fff', color: '#64748b', cursor: page === 1 ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '.9rem', fontWeight: 700, opacity: page === 1 ? .4 : 1 }}>
                ‹
              </button>
              {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => i + 1).map(p => (
                <button key={p}
                  onClick={() => { setPage(p); load(p); }}
                  style={{
                    width: 34, height: 34, borderRadius: 7, cursor: 'pointer',
                    border: p === page ? 'none' : '1.5px solid #e2e8f0',
                    background: p === page ? '#1B3A8C' : '#fff',
                    color: p === page ? '#fff' : '#64748b',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '.88rem', fontWeight: 700,
                  }}>
                  {p}
                </button>
              ))}
              <button
                onClick={() => { const p = page + 1; setPage(p); load(p); }}
                disabled={page >= totalPages}
                style={{ width: 34, height: 34, borderRadius: 7, border: '1.5px solid #e2e8f0', background: '#fff', color: '#64748b', cursor: page >= totalPages ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '.9rem', fontWeight: 700, opacity: page >= totalPages ? .4 : 1 }}>
                ›
              </button>
            </div>
          )}
        </main>
      </div>

      <Footer />
    </div>
  );
}

export default function ExplorarPage() {
  return <Suspense><ExplorarContent /></Suspense>;
}
