const { useEffect, useMemo, useState } = React;

const API = "./api";
const districts = ["Miraflores", "Surco", "San Isidro", "San Miguel", "La Molina", "Jesus Maria", "Magdalena", "Barranco", "Lince", "Pueblo Libre"];
const urgencyOptions = ["baja", "media", "alta"];
const requestStatuses = ["new", "reviewed", "contacted", "closed"];
const categoryInsights = {
  Carpinteria: {
    range: "Desde S/ 80 a S/ 350 segun ajuste, reparacion o instalacion.",
    includes: ["Ajuste de puertas y bisagras", "Reparacion de muebles", "Instalacion de repisas o accesorios"],
    tip: "Envia fotos del mueble o puerta para que el tecnico estime materiales y tiempo antes de visitarte.",
  },
  Cerrajeria: {
    range: "Desde S/ 60 a S/ 220 segun apertura, cambio de chapa o nivel de seguridad.",
    includes: ["Apertura de puertas", "Cambio de chapas", "Mejora de seguridad domestica"],
    tip: "Indica si la cerradura es simple, multipunto o digital para evitar cotizaciones incompletas.",
  },
  Electricidad: {
    range: "Desde S/ 70 a S/ 300 segun punto electrico, luminaria o tablero.",
    includes: ["Instalacion de tomacorrientes", "Cambio de luminarias", "Revision de llaves y tableros"],
    tip: "Si hay chispas, olor a quemado o cortes recurrentes, solicita atencion prioritaria.",
  },
  Gasfiteria: {
    range: "Desde S/ 70 a S/ 280 segun fuga, griferia, desatoro o conexion.",
    includes: ["Reparacion de fugas", "Cambio de griferias", "Desatoros y conexiones de agua"],
    tip: "Cierra la llave de paso si hay fuga activa y comparte una foto o video corto del problema.",
  },
  Limpieza: {
    range: "Desde S/ 90 a S/ 300 segun area, profundidad y horas requeridas.",
    includes: ["Limpieza profunda", "Mantenimiento por horas", "Apoyo para mudanza o post obra"],
    tip: "Indica metraje aproximado, cantidad de ambientes y si necesitas insumos incluidos.",
  },
  "Mantenimiento general": {
    range: "Desde S/ 80 a S/ 320 segun cantidad de tareas y complejidad.",
    includes: ["Ajustes menores del hogar", "Instalaciones simples", "Revision preventiva"],
    tip: "Agrupa varias tareas pequenas en una sola visita para aprovechar mejor el costo de traslado.",
  },
  Pintura: {
    range: "Desde S/ 180 por ambiente pequeno; varia por metraje, resanes y acabado.",
    includes: ["Pintado de ambientes", "Resanes menores", "Acabados y retoques"],
    tip: "Define si necesitas solo mano de obra o tambien materiales para comparar cotizaciones de forma justa.",
  },
  "Reparaciones menores": {
    range: "Desde S/ 60 a S/ 200 segun tiempo, herramientas y materiales.",
    includes: ["Ajustes rapidos", "Instalaciones pequenas", "Correcciones de uso diario"],
    tip: "Describe cada tarea por separado para que el tecnico confirme si puede resolverlas en una visita.",
  },
};
const experienceOptions = [
  { label: "0 a 5 anos", value: "0" },
  { label: "5 a 10 anos", value: "5" },
  { label: "Mas de 10 anos", value: "10" },
];
const dayOptions = ["Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"];
const scheduleOptions = ["Manana", "Tarde", "Noche", "Horario completo", "Emergencias", "Previa coordinacion"];

function apiUrl(path) {
  return `${API}/${path}`;
}

async function requestJson(path, options = {}) {
  const response = await fetch(apiUrl(path), {
    headers: { "Content-Type": "application/json", ...(options.headers || {}) },
    credentials: "include",
    ...options,
  });
  const data = await response.json();
  if (!response.ok || data.success === false) {
    throw new Error(data.message || "No se pudo completar la accion.");
  }
  return data;
}

function formatExperience(value) {
  const found = experienceOptions.find((item) => item.value === String(value));
  return found ? found.label : `${value} anos`;
}

function MultiSelect({ label, options, selected, onChange, placeholder = "Buscar y seleccionar" }) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const filteredOptions = options.filter((option) => option.toLowerCase().includes(query.toLowerCase()));

  function toggle(option) {
    if (selected.includes(option)) {
      onChange(selected.filter((item) => item !== option));
      return;
    }
    onChange([...selected, option]);
  }

  return (
    <label className="multiSelectLabel">
      {label}
      <div className="multiSelect">
        <button type="button" className="multiSelectTrigger" onClick={() => setOpen(!open)}>
          <span>{selected.length ? selected.join(", ") : placeholder}</span>
          <span aria-hidden="true">v</span>
        </button>
        {open && (
          <div className="multiSelectMenu">
            <input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Buscar..." />
            <div className="multiSelectOptions">
              {filteredOptions.map((option) => (
                <button type="button" key={option} className={selected.includes(option) ? "selected" : ""} onClick={() => toggle(option)}>
                  <span>{selected.includes(option) ? "OK" : ""}</span>
                  {option}
                </button>
              ))}
              {!filteredOptions.length && <p className="empty smallEmpty">Sin resultados.</p>}
            </div>
          </div>
        )}
      </div>
    </label>
  );
}

function ServiceGlyph({ name }) {
  const key = (name || "").toLowerCase();
  const common = { fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" };
  let paths = (
    <>
      <path {...common} d="M5 11l7-6 7 6" />
      <path {...common} d="M7 10v9h10v-9" />
    </>
  );

  if (key.includes("gasf")) {
    paths = <><path {...common} d="M8 4v6a4 4 0 0 0 8 0V4" /><path {...common} d="M12 14v6" /><path {...common} d="M9 20h6" /></>;
  } else if (key.includes("elect")) {
    paths = <><path {...common} d="M13 2L6 13h6l-1 9 7-12h-6z" /></>;
  } else if (key.includes("pint")) {
    paths = <><path {...common} d="M5 5h11a2 2 0 0 1 0 4H9v4" /><path {...common} d="M9 13h3v7H9z" /></>;
  } else if (key.includes("cerra")) {
    paths = <><circle {...common} cx="8" cy="9" r="4" /><path {...common} d="M11 12l8 8" /><path {...common} d="M16 17l2-2" /><path {...common} d="M18 19l2-2" /></>;
  } else if (key.includes("limp")) {
    paths = <><path {...common} d="M5 14l6-10 6 10" /><path {...common} d="M7 14h10l-1 6H8z" /></>;
  } else if (key.includes("carp")) {
    paths = <><path {...common} d="M4 18L16 6" /><path {...common} d="M14 4l6 6" /><path {...common} d="M3 21l5-1 11-11-4-4L4 16z" /></>;
  } else if (key.includes("mantenimiento")) {
    paths = <><path {...common} d="M14 7l3-3 3 3-3 3z" /><path {...common} d="M4 20l8-8" /><path {...common} d="M8 8l8 8" /></>;
  } else if (key.includes("repar")) {
    paths = <><path {...common} d="M15 6l3-3 3 3-3 3" /><path {...common} d="M18 9L9 18l-4 1 1-4 9-9" /></>;
  }

  return <svg viewBox="0 0 24 24" aria-hidden="true">{paths}</svg>;
}

function Header() {
  return (
    <header className="topbar">
      <a className="brand" href="/" aria-label="Hogar360 inicio">
        <img className="brandLogo" src="/assets/img/hogar360.png" alt="Hogar360, plataforma de técnicos confiables" />
      </a>
      <nav>
        <a href="/servicios">Servicios</a>
        <a href="/blog">Blog</a>
        <a className="technicianCta" href="/soy-tecnico">¿Eres Técnico?</a>
      </nav>
    </header>
  );
}

function SiteFooter() {
  return (
    <footer className="siteFooter">
      <div className="footerGrid">
        <div>
          <a className="footerBrand" href="/">
            <img className="footerLogo" src="/assets/img/hogar360.png" alt="Hogar360" />
          </a>
          <p>Hogar360 conecta personas que necesitan servicios para el hogar con tecnicos independientes aprobados, de forma simple, cercana y confiable.</p>
        </div>
        <div>
          <h3>Enlaces utiles</h3>
          <a href="/servicios">Servicios para el hogar</a>
          <a href="/blog">Blog</a>
          <a href="/libro-reclamaciones">Libro de Reclamaciones</a>
          <a href="/terminos-condiciones">Terminos y Condiciones</a>
          <a href="/politica-privacidad">Politica de Privacidad</a>
          <a href="/politica-pagos">Politica de pagos, cancelaciones y devoluciones</a>
        </div>
        <div>
          <h3>Contacto</h3>
          <a href="/contacto">Contacta con Hogar360</a>
          <a href="mailto:soporte@360hogar.com">soporte@360hogar.com</a>
          <a href="https://wa.me/51963542613" target="_blank" rel="noopener noreferrer">WhatsApp +51 963 542 613</a>
          <div className="socialLinks" aria-label="Redes sociales">
            <a href="#" aria-label="Instagram">IG</a>
            <a href="#" aria-label="LinkedIn">IN</a>
            <a href="#" aria-label="Facebook">FB</a>
            <a href="#" aria-label="TikTok">TT</a>
          </div>
        </div>
      </div>
      <div className="footerBottom">© 2026 Hogar360 — Todos los derechos reservados.</div>
    </footer>
  );
}

function Hero({ categories, filters, setFilters, onRequest }) {
  return (
    <section id="inicio" className="hero">
      <div className="heroText">
        <p className="eyebrow">Servicios para cuidar tu hogar, en un solo lugar</p>
        <h1>Encuentra técnicos confiables para tu hogar en Lima</h1>
        <p className="lead">Gasfiteros, electricistas, pintores y especialistas verificados cerca de ti.</p>
        <div className="heroActions">
          <button className="primary" onClick={() => onRequest(null, filters)}>Solicitar servicio</button>
          <a className="secondaryButton" href="/soy-tecnico">Soy tecnico</a>
        </div>
      </div>
      <div className="searchPanel" aria-label="Buscador de servicios">
        <div className="searchPanelHeader">
          <p className="eyebrow">Busqueda rapida</p>
          <h2>Solicita un servicio</h2>
          <p>Filtra el directorio o registra tu solicitud para recibir tecnicos recomendados.</p>
        </div>
        <label>
          Servicio
          <select value={filters.category} onChange={(event) => setFilters({ ...filters, category: event.target.value })}>
            <option value="">Todos los servicios</option>
            {categories.map((category) => <option key={category.id} value={category.name}>{category.name}</option>)}
          </select>
        </label>
        <label>
          Distrito
          <select value={filters.district} onChange={(event) => setFilters({ ...filters, district: event.target.value })}>
            <option value="">Todos los distritos</option>
            {districts.map((district) => <option key={district} value={district}>{district}</option>)}
          </select>
        </label>
        <div className="searchPanelActions">
          <button className="primary full" onClick={() => onRequest(null, filters)}>Solicitar con busqueda guiada</button>
          <a className="secondary full" href="#tecnicos">Ver tecnicos filtrados</a>
        </div>
      </div>
    </section>
  );
}

function CategoryDescriptionModal({ category, onClose, onExplore }) {
  if (!category) return null;
  const insight = categoryInsights[category.name] || {
    range: "El costo depende del alcance, materiales y urgencia del servicio.",
    includes: ["Revision del problema", "Cotizacion segun alcance", "Coordinacion directa con el tecnico"],
    tip: "Describe el problema con detalle y adjunta fotos cuando contactes al tecnico.",
  };
  return (
    <div className="modalBackdrop" role="dialog" aria-modal="true" onClick={onClose}>
      <div className="servicePopup" onClick={(event) => event.stopPropagation()}>
        <div className="modalHeader">
          <div className="popupTitle">
            <span className="serviceIcon large"><ServiceGlyph name={category.name} /></span>
            <div>
              <p className="eyebrow">Servicio</p>
              <h2>{category.name}</h2>
            </div>
          </div>
          <button className="ghost small" onClick={onClose}>Cerrar</button>
        </div>
        <p>{category.description}</p>
        <div className="serviceInsightGrid">
          <div className="serviceInsightBox highlight">
            <span className="eyebrow">Referencia</span>
            <strong>{insight.range}</strong>
          </div>
          <div className="serviceInsightBox">
            <span className="eyebrow">Suele incluir</span>
            <ul>
              {insight.includes.map((item) => <li key={item}>{item}</li>)}
            </ul>
          </div>
          <div className="serviceInsightBox">
            <span className="eyebrow">Consejo rapido</span>
            <p>{insight.tip}</p>
          </div>
        </div>
        <div className="modalActions">
          <button className="primary" onClick={() => onExplore(category.name)}>Ver tecnicos disponibles</button>
          <button className="secondary" onClick={onClose}>Regresar</button>
        </div>
      </div>
    </div>
  );
}

function CategoryGrid({ categories, onExploreCategory }) {
  const [selectedCategory, setSelectedCategory] = useState(null);
  const steps = [
    "Describe tu problema.",
    "Elige servicio, distrito y fecha.",
    "Te conectamos con un tecnico disponible.",
    "Recibe el servicio y califica la experiencia.",
  ];

  return (
    <section id="servicios" className="section serviceGuide">
      <div className="serviceGuidePanel">
        <div className="sectionHeader">
          <p className="eyebrow">Categorias</p>
          <h2>Servicios para el hogar en Lima</h2>
        </div>
        <div className="serviceList">
          {categories.map((category) => (
            <button className="serviceItem" key={category.id} onClick={() => setSelectedCategory(category)}>
              <span className="serviceIcon"><ServiceGlyph name={category.name} /></span>
              <span>{category.name}</span>
            </button>
          ))}
        </div>
      </div>
      <div className="serviceGuidePanel">
        <div className="sectionHeader">
          <p className="eyebrow">Pasos</p>
          <h2>Como funciona Hogar360</h2>
        </div>
        <div className="processGraphic" aria-label="Pasos para solicitar un servicio">
          {steps.map((step, index) => (
            <div className={`processStep processStep${index + 1}`} key={step}>
              <span>{index + 1}</span>
              <p>{step}</p>
            </div>
          ))}
          <div className="processCenter">H360</div>
        </div>
      </div>
      <CategoryDescriptionModal category={selectedCategory} onClose={() => setSelectedCategory(null)} onExplore={(categoryName) => {
        setSelectedCategory(null);
        onExploreCategory(categoryName);
      }} />
    </section>
  );
}

function SeoHomeSection() {
  return (
    <section className="section seoHomeSection" aria-labelledby="seo-services-title">
      <div>
        <p className="eyebrow">Hogar360 en Lima</p>
        <h2 id="seo-services-title">Servicios para el hogar en Lima</h2>
      </div>
      <div className="seoHomeCopy">
        <p>Hogar360 conecta a personas que necesitan resolver problemas del hogar con tecnicos y especialistas en gasfiteria, electricidad, pintura, cerrajeria, limpieza, carpinteria y mantenimiento general.</p>
        <p>Nuestro objetivo es facilitar la busqueda de tecnicos confiables, revisados y disponibles para atender servicios en Lima, ayudando a los usuarios a comparar perfiles, solicitar citas y reducir la incertidumbre al momento de contratar.</p>
        <div className="seoServiceLinks" aria-label="Servicios principales">
          <a href="/servicios/gasfiteria">Gasfiteros en Lima</a>
          <a href="/servicios/electricidad">Electricistas en Lima</a>
          <a href="/servicios/pintura">Pintores en Lima</a>
          <a href="/servicios/cerrajeria">Cerrajeros en Lima</a>
          <a href="/servicios/limpieza">Limpieza del hogar</a>
          <a href="/servicios/mantenimiento-general">Mantenimiento del hogar</a>
        </div>
      </div>
    </section>
  );
}

function ProviderDirectory({ providers, onRequest, filters, setFilters, categories }) {
  const [page, setPage] = useState(0);
  const [activeProvider, setActiveProvider] = useState(null);
  const filtered = useMemo(() => providers.filter((provider) => {
    const byCategory = !filters.category || provider.category === filters.category;
    const byDistrict = !filters.district || provider.district === filters.district || provider.service_area?.includes(filters.district);
    return byCategory && byDistrict;
  }), [providers, filters]);
  const totalPages = Math.max(1, Math.ceil(filtered.length / 3));
  const visibleProviders = filtered.slice(page * 3, page * 3 + 3);

  useEffect(() => {
    setPage(0);
  }, [filters.category, filters.district, providers.length]);

  function previousPage() {
    setPage((current) => Math.max(0, current - 1));
  }

  function nextPage() {
    setPage((current) => Math.min(totalPages - 1, current + 1));
  }

  return (
    <section id="tecnicos" className="section">
      <div className="sectionHeader row">
        <div>
          <p className="eyebrow">Directorio verificado</p>
          <h2>Tecnicos destacados</h2>
        </div>
        <div className="inlineFilters">
          <select value={filters.category} onChange={(event) => setFilters({ ...filters, category: event.target.value })}>
            <option value="">Servicio</option>
            {categories.map((category) => <option key={category.id} value={category.name}>{category.name}</option>)}
          </select>
          <select value={filters.district} onChange={(event) => setFilters({ ...filters, district: event.target.value })}>
            <option value="">Distrito</option>
            {districts.map((district) => <option key={district} value={district}>{district}</option>)}
          </select>
        </div>
      </div>
      <div className="providerCarousel">
        <div className="providerGrid">
          {visibleProviders.map((provider) => (
            <article className="providerCard compactProviderCard" key={provider.id}>
              <div className="providerPhoto">{provider.photo_url ? <img src={provider.photo_url} loading="lazy" alt={`${provider.full_name}, tecnico de ${provider.category} en Lima`} /> : provider.full_name.slice(0, 1)}</div>
              <div className="providerCardBody">
                <span className="badge">Aprobado</span>
                <strong className="providerCompactName">{provider.full_name}</strong>
                <h3>{provider.category}</h3>
                <p>{provider.service_area || provider.district}</p>
                <div className="providerMiniFacts">
                  <span>{formatExperience(provider.experience_years)}</span>
                  <span>{provider.reference_price || "Tarifa por evaluar"}</span>
                </div>
              </div>
              <button className="secondary full" onClick={() => setActiveProvider(provider)}>Ver ficha</button>
            </article>
          ))}
          {!filtered.length && <p className="empty">Aun no hay tecnicos aprobados con esos filtros.</p>}
        </div>
        {filtered.length > 3 && (
          <div className="carouselControls">
            <button className="ghost small" onClick={previousPage} disabled={page === 0}>Anterior</button>
            <span>{page + 1} de {totalPages}</span>
            <button className="ghost small" onClick={nextPage} disabled={page >= totalPages - 1}>Siguiente</button>
          </div>
        )}
      </div>
      <ProviderProfileModal
        provider={activeProvider}
        onClose={() => setActiveProvider(null)}
        onRequest={(provider) => {
          setActiveProvider(null);
          onRequest(provider);
        }}
      />
    </section>
  );
}

function ProviderProfileModal({ provider, onClose, onRequest }) {
  if (!provider) return null;
  return (
    <div className="modalBackdrop" role="dialog" aria-modal="true" onClick={onClose}>
      <div className="providerModal" onClick={(event) => event.stopPropagation()}>
        <div className="modalHeader">
          <div className="popupTitle">
            <div className="providerAvatar">{provider.photo_url ? <img src={provider.photo_url} alt={provider.full_name} /> : provider.full_name.slice(0, 1)}</div>
            <div>
              <span className="badge">Aprobado</span>
              <h2>{provider.full_name}</h2>
            </div>
          </div>
          <button className="ghost small" onClick={onClose}>Regresar</button>
        </div>
        <div className="providerDetails">
          <p><strong>Categoria:</strong> {provider.category}</p>
          <p><strong>Oficio:</strong> {provider.trade}</p>
          <p><strong>Distrito base:</strong> {provider.district}</p>
          <p><strong>Zonas de atencion:</strong> {provider.service_area || provider.district}</p>
          <p><strong>Experiencia:</strong> {formatExperience(provider.experience_years)}</p>
          <p><strong>Disponibilidad:</strong> {provider.availability || "Por coordinar"}</p>
          <p><strong>Tarifa referencial:</strong> {provider.reference_price || "Por evaluar"}</p>
          <p><strong>Descripcion:</strong> {provider.description}</p>
          <p><strong>Calificacion:</strong> 4.8</p>
        </div>
        <div className="modalActions">
          <button className="primary" onClick={() => onRequest(provider)}>Solicitar cita</button>
          <button className="secondary" onClick={onClose}>Regresar</button>
        </div>
      </div>
    </div>
  );
}

function RequestModal({ open, categories, providers, selectedProvider, initialRequest = {}, onClose }) {
  if (!open) return null;
  return (
    <div className="modalBackdrop" role="dialog" aria-modal="true" onClick={onClose}>
      <div className="requestModal" onClick={(event) => event.stopPropagation()}>
        <div className="modalHeader">
          <div>
            <p className="eyebrow">Solicitar servicio</p>
            <h2>Cuentanos que necesitas arreglar</h2>
          </div>
          <button className="ghost small" onClick={onClose}>Cerrar</button>
        </div>
        <ServiceRequestForm categories={categories} providers={providers} selectedProvider={selectedProvider} initialRequest={initialRequest} onDone={onClose} />
      </div>
    </div>
  );
}

function ServiceRequestForm({ categories, providers = [], selectedProvider, initialRequest = {}, onDone }) {
  const [form, setForm] = useState({
    customer_name: "", customer_whatsapp: "", customer_email: "", district: initialRequest.district || "", category: initialRequest.category || "",
    problem_description: "", urgency: "media", preferred_date: "", preferred_start_time: "", preferred_end_time: "", provider_id: selectedProvider?.id || "",
  });
  const [message, setMessage] = useState("");
  const [whatsappUrl, setWhatsappUrl] = useState("");
  const [recommendedProviders, setRecommendedProviders] = useState([]);
  const [selectedRecommendedIds, setSelectedRecommendedIds] = useState([]);
  const [submittedRequest, setSubmittedRequest] = useState(null);
  const [saving, setSaving] = useState(false);
  const isProviderRequest = Boolean(selectedProvider);
  const providerDistricts = useMemo(() => {
    if (!selectedProvider) return districts;
    const serviceAreas = String(selectedProvider.service_area || "")
      .split(",")
      .map((area) => area.trim())
      .filter(Boolean);
    return [...new Set([selectedProvider.district, ...serviceAreas].filter(Boolean))];
  }, [selectedProvider]);
  const categoryExists = categories.some((category) => category.name === selectedProvider?.category);

  useEffect(() => {
    setForm((current) => ({
      ...current,
      provider_id: selectedProvider?.id || "",
      category: selectedProvider?.category || current.category,
      district: providerDistricts.includes(current.district) ? current.district : providerDistricts[0] || current.district,
    }));
  }, [selectedProvider, providerDistricts]);

  function buildWhatsappUrl(provider, requestData) {
    if (!provider?.whatsapp) return "";
    let phone = String(provider.whatsapp).replace(/\D/g, "");
    if (phone.length === 9) {
      phone = `51${phone}`;
    }
    if (phone.length < 9) return "";

    const timeRange = requestData.preferred_start_time || requestData.preferred_end_time
      ? `${requestData.preferred_start_time || "por definir"} - ${requestData.preferred_end_time || "por definir"}`
      : "por coordinar";

    const text = [
      `Hola ${provider.full_name}, te contacto desde Hogar360.`,
      `Necesito un servicio de ${requestData.category}.`,
      `Distrito: ${requestData.district}.`,
      `Fecha tentativa: ${requestData.preferred_date || "por coordinar"}.`,
      `Horario: ${timeRange}.`,
      `Urgencia: ${requestData.urgency}.`,
      `Descripcion: ${requestData.problem_description}.`,
      `Mi nombre es ${requestData.customer_name} y mi WhatsApp es ${requestData.customer_whatsapp}.`,
    ].join("\n");

    return `https://wa.me/${phone}?text=${encodeURIComponent(text)}`;
  }

  function priceValue(provider) {
    const match = String(provider.reference_price || "").match(/\d+/);
    return match ? Number(match[0]) : 999999;
  }

  function providerScore(provider, requestData) {
    let score = 0;
    if (provider.category === requestData.category) score += 100;
    if (provider.district === requestData.district) score += 40;
    if (provider.service_area?.includes(requestData.district)) score += 30;
    if (provider.reference_price) score += 5;
    return score;
  }

  function buildRecommendations(requestData) {
    return providers
      .filter((provider) => provider.category === requestData.category)
      .filter((provider) => provider.district === requestData.district || provider.service_area?.includes(requestData.district))
      .sort((a, b) => {
        const scoreDiff = providerScore(b, requestData) - providerScore(a, requestData);
        return scoreDiff || priceValue(a) - priceValue(b);
      })
      .slice(0, 6);
  }

  function toggleRecommended(id) {
    if (selectedRecommendedIds.includes(id)) {
      setSelectedRecommendedIds(selectedRecommendedIds.filter((item) => item !== id));
      return;
    }
    setSelectedRecommendedIds([...selectedRecommendedIds, id]);
  }

  function openSelectedWhatsappChats() {
    recommendedProviders
      .filter((provider) => selectedRecommendedIds.includes(provider.id))
      .forEach((provider, index) => {
        const url = buildWhatsappUrl(provider, submittedRequest);
        if (url) {
          setTimeout(() => window.open(url, "_blank", "noopener,noreferrer"), index * 250);
        }
      });
  }

  async function submit(event) {
    event.preventDefault();
    setSaving(true);
    setMessage("");
    setWhatsappUrl("");
    setRecommendedProviders([]);
    setSelectedRecommendedIds([]);
    try {
      await requestJson("create_request.php", { method: "POST", body: JSON.stringify(form) });
      const requestSnapshot = { ...form };
      setSubmittedRequest(requestSnapshot);
      const url = buildWhatsappUrl(selectedProvider, requestSnapshot);
      setWhatsappUrl(url);
      if (url) {
        setMessage("Solicitud registrada. Tambien puedes escribirle al tecnico por WhatsApp.");
      } else {
        const recommendations = buildRecommendations(requestSnapshot);
        setRecommendedProviders(recommendations);
        setSelectedRecommendedIds(recommendations.map((provider) => provider.id));
        setMessage(recommendations.length ? "Solicitud registrada. Te recomendamos estos tecnicos disponibles para que puedas contactarlos por WhatsApp." : "Solicitud enviada. No encontramos tecnicos aprobados con esa categoria y distrito por ahora; el administrador revisara tu solicitud.");
      }
      if (!url) {
        if (!buildRecommendations(requestSnapshot).length) {
          setForm({ customer_name: "", customer_whatsapp: "", customer_email: "", district: "", category: "", problem_description: "", urgency: "media", preferred_date: "", preferred_start_time: "", preferred_end_time: "", provider_id: "" });
        }
      }
      if (onDone && !url && !buildRecommendations(requestSnapshot).length) {
        setTimeout(onDone, 1400);
      }
    } catch (error) {
      setMessage(error.message);
    } finally {
      setSaving(false);
    }
  }

  return (
    <form className="form" onSubmit={submit}>
      {selectedProvider && (
        <div className="notice providerRequestNotice">
          <strong>Solicitando cita con {selectedProvider.full_name}</strong>
          <span>Esta solicitud queda limitada a {selectedProvider.category} y a sus zonas de atencion. Si necesitas otro servicio o distrito, regresa y elige otro tecnico.</span>
        </div>
      )}
      <label>Nombre del cliente<input required value={form.customer_name} onChange={(e) => setForm({ ...form, customer_name: e.target.value })} /></label>
      <label>WhatsApp<input required value={form.customer_whatsapp} onChange={(e) => setForm({ ...form, customer_whatsapp: e.target.value })} /></label>
      <label>Correo opcional<input type="email" value={form.customer_email} onChange={(e) => setForm({ ...form, customer_email: e.target.value })} /></label>
      <label>Distrito<select required value={form.district} onChange={(e) => setForm({ ...form, district: e.target.value })}><option value="">Selecciona</option>{providerDistricts.map((district) => <option key={district}>{district}</option>)}</select></label>
      <label>Tipo de servicio<select required disabled={isProviderRequest} value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })}><option value="">Selecciona</option>{isProviderRequest && selectedProvider?.category && !categoryExists && <option value={selectedProvider.category}>{selectedProvider.category}</option>}{categories.map((category) => <option key={category.id}>{category.name}</option>)}</select></label>
      <label>Descripcion del problema<textarea required rows="4" value={form.problem_description} onChange={(e) => setForm({ ...form, problem_description: e.target.value })} /></label>
      <label>Urgencia<select value={form.urgency} onChange={(e) => setForm({ ...form, urgency: e.target.value })}>{urgencyOptions.map((urgency) => <option key={urgency}>{urgency}</option>)}</select></label>
      <div className="dateTimeGroup">
        <label>Fecha tentativa<input type="date" value={form.preferred_date} onChange={(e) => setForm({ ...form, preferred_date: e.target.value })} /></label>
        <div className="timeRange">
          <label>Desde<input type="time" value={form.preferred_start_time} onChange={(e) => setForm({ ...form, preferred_start_time: e.target.value })} /></label>
          <label>Hasta<input type="time" value={form.preferred_end_time} onChange={(e) => setForm({ ...form, preferred_end_time: e.target.value })} /></label>
        </div>
      </div>
      <button className="primary full" disabled={saving}>{saving ? "Enviando..." : "Enviar solicitud"}</button>
      {whatsappUrl && (
        <div className="whatsappActions">
          <a className="whatsappButton" href={whatsappUrl} target="_blank" rel="noopener noreferrer">Contactar por WhatsApp</a>
          <button type="button" className="secondary full" onClick={onDone}>Cerrar</button>
        </div>
      )}
      {recommendedProviders.length > 0 && submittedRequest && (
        <div className="recommendationPanel">
          <h3>Tecnicos recomendados</h3>
          <p>Selecciona a quienes deseas contactar. La solicitud ya quedo registrada para seguimiento del administrador.</p>
          <div className="recommendationList">
            {recommendedProviders.map((provider) => {
              const url = buildWhatsappUrl(provider, submittedRequest);
              return (
                <article className="recommendationItem" key={provider.id}>
                  <label className="recommendationCheck">
                    <input type="checkbox" checked={selectedRecommendedIds.includes(provider.id)} onChange={() => toggleRecommended(provider.id)} />
                    <span>
                      <strong>{provider.full_name}</strong>
                      <small>{provider.category} - {provider.service_area || provider.district} - {provider.reference_price || "Tarifa por evaluar"}</small>
                    </span>
                  </label>
                  {url && <a className="miniWhatsapp" href={url} target="_blank" rel="noopener noreferrer">WhatsApp</a>}
                </article>
              );
            })}
          </div>
          <div className="whatsappActions">
            <button type="button" className="whatsappButton" onClick={openSelectedWhatsappChats}>Abrir WhatsApp seleccionados</button>
            <button type="button" className="secondary full" onClick={onDone}>Cerrar</button>
          </div>
        </div>
      )}
      {message && <p className="formMessage">{message}</p>}
    </form>
  );
}

function ProviderRegistrationForm({ categories }) {
  const [form, setForm] = useState({
    full_name: "", category: "", service_area: [], experience_years: "",
    description: "", whatsapp: "", email: "", availability_days: [], availability_times: [], reference_price: "",
  });
  const [photoFile, setPhotoFile] = useState(null);
  const [message, setMessage] = useState("");

  async function submit(event) {
    event.preventDefault();
    setMessage("");
    try {
      if (!photoFile) {
        setMessage("Adjunta una foto para enviar tu perfil.");
        return;
      }
      if (!form.service_area.length) {
        setMessage("Selecciona al menos una zona de atencion.");
        return;
      }
      if (!form.availability_days.length || !form.availability_times.length) {
        setMessage("Selecciona tus dias y horarios de disponibilidad.");
        return;
      }

      const payload = new FormData();
      payload.append("full_name", form.full_name);
      payload.append("category", form.category);
      payload.append("trade", form.category);
      payload.append("district", form.service_area[0]);
      payload.append("service_area", form.service_area.join(", "));
      payload.append("experience_years", form.experience_years);
      payload.append("description", form.description);
      payload.append("whatsapp", form.whatsapp);
      payload.append("email", form.email);
      payload.append("availability", `${form.availability_days.join(", ")} | ${form.availability_times.join(", ")}`);
      payload.append("reference_price", form.reference_price);
      payload.append("photo", photoFile);

      const response = await fetch(apiUrl("register_provider.php"), {
        method: "POST",
        body: payload,
        credentials: "include",
      });
      const data = await response.json();
      if (!response.ok || data.success === false) {
        throw new Error(data.message || "No se pudo registrar el perfil.");
      }
      setMessage("Tu perfil fue enviado para revision. Cuando sea aprobado, aparecera en la plataforma.");
      setForm({ full_name: "", category: "", service_area: [], experience_years: "", description: "", whatsapp: "", email: "", availability_days: [], availability_times: [], reference_price: "" });
      setPhotoFile(null);
      event.target.reset();
    } catch (error) {
      setMessage(error.message);
    }
  }

  return (
    <form className="form" onSubmit={submit}>
      <label>Nombre completo<input required value={form.full_name} onChange={(e) => setForm({ ...form, full_name: e.target.value })} /></label>
      <label>Categoria<select required value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })}><option value="">Selecciona</option>{categories.map((category) => <option key={category.id}>{category.name}</option>)}</select></label>
      <MultiSelect label="Zonas de atencion" options={districts} selected={form.service_area} onChange={(items) => setForm({ ...form, service_area: items })} placeholder="Selecciona distritos" />
      <label>Anos de experiencia<select required value={form.experience_years} onChange={(e) => setForm({ ...form, experience_years: e.target.value })}><option value="">Selecciona</option>{experienceOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}</select></label>
      <label>Descripcion del servicio<textarea required rows="4" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></label>
      <label>WhatsApp<input required value={form.whatsapp} onChange={(e) => setForm({ ...form, whatsapp: e.target.value })} /></label>
      <label>Correo<input required type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} /></label>
      <MultiSelect label="Dias de disponibilidad" options={dayOptions} selected={form.availability_days} onChange={(items) => setForm({ ...form, availability_days: items })} placeholder="Selecciona dias" />
      <MultiSelect label="Horarios de disponibilidad" options={scheduleOptions} selected={form.availability_times} onChange={(items) => setForm({ ...form, availability_times: items })} placeholder="Selecciona horarios" />
      <label>Tarifa referencial opcional<input value={form.reference_price} onChange={(e) => setForm({ ...form, reference_price: e.target.value })} placeholder="Desde S/ 60" /></label>
      <label>Foto de perfil<input required type="file" accept="image/png,image/jpeg,image/webp" onChange={(e) => setPhotoFile(e.target.files?.[0] || null)} /></label>
      <button className="primary full">Enviar perfil para revision</button>
      {message && <p className="formMessage">{message}</p>}
    </form>
  );
}

function TechnicianSignupPage({ categories }) {
  return (
    <main className="technicianPage">
      <section className="technicianHero">
        <div className="technicianIntro">
          <p className="eyebrow">Registro de tecnicos</p>
          <h1>Haz visible tu perfil profesional.</h1>
          <p>Forma parte del directorio de Hogar360 y recibe solicitudes de clientes que buscan servicios para su hogar.</p>
          <ul>
            <li>Te encuentran por categoria y zona de atencion.</li>
            <li>Un perfil completo genera mas confianza.</li>
            <li>Tu perfil aparece solo despues de ser aprobado.</li>
          </ul>
          <p className="timeNote">Solo toma unos minutos completar el formulario.</p>
        </div>
        <div className="technicianFormPanel">
          <p className="eyebrow">Soy tecnico</p>
          <h2>Registra tu perfil para revision</h2>
          <p className="muted">Completa tus datos para que podamos validar tu perfil antes de publicarlo.</p>
          <ProviderRegistrationForm categories={categories} />
        </div>
      </section>
    </main>
  );
}

function AdminPanel({ open, onClose }) {
  const [session, setSession] = useState(false);
  const [login, setLogin] = useState({ email: "admin@hogar360.pe", password: "password" });
  const [message, setMessage] = useState("");
  const [pending, setPending] = useState([]);
  const [approved, setApproved] = useState([]);
  const [requests, setRequests] = useState([]);

  async function loadAdminData() {
    const [pendingData, approvedData, requestsData] = await Promise.all([
      requestJson("admin_get_pending_providers.php"),
      requestJson("admin_get_providers.php"),
      requestJson("admin_get_requests.php"),
    ]);
    setPending(pendingData.providers || []);
    setApproved(approvedData.providers || []);
    setRequests(requestsData.requests || []);
  }

  async function doLogin(event) {
    event.preventDefault();
    setMessage("");
    try {
      await requestJson("admin_login.php", { method: "POST", body: JSON.stringify(login) });
      setSession(true);
      await loadAdminData();
    } catch (error) {
      setMessage(error.message);
    }
  }

  async function updateProvider(id, status) {
    await requestJson("admin_update_provider_status.php", { method: "POST", body: JSON.stringify({ id, status }) });
    await loadAdminData();
  }

  async function updateRequest(id, status) {
    await requestJson("admin_update_request_status.php", { method: "POST", body: JSON.stringify({ id, status }) });
    await loadAdminData();
  }

  async function logout() {
    await requestJson("admin_logout.php", { method: "POST" });
    setSession(false);
  }

  if (!open) return null;
  return (
    <div className="modalBackdrop" role="dialog" aria-modal="true">
      <div className="adminPanel">
        <div className="modalHeader">
          <h2>Panel administrador</h2>
          <button className="ghost small" onClick={onClose}>Cerrar</button>
        </div>
        {!session ? (
          <form className="form compact" onSubmit={doLogin}>
            <label>Correo<input type="email" value={login.email} onChange={(e) => setLogin({ ...login, email: e.target.value })} /></label>
            <label>Contrasena<input type="password" value={login.password} onChange={(e) => setLogin({ ...login, password: e.target.value })} /></label>
            <button className="primary full">Ingresar</button>
            {message && <p className="formMessage">{message}</p>}
          </form>
        ) : (
          <div className="adminContent">
            <button className="ghost small" onClick={logout}>Cerrar sesion</button>
            <h3>Brindadores pendientes</h3>
            <div className="adminList">{pending.map((provider) => <div className="adminItem" key={provider.id}><strong>{provider.full_name}</strong><span>{provider.trade} - {provider.district}</span><p>{provider.description}</p><button onClick={() => updateProvider(provider.id, "approved")}>Aprobar</button><button className="danger" onClick={() => updateProvider(provider.id, "rejected")}>Rechazar</button></div>)}{!pending.length && <p className="empty">No hay perfiles pendientes.</p>}</div>
            <h3>Brindadores aprobados</h3>
            <div className="adminList">{approved.map((provider) => <div className="adminItem" key={provider.id}><strong>{provider.full_name}</strong><span>{provider.category} - {provider.district}</span></div>)}</div>
            <h3>Solicitudes de clientes</h3>
            <div className="adminList">{requests.map((item) => <div className="adminItem" key={item.id}><strong>{item.customer_name}</strong><span>{item.category} - {item.district} - {item.urgency}</span><p>{item.problem_description}</p><select value={item.status} onChange={(e) => updateRequest(item.id, e.target.value)}>{requestStatuses.map((status) => <option key={status}>{status}</option>)}</select></div>)}{!requests.length && <p className="empty">No hay solicitudes todavia.</p>}</div>
          </div>
        )}
      </div>
    </div>
  );
}

function App() {
  const page = document.getElementById("root")?.dataset.page || "home";
  const [categories, setCategories] = useState([]);
  const [providers, setProviders] = useState([]);
  const [filters, setFilters] = useState({ category: "", district: "" });
  const [selectedProvider, setSelectedProvider] = useState(null);
  const [requestDefaults, setRequestDefaults] = useState({});
  const [showRequest, setShowRequest] = useState(false);
  const [adminOpen, setAdminOpen] = useState(false);

  useEffect(() => {
    requestJson("get_categories.php").then((data) => setCategories(data.categories || [])).catch(console.error);
    requestJson("get_providers.php").then((data) => setProviders(data.providers || [])).catch(console.error);
  }, []);

  useEffect(() => {
    function openAdminFromHash() {
      if (window.location.hash === "#admin") {
        setAdminOpen(true);
      }
    }

    openAdminFromHash();
    window.addEventListener("hashchange", openAdminFromHash);
    return () => window.removeEventListener("hashchange", openAdminFromHash);
  }, []);

  function openRequest(provider, defaults = {}) {
    setSelectedProvider(provider);
    setRequestDefaults(provider ? {} : defaults);
    setShowRequest(true);
  }

  function exploreCategory(categoryName) {
    setFilters({ category: categoryName, district: "" });
    window.location.hash = "tecnicos";
    setTimeout(() => document.getElementById("tecnicos")?.scrollIntoView({ behavior: "smooth" }), 0);
  }

  if (page === "technician") {
    return (
      <>
        <Header />
        <TechnicianSignupPage categories={categories} />
        <SiteFooter />
        <AdminPanel open={adminOpen} onClose={() => setAdminOpen(false)} />
      </>
    );
  }

  return (
    <>
      <Header />
      <main>
        <Hero categories={categories} filters={filters} setFilters={setFilters} onRequest={openRequest} />
        <CategoryGrid categories={categories} onExploreCategory={exploreCategory} />
        <SeoHomeSection />
        <ProviderDirectory providers={providers} categories={categories} filters={filters} setFilters={setFilters} onRequest={openRequest} />
        <section className="section future"><h2>Muy pronto tambien podras organizar mantenimientos, documentos y recordatorios de tu inmueble desde Hogar360.</h2><p>La primera fase conecta hogares con tecnicos. La siguiente ayudara a cuidar todo el ciclo de vida del inmueble.</p></section>
      </main>
      <SiteFooter />
      <RequestModal open={showRequest} categories={categories} providers={providers} selectedProvider={selectedProvider} initialRequest={requestDefaults} onClose={() => { setShowRequest(false); setSelectedProvider(null); setRequestDefaults({}); }} />
      <AdminPanel open={adminOpen} onClose={() => setAdminOpen(false)} />
    </>
  );
}
