"use client";

import { useEffect, useState } from "react";
import Sidebar from "@/components/Sidebar";
import { supabase } from "@/lib/supabase";

type Cliente = {
  id: string | number;
  nombre: string | null;
  telefono: string | null;
  correo: string | null;
};

type Guia = {
  id: string | number;
  numero: string;
  cliente: string | null;
  telefono: string | null;
};

type Recibo = {
  id: string | number;
  guia_id: string | number | null;
  numero: string | null;
  numero_guia: string | null;
  cliente: string | null;
  telefono: string | null;
  destinatario: string | null;
  telefono_destinatario: string | null;
  pais_destino: string | null;
  observaciones: string | null;
  monto: number | null;
  metodo_pago: string | null;
  estado: string | null;
  fecha: string | null;
};

export default function RecibosPage() {
  // =========================================================
  // CLIENTE / DESTINATARIO
  // =========================================================

  const [busquedaDestinatario, setBusquedaDestinatario] =
    useState("");

  const [clientesEncontrados, setClientesEncontrados] =
    useState<Cliente[]>([]);

  const [destinatarioSeleccionado, setDestinatarioSeleccionado] =
    useState<Cliente | null>(null);

  const [mostrarClientes, setMostrarClientes] =
    useState(false);

  const [buscandoCliente, setBuscandoCliente] =
    useState(false);

  // =========================================================
  // GUÍAS
  // =========================================================

  const [guiasEncontradas, setGuiasEncontradas] =
    useState<Guia[]>([]);

  const [guiaSeleccionada, setGuiaSeleccionada] =
    useState<Guia | null>(null);

  const [cargandoGuias, setCargandoGuias] =
    useState(false);

  // =========================================================
  // REMITENTE
  // =========================================================

  const [clienteEnvia, setClienteEnvia] =
    useState("");

  const [telefonoEnvia, setTelefonoEnvia] =
    useState("");

  const [correoEnvia, setCorreoEnvia] =
    useState("");

  // =========================================================
  // DESTINATARIO
  // =========================================================

  const [clienteRecibe, setClienteRecibe] =
    useState("");

  const [telefonoRecibe, setTelefonoRecibe] =
    useState("");

  // =========================================================
  // RECIBO
  // =========================================================

  const [paisDestino, setPaisDestino] =
    useState("Honduras");

  const [observaciones, setObservaciones] =
    useState("");

  const [monto, setMonto] =
    useState("");

  const [estado, setEstado] =
    useState("Pendiente");

  const [metodoPago, setMetodoPago] =
    useState("");

  // =========================================================
  // LISTA DE RECIBOS
  // =========================================================

  const [recibos, setRecibos] =
    useState<Recibo[]>([]);

  const [reciboGenerado, setReciboGenerado] =
    useState<Recibo | null>(null);

  const [reciboImprimir, setReciboImprimir] =
    useState<Recibo | null>(null);

  // =========================================================
  // ESTADOS
  // =========================================================

  const [mensaje, setMensaje] =
    useState("");

  const [guardando, setGuardando] =
    useState(false);

  // =========================================================
  // EDICIÓN
  // =========================================================

  const [reciboEditando, setReciboEditando] =
    useState<Recibo | null>(null);

  const [editCliente, setEditCliente] =
    useState("");

  const [editTelefono, setEditTelefono] =
    useState("");

  const [editDestinatario, setEditDestinatario] =
    useState("");

  const [editTelefonoDestinatario, setEditTelefonoDestinatario] =
    useState("");

  const [editPaisDestino, setEditPaisDestino] =
    useState("Honduras");

  const [editObservaciones, setEditObservaciones] =
    useState("");

  const [editMonto, setEditMonto] =
    useState("");

  const [editEstado, setEditEstado] =
    useState("Pendiente");

  const [editMetodoPago, setEditMetodoPago] =
    useState("");

  const [guardandoEdicion, setGuardandoEdicion] =
    useState(false);

  // =========================================================
  // CARGAR RECIBOS
  // =========================================================

  useEffect(() => {
    cargarRecibos();
  }, []);

  async function cargarRecibos() {
    const { data, error } = await supabase
      .from("hce_recibos")
      .select("*")
      .order("id", {
        ascending: false,
      });

    if (error) {
      console.error(
        "ERROR CARGANDO RECIBOS:",
        error
      );

      setMensaje(
        "Error al cargar recibos: " +
          error.message
      );

      return;
    }

    setRecibos(
      (data || []) as Recibo[]
    );
  }

  // =========================================================
  // BUSCAR QUIÉN RECIBE
  // =========================================================

  async function buscarDestinatario(
    texto: string
  ) {
    setBusquedaDestinatario(texto);

    setDestinatarioSeleccionado(null);
    setGuiasEncontradas([]);
    setGuiaSeleccionada(null);

    setClienteRecibe("");
    setTelefonoRecibe("");

    if (texto.trim().length < 2) {
      setClientesEncontrados([]);
      setMostrarClientes(false);
      return;
    }

    setBuscandoCliente(true);

    const { data, error } = await supabase
      .from("hce_clientes")
      .select(
        "id,nombre,telefono,correo"
      )
      .ilike(
        "nombre",
        `%${texto.trim()}%`
      )
      .order("nombre", {
        ascending: true,
      })
      .limit(10);

    setBuscandoCliente(false);

    if (error) {
      console.error(
        "ERROR BUSCANDO DESTINATARIO:",
        error
      );

      setMensaje(
        "Error buscando destinatario: " +
          error.message
      );

      return;
    }

    setClientesEncontrados(
      (data || []) as Cliente[]
    );

    setMostrarClientes(true);
  }

  // =========================================================
  // SELECCIONAR DESTINATARIO
  // =========================================================

  async function seleccionarDestinatario(
    cliente: Cliente
  ) {
    setDestinatarioSeleccionado(
      cliente
    );

    setBusquedaDestinatario(
      cliente.nombre || ""
    );

    setMostrarClientes(false);
    setClientesEncontrados([]);

    setClienteRecibe(
      cliente.nombre || ""
    );

    setTelefonoRecibe(
      cliente.telefono || ""
    );

    setGuiasEncontradas([]);
    setGuiaSeleccionada(null);

    setCargandoGuias(true);
    setMensaje("");

    // Primero intentamos encontrar guías exactamente
    // relacionadas con el nombre del destinatario.
    const { data, error } = await supabase
      .from("hce_guias")
      .select(
        "id,numero,cliente,telefono"
      )
      .eq(
        "cliente",
        cliente.nombre || ""
      )
      .order("id", {
        ascending: false,
      })
      .limit(20);

    setCargandoGuias(false);

    if (error) {
      console.error(
        "ERROR BUSCANDO GUÍAS:",
        error
      );

      setMensaje(
        "Error buscando las guías: " +
          error.message
      );

      return;
    }

    const guias =
      (data || []) as Guia[];

    setGuiasEncontradas(
      guias
    );

    if (guias.length === 0) {
      setMensaje(
        "El destinatario está registrado, pero no se encontraron guías asociadas."
      );

      return;
    }

    if (guias.length === 1) {
      seleccionarGuia(
        guias[0]
      );

      setMensaje(
        "Destinatario y guía cargados automáticamente."
      );

      return;
    }

    setMensaje(
      "El cliente tiene varias guías. Selecciona la guía correspondiente."
    );
  }

  // =========================================================
  // SELECCIONAR GUÍA
  // =========================================================

  function seleccionarGuia(
    guia: Guia
  ) {
    setGuiaSeleccionada(
      guia
    );

    setClienteRecibe(
      guia.cliente ||
        destinatarioSeleccionado?.nombre ||
        ""
    );

    setTelefonoRecibe(
      guia.telefono ||
        destinatarioSeleccionado?.telefono ||
        ""
    );

    setMensaje(
      "Guía seleccionada correctamente."
    );
  }

  // =========================================================
  // GENERAR NÚMERO DE RECIBO
  // =========================================================

  async function generarNumeroRecibo() {
    const { data, error } = await supabase
      .from("hce_recibos")
      .select("numero")
      .order("id", {
        ascending: false,
      })
      .limit(1);

    if (error) {
      console.error(
        "ERROR OBTENIENDO ÚLTIMO RECIBO:",
        error
      );

      return (
        "REC-" +
        Date.now()
      );
    }

    if (
      !data ||
      data.length === 0 ||
      !data[0]?.numero
    ) {
      return "REC-000001";
    }

    const ultimo =
      String(
        data[0].numero
      );

    const match =
      ultimo.match(
        /(\d+)$/
      );

    if (!match) {
      return (
        "REC-" +
        Date.now()
      );
    }

    const siguiente =
      Number(
        match[1]
      ) + 1;

    return (
      "REC-" +
      String(
        siguiente
      ).padStart(
        6,
        "0"
      )
    );
  }

  // =========================================================
  // GUARDAR RECIBO
  // =========================================================

  async function guardarRecibo(
    e: React.FormEvent<HTMLFormElement>
  ) {
    e.preventDefault();

    setMensaje("");

    if (
      !clienteRecibe.trim()
    ) {
      setMensaje(
        "Primero busca y selecciona quién recibe."
      );

      return;
    }

    if (
      !guiaSeleccionada
    ) {
      setMensaje(
        "Selecciona la guía correspondiente."
      );

      return;
    }

    if (
      !clienteEnvia.trim()
    ) {
      setMensaje(
        "Ingresa quién envía."
      );

      return;
    }

    if (
      !telefonoEnvia.trim()
    ) {
      setMensaje(
        "Ingresa el teléfono de quien envía."
      );

      return;
    }

    if (
      !monto ||
      Number(monto) <= 0
    ) {
      setMensaje(
        "Ingresa un monto válido."
      );

      return;
    }

    if (
      estado === "Pagado" &&
      !metodoPago
    ) {
      setMensaje(
        "Selecciona el método de pago."
      );

      return;
    }

    setGuardando(true);

    try {
      const numero =
        await generarNumeroRecibo();

      const { data, error } =
        await supabase
          .from("hce_recibos")
          .insert([
            {
              guia_id:
                guiaSeleccionada.id,

              numero,

              numero_guia:
                guiaSeleccionada.numero,

              cliente:
                clienteEnvia.trim(),

              telefono:
                telefonoEnvia.trim(),

              destinatario:
                clienteRecibe.trim(),

              telefono_destinatario:
                telefonoRecibe.trim() ||
                null,

              pais_destino:
                paisDestino,

              observaciones:
                observaciones.trim() ||
                null,

              monto:
                Number(monto),

              estado,

              metodo_pago:
                estado === "Pagado"
                  ? metodoPago
                  : null,

              fecha:
                new Date().toISOString(),
            },
          ])
          .select("*")
          .single();

      if (error) {
        console.error(
          "ERROR GUARDANDO RECIBO:",
          error
        );

        setMensaje(
          "Error al guardar recibo: " +
            error.message
        );

        return;
      }

      const recibo =
        data as Recibo;

      setReciboGenerado(
        recibo
      );

      setRecibos(
        (prev) => [
          recibo,
          ...prev,
        ]
      );

      setMensaje(
        "Recibo generado correctamente."
      );
    } catch (error: any) {
      console.error(
        "ERROR GENERAL:",
        error
      );

      setMensaje(
        "Error: " +
          (
            error?.message ||
            "Error desconocido"
          )
      );
    } finally {
      setGuardando(false);
    }
  }

  // =========================================================
  // NUEVO RECIBO
  // =========================================================

  function nuevoRecibo() {
    setReciboGenerado(null);

    setBusquedaDestinatario("");
    setClientesEncontrados([]);
    setDestinatarioSeleccionado(null);
    setMostrarClientes(false);

    setGuiasEncontradas([]);
    setGuiaSeleccionada(null);

    setClienteRecibe("");
    setTelefonoRecibe("");

    setClienteEnvia("");
    setTelefonoEnvia("");
    setCorreoEnvia("");

    setPaisDestino(
      "Honduras"
    );

    setObservaciones("");

    setMonto("");

    setEstado(
      "Pendiente"
    );

    setMetodoPago("");

    setMensaje("");
  }

  // =========================================================
  // DETECTAR TELÉFONO PARA WHATSAPP
  // =========================================================

  function prepararNumeroWhatsApp(
    telefono: string
  ) {
    let numero =
      telefono.replace(
        /\D/g,
        ""
      );

    // Honduras: 8 dígitos
    // 9795-9210
    // 97959210
    if (
      numero.length === 8
    ) {
      return "504" + numero;
    }

    // USA: 10 dígitos
    // 865-389-7216
    // (865) 389-7216
    // 8653897216
    if (
      numero.length === 10
    ) {
      return "1" + numero;
    }

    // Honduras con código de país
    if (
      numero.startsWith("504") &&
      numero.length === 11
    ) {
      return numero;
    }

    // USA con código de país
    if (
      numero.startsWith("1") &&
      numero.length === 11
    ) {
      return numero;
    }

    return null;
  }

  // =========================================================
  // WHATSAPP — SIEMPRE AL QUE ENVÍA
  // =========================================================

  function enviarWhatsApp(
    recibo: Recibo
  ) {
    if (
      !recibo.telefono
    ) {
      alert(
        "El cliente que envía no tiene teléfono registrado."
      );

      return;
    }

    const numero =
      prepararNumeroWhatsApp(
        recibo.telefono
      );

    if (!numero) {
      alert(
        "No se pudo reconocer el teléfono de quien envía. Verifica que tenga 8 dígitos si es Honduras o 10 dígitos si es USA."
      );

      return;
    }

    const guia = recibo.numero_guia || "";

    const enlaceRastreo = guia
      ? `https://hondurascargoexpress.com/?guia=${encodeURIComponent(
          guia
        )}`
      : "";

    const texto =
      `Hola ${recibo.cliente || "cliente"},\n\n` +
      `Honduras Cargo Express le comparte la información de su envío.\n\n` +
      `📦 Guía: ${guia || "-"}\n` +
      `👤 Recibe: ${recibo.destinatario || "-"}\n` +
      `🌎 Destino: ${recibo.pais_destino || "Honduras"}\n\n` +
      (enlaceRastreo
        ? `🔎 RASTREAR ENVÍO:\n${enlaceRastreo}\n\n`
        : "") +
      `Gracias por confiar en Honduras Cargo Express.`;

    const url =
      `https://wa.me/${numero}?text=` +
      encodeURIComponent(
        texto
      );

    window.open(
      url,
      "_blank",
      "noopener,noreferrer"
    );
  }

  // =========================================================
  // IMPRIMIR
  // =========================================================

  function imprimirRecibo(
    recibo: Recibo
  ) {
    setReciboImprimir(
      recibo
    );

    setTimeout(() => {
      window.print();
    }, 400);
  }

  // =========================================================
  // EDITAR
  // =========================================================

  function abrirEditar(
    recibo: Recibo
  ) {
    setReciboEditando(
      recibo
    );

    setEditCliente(
      recibo.cliente || ""
    );

    setEditTelefono(
      recibo.telefono || ""
    );

    setEditDestinatario(
      recibo.destinatario || ""
    );

    setEditTelefonoDestinatario(
      recibo.telefono_destinatario ||
        ""
    );

    setEditPaisDestino(
      recibo.pais_destino ||
        "Honduras"
    );

    setEditObservaciones(
      recibo.observaciones ||
        ""
    );

    setEditMonto(
      String(
        recibo.monto || ""
      )
    );

    setEditEstado(
      recibo.estado ||
        "Pendiente"
    );

    setEditMetodoPago(
      recibo.metodo_pago ||
        ""
    );
  }

  // =========================================================
  // GUARDAR EDICIÓN
  // =========================================================

  async function guardarEdicion() {
    if (
      !reciboEditando
    ) {
      return;
    }

    if (
      !editCliente.trim()
    ) {
      alert(
        "Ingresa quién envía."
      );

      return;
    }

    if (
      !editTelefono.trim()
    ) {
      alert(
        "Ingresa el teléfono de quien envía."
      );

      return;
    }

    if (
      !editDestinatario.trim()
    ) {
      alert(
        "Ingresa quién recibe."
      );

      return;
    }

    if (
      !editMonto ||
      Number(editMonto) <= 0
    ) {
      alert(
        "Ingresa un monto válido."
      );

      return;
    }

    if (
      editEstado === "Pagado" &&
      !editMetodoPago
    ) {
      alert(
        "Selecciona el método de pago."
      );

      return;
    }

    setGuardandoEdicion(
      true
    );

    const { data, error } =
      await supabase
        .from("hce_recibos")
        .update({
          cliente:
            editCliente.trim(),

          telefono:
            editTelefono.trim(),

          destinatario:
            editDestinatario.trim(),

          telefono_destinatario:
            editTelefonoDestinatario.trim() ||
            null,

          pais_destino:
            editPaisDestino,

          observaciones:
            editObservaciones.trim() ||
            null,

          monto:
            Number(editMonto),

          estado:
            editEstado,

          metodo_pago:
            editEstado === "Pagado"
              ? editMetodoPago
              : null,
        })
        .eq(
          "id",
          reciboEditando.id
        )
        .select("*")
        .single();

    setGuardandoEdicion(
      false
    );

    if (error) {
      console.error(
        "ERROR EDITANDO RECIBO:",
        error
      );

      alert(
        "No se pudo editar el recibo: " +
          error.message
      );

      return;
    }

    const actualizado =
      data as Recibo;

    setRecibos(
      (prev) =>
        prev.map(
          (recibo) =>
            recibo.id ===
            actualizado.id
              ? actualizado
              : recibo
        )
    );

    if (
      reciboGenerado &&
      reciboGenerado.id ===
        actualizado.id
    ) {
      setReciboGenerado(
        actualizado
      );
    }

    setReciboEditando(
      null
    );

    setMensaje(
      "Recibo actualizado correctamente."
    );
  }

  // =========================================================
  // BORRAR
  // =========================================================

  async function borrarRecibo(
    recibo: Recibo
  ) {
    const confirmar =
      window.confirm(
        `¿Seguro que deseas borrar el recibo ${recibo.numero || ""} de la guía ${recibo.numero_guia || "-"}?\n\nEsta acción no se puede deshacer.`
      );

    if (!confirmar) {
      return;
    }

    const { error } =
      await supabase
        .from("hce_recibos")
        .delete()
        .eq(
          "id",
          recibo.id
        );

    if (error) {
      console.error(
        "ERROR BORRANDO RECIBO:",
        error
      );

      setMensaje(
        "No se pudo borrar el recibo: " +
          error.message
      );

      return;
    }

    setRecibos(
      (prev) =>
        prev.filter(
          (item) =>
            item.id !==
            recibo.id
        )
    );

    if (
      reciboGenerado &&
      reciboGenerado.id ===
        recibo.id
    ) {
      setReciboGenerado(
        null
      );
    }

    setMensaje(
      "Recibo eliminado correctamente."
    );
  }

  // =========================================================
  // FECHA
  // =========================================================

  function fechaRecibo(
    fecha: string | null
  ) {
    if (!fecha) {
      return "-";
    }

    return new Date(
      fecha
    ).toLocaleString(
      "es-HN",
      {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      }
    );
  }

  // =========================================================
  // IMPRESIÓN TÉRMICA 80MM
  // EXACTAMENTE 2 COPIAS:
  // 1 ORIGINAL
  // 1 COPIA CLIENTE
  // =========================================================

  if (reciboImprimir) {
    return (
      <main className="thermal-print-page">

        <style jsx global>{`
          @page {
            size: 80mm auto;
            margin: 0;
          }

          html,
          body {
            margin: 0 !important;
            padding: 0 !important;
          }

          @media print {
            html,
            body {
              width: 80mm !important;
              margin: 0 !important;
              padding: 0 !important;
              background: white !important;
            }

            body {
              -webkit-print-color-adjust: exact;
              print-color-adjust: exact;
            }

            .no-print {
              display: none !important;
            }

            .thermal-copy {
              display: block !important;
              width: 72mm !important;
              box-sizing: border-box !important;
              margin: 0 auto !important;
              padding: 3mm 2mm !important;
              background: white !important;
              color: black !important;
              font-family: Arial, Helvetica, sans-serif !important;
              font-size: 11px !important;
              line-height: 1.25 !important;
              page-break-after: always !important;
              break-after: page !important;
            }

            .thermal-copy:last-child {
              page-break-after: auto !important;
              break-after: auto !important;
            }

            .thermal-title {
              font-size: 16px !important;
              line-height: 1.05 !important;
            }

            .thermal-subtitle {
              font-size: 12px !important;
            }

            .thermal-section {
              margin-top: 7px !important;
              padding-top: 6px !important;
              border-top: 1px dashed #000 !important;
            }

            .thermal-total {
              margin-top: 8px !important;
              padding: 7px !important;
              border: 1px solid #000 !important;
              font-size: 15px !important;
            }

            .thermal-footer {
              margin-top: 12px !important;
              text-align: center !important;
            }
          }

          @media screen {
            .thermal-print-page {
              min-height: 100vh;
              background: #020617;
              padding: 90px 20px;
            }

            .thermal-copy {
              width: 80mm;
              max-width: 80mm;
              margin: 20px auto;
              padding: 10px;
              background: white;
              color: black;
              font-family: Arial, Helvetica, sans-serif;
              box-sizing: border-box;
            }
          }
        `}</style>

        {/* BARRA DE CONTROL */}

        <div className="no-print fixed left-0 right-0 top-0 z-50 flex flex-wrap items-center justify-center gap-3 bg-slate-900 p-4">

          <button
            type="button"
            onClick={() =>
              window.print()
            }
            className="rounded-xl bg-blue-600 px-6 py-3 font-black text-white hover:bg-blue-500"
          >
            🖨️ IMPRIMIR 2 COPIAS
          </button>

          <button
            type="button"
            onClick={() =>
              enviarWhatsApp(
                reciboImprimir
              )
            }
            className="rounded-xl bg-green-600 px-6 py-3 font-black text-white hover:bg-green-500"
          >
            🟢 WHATSAPP
          </button>

          <button
            type="button"
            onClick={() =>
              setReciboImprimir(
                null
              )
            }
            className="rounded-xl bg-slate-600 px-6 py-3 font-black text-white hover:bg-slate-500"
          >
            VOLVER
          </button>

        </div>

        {/* ===================================================
            ORIGINAL
        =================================================== */}

        <div className="thermal-copy">

          <div className="text-center">

            <div className="thermal-title font-black">
              HONDURAS CARGO EXPRESS
            </div>

            <div className="thermal-subtitle mt-1 font-black">
              RECIBO DE ENVÍO
            </div>

            <div className="mt-1 text-xs font-black">
              ORIGINAL — EMPRESA
            </div>

          </div>

          <div className="thermal-section">

            <div className="flex justify-between">
              <b>RECIBO:</b>
              <span>
                {reciboImprimir.numero ||
                  "-"}
              </span>
            </div>

            <div className="mt-1 flex justify-between">
              <b>FECHA:</b>
              <span>
                {fechaRecibo(
                  reciboImprimir.fecha
                )}
              </span>
            </div>

            <div className="mt-1 flex justify-between">
              <b>GUÍA:</b>
              <b>
                {reciboImprimir.numero_guia ||
                  "-"}
              </b>
            </div>

          </div>

          <div className="thermal-section">

            <b>QUIÉN ENVÍA</b>

            <div className="mt-1 text-sm font-black">
              {reciboImprimir.cliente ||
                "-"}
            </div>

            <div>
              Tel:
              {" "}
              {reciboImprimir.telefono ||
                "-"}
            </div>

          </div>

          <div className="thermal-section">

            <b>QUIÉN RECIBE</b>

            <div className="mt-1 text-sm font-black">
              {reciboImprimir.destinatario ||
                "-"}
            </div>

            <div>
              Tel:
              {" "}
              {reciboImprimir.telefono_destinatario ||
                "-"}
            </div>

          </div>

          <div className="thermal-section">

            <b>DESTINO</b>

            <div className="mt-1">
              {reciboImprimir.pais_destino ||
                "Honduras"}
            </div>

          </div>

          <div className="thermal-section">

            <b>CONTENIDO / OBSERVACIONES</b>

            <div className="mt-1">
              {reciboImprimir.observaciones ||
                "-"}
            </div>

          </div>

          <div className="thermal-section">

            <div className="flex justify-between">
              <b>ESTADO:</b>
              <b>
                {reciboImprimir.estado ||
                  "Pendiente"}
              </b>
            </div>

            <div className="mt-1 flex justify-between">
              <b>MÉTODO:</b>
              <b>
                {reciboImprimir.metodo_pago ||
                  "-"}
              </b>
            </div>

          </div>

          <div className="thermal-total">

            <div className="flex justify-between">

              <b>
                TOTAL
              </b>

              <b>
                $
                {Number(
                  reciboImprimir.monto ||
                    0
                ).toLocaleString(
                  "en-US",
                  {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                  }
                )}
              </b>

            </div>

          </div>

          <div className="mt-10 text-center">

            <div className="mx-auto w-48 border-t border-black" />

            <div className="mt-1 text-[9px]">
              Firma del remitente
            </div>

          </div>

          <div className="thermal-footer">

            <div className="font-bold italic">
              ¡Gracias por preferirnos!
            </div>

            <div className="mt-1 font-black">
              HONDURAS CARGO EXPRESS
            </div>

            <div className="font-bold">
              TU CARGA, NUESTRO COMPROMISO
            </div>

          </div>

        </div>

        {/* ===================================================
            COPIA CLIENTE
        =================================================== */}

        <div className="thermal-copy">

          <div className="text-center">

            <div className="thermal-title font-black">
              HONDURAS CARGO EXPRESS
            </div>

            <div className="thermal-subtitle mt-1 font-black">
              RECIBO DE ENVÍO
            </div>

            <div className="mt-1 text-xs font-black">
              COPIA — CLIENTE
            </div>

          </div>

          <div className="thermal-section">

            <div className="flex justify-between">
              <b>RECIBO:</b>
              <span>
                {reciboImprimir.numero ||
                  "-"}
              </span>
            </div>

            <div className="mt-1 flex justify-between">
              <b>FECHA:</b>
              <span>
                {fechaRecibo(
                  reciboImprimir.fecha
                )}
              </span>
            </div>

            <div className="mt-1 flex justify-between">
              <b>GUÍA:</b>
              <b>
                {reciboImprimir.numero_guia ||
                  "-"}
              </b>
            </div>

          </div>

          <div className="thermal-section">

            <b>QUIÉN ENVÍA</b>

            <div className="mt-1 text-sm font-black">
              {reciboImprimir.cliente ||
                "-"}
            </div>

            <div>
              Tel:
              {" "}
              {reciboImprimir.telefono ||
                "-"}
            </div>

          </div>

          <div className="thermal-section">

            <b>QUIÉN RECIBE</b>

            <div className="mt-1 text-sm font-black">
              {reciboImprimir.destinatario ||
                "-"}
            </div>

            <div>
              Tel:
              {" "}
              {reciboImprimir.telefono_destinatario ||
                "-"}
            </div>

          </div>

          <div className="thermal-section">

            <b>DESTINO</b>

            <div className="mt-1">
              {reciboImprimir.pais_destino ||
                "Honduras"}
            </div>

          </div>

          <div className="thermal-section">

            <b>CONTENIDO / OBSERVACIONES</b>

            <div className="mt-1">
              {reciboImprimir.observaciones ||
                "-"}
            </div>

          </div>

          <div className="thermal-section">

            <div className="flex justify-between">
              <b>ESTADO:</b>
              <b>
                {reciboImprimir.estado ||
                  "Pendiente"}
              </b>
            </div>

            <div className="mt-1 flex justify-between">
              <b>MÉTODO:</b>
              <b>
                {reciboImprimir.metodo_pago ||
                  "-"}
              </b>
            </div>

          </div>

          <div className="thermal-total">

            <div className="flex justify-between">

              <b>
                TOTAL
              </b>

              <b>
                $
                {Number(
                  reciboImprimir.monto ||
                    0
                ).toLocaleString(
                  "en-US",
                  {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                  }
                )}
              </b>

            </div>

          </div>

          <div className="mt-10 text-center">

            <div className="mx-auto w-48 border-t border-black" />

            <div className="mt-1 text-[9px]">
              Firma del remitente
            </div>

          </div>

          <div className="thermal-footer">

            <div className="font-bold italic">
              ¡Gracias por preferirnos!
            </div>

            <div className="mt-1 font-black">
              HONDURAS CARGO EXPRESS
            </div>

            <div className="font-bold">
              TU CARGA, NUESTRO COMPROMISO
            </div>

          </div>

        </div>

      </main>
    );
  }

  // =========================================================
  // RECIBO GENERADO
  // =========================================================

  if (reciboGenerado) {
    return (
      <main className="min-h-screen bg-[#020617] text-white">

        <Sidebar />

        <section className="p-6 pt-28 md:ml-72 md:p-10">

          <div className="rounded-2xl border border-green-500/30 bg-green-500/10 p-6">

            <h2 className="text-2xl font-black text-green-400">
              ✅ RECIBO GENERADO
            </h2>

            <p className="mt-2 text-slate-300">
              Recibo{" "}
              <b>
                {reciboGenerado.numero ||
                  "-"}
              </b>{" "}
              guardado correctamente.
            </p>

            <div className="mt-5 grid gap-4 md:grid-cols-2">

              <div className="rounded-xl bg-slate-900/70 p-5">

                <p className="text-xs font-bold text-slate-400">
                  QUIÉN ENVÍA
                </p>

                <p className="mt-1 text-xl font-black">
                  {reciboGenerado.cliente ||
                    "-"}
                </p>

                <p className="mt-1 text-slate-300">
                  📞{" "}
                  {reciboGenerado.telefono ||
                    "-"}
                </p>

              </div>

              <div className="rounded-xl bg-slate-900/70 p-5">

                <p className="text-xs font-bold text-slate-400">
                  QUIÉN RECIBE
                </p>

                <p className="mt-1 text-xl font-black">
                  {reciboGenerado.destinatario ||
                    "-"}
                </p>

                <p className="mt-1 text-slate-300">
                  📞{" "}
                  {reciboGenerado.telefono_destinatario ||
                    "-"}
                </p>

              </div>

            </div>

            <div className="mt-5 rounded-xl bg-slate-900/70 p-5">

              <p className="text-xs font-bold text-slate-400">
                GUÍA
              </p>

              <p className="text-3xl font-black text-orange-400">
                {reciboGenerado.numero_guia ||
                  "-"}
              </p>

              <p className="mt-3 text-slate-300">
                Destino:{" "}
                <b>
                  {reciboGenerado.pais_destino ||
                    "Honduras"}
                </b>
              </p>

              <p className="mt-2 text-slate-300">
                Contenido:{" "}
                <b>
                  {reciboGenerado.observaciones ||
                    "-"}
                </b>
              </p>

            </div>

            <div className="mt-5 grid gap-3 md:grid-cols-3">

              <button
                type="button"
                onClick={() =>
                  imprimirRecibo(
                    reciboGenerado
                  )
                }
                className="rounded-xl bg-blue-600 p-4 font-black hover:bg-blue-500"
              >
                🖨️ IMPRIMIR 2 COPIAS
              </button>

              <button
                type="button"
                onClick={() =>
                  enviarWhatsApp(
                    reciboGenerado
                  )
                }
                className="rounded-xl bg-green-600 p-4 font-black hover:bg-green-500"
              >
                🟢 ENVIAR POR WHATSAPP
              </button>

              <button
                type="button"
                onClick={
                  nuevoRecibo
                }
                className="rounded-xl bg-slate-600 p-4 font-black hover:bg-slate-500"
              >
                ➕ NUEVO RECIBO
              </button>

            </div>

          </div>

        </section>

      </main>
    );
  }

  // =========================================================
  // PÁGINA PRINCIPAL
  // =========================================================

  return (
    <main className="min-h-screen bg-[#020617] text-white">

      <Sidebar />

      <section className="min-h-screen p-6 pt-32 md:ml-72 md:p-10">

        <div className="mb-8">

          <h1 className="text-4xl font-black">
            Recibos
          </h1>

          <p className="mt-2 text-slate-400">
            Registro y control de pagos de Honduras Cargo Express.
          </p>

        </div>

        {/* =====================================================
            NUEVO RECIBO
        ===================================================== */}

        <div className="rounded-2xl border border-slate-700 bg-[#172033] p-6 shadow-xl">

          <h2 className="mb-7 text-2xl font-black">
            Nuevo Recibo
          </h2>

          <form
            onSubmit={
              guardarRecibo
            }
            className="space-y-6"
          >

            {/* =================================================
                QUIÉN RECIBE — PRIMERO
            ================================================= */}

            <div className="relative">

              <label className="mb-2 block text-lg font-black">
                👤 QUIÉN RECIBE
              </label>

              <input
                type="text"
                value={
                  busquedaDestinatario
                }
                onChange={(e) =>
                  buscarDestinatario(
                    e.target.value
                  )
                }
                placeholder="Escribe el nombre de quien recibe, ejemplo: Wilmer"
                autoComplete="off"
                className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-lg font-bold text-white outline-none focus:border-orange-500"
              />

              {buscandoCliente && (

                <p className="mt-2 text-sm text-slate-400">
                  Buscando destinatario...
                </p>

              )}

              {mostrarClientes &&
                clientesEncontrados.length >
                  0 && (

                <div className="absolute left-0 right-0 z-50 mt-2 max-h-72 overflow-auto rounded-xl border border-slate-600 bg-[#1e293b] shadow-2xl">

                  {clientesEncontrados.map(
                    (cliente) => (

                      <button
                        key={
                          String(
                            cliente.id
                          )
                        }
                        type="button"
                        onClick={() =>
                          seleccionarDestinatario(
                            cliente
                          )
                        }
                        className="block w-full border-b border-slate-700 p-4 text-left hover:bg-slate-700"
                      >

                        <p className="text-lg font-black">
                          {cliente.nombre}
                        </p>

                        <p className="mt-1 text-sm text-slate-400">
                          📞{" "}
                          {cliente.telefono ||
                            "Sin teléfono"}
                        </p>

                        {cliente.correo && (

                          <p className="mt-1 text-sm text-slate-500">
                            ✉️{" "}
                            {cliente.correo}
                          </p>

                        )}

                      </button>

                    )
                  )}

                </div>

              )}

            </div>

            {/* =================================================
                DATOS DESTINATARIO
            ================================================= */}

            {destinatarioSeleccionado && (

              <div className="rounded-xl border border-blue-500/30 bg-blue-500/10 p-5">

                <div className="grid gap-4 md:grid-cols-3">

                  <div>

                    <p className="text-xs font-bold text-slate-400">
                      DESTINATARIO
                    </p>

                    <p className="text-xl font-black text-blue-400">
                      {destinatarioSeleccionado.nombre}
                    </p>

                  </div>

                  <div>

                    <p className="text-xs font-bold text-slate-400">
                      TELÉFONO
                    </p>

                    <p className="text-xl font-black">
                      {destinatarioSeleccionado.telefono ||
                        "Sin teléfono"}
                    </p>

                  </div>

                  <div>

                    <p className="text-xs font-bold text-slate-400">
                      GUÍAS ENCONTRADAS
                    </p>

                    <p className="text-xl font-black">
                      {cargandoGuias
                        ? "Buscando..."
                        : guiasEncontradas.length}
                    </p>

                  </div>

                </div>

              </div>

            )}

            {/* =================================================
                GUÍAS
            ================================================= */}

            {guiasEncontradas.length > 1 && (

              <div>

                <label className="mb-3 block text-lg font-black">
                  📦 SELECCIONA LA GUÍA
                </label>

                <div className="grid gap-3 md:grid-cols-2">

                  {guiasEncontradas.map(
                    (guia) => {

                      const seleccionada =
                        guiaSeleccionada?.id ===
                        guia.id;

                      return (

                        <button
                          key={
                            String(
                              guia.id
                            )
                          }
                          type="button"
                          onClick={() =>
                            seleccionarGuia(
                              guia
                            )
                          }
                          className={`rounded-xl border p-4 text-left transition ${
                            seleccionada
                              ? "border-orange-500 bg-orange-500/20"
                              : "border-slate-600 bg-[#263248] hover:border-orange-400"
                          }`}
                        >

                          <p className="text-xl font-black text-orange-400">
                            {guia.numero}
                          </p>

                          <p className="mt-2 text-sm text-slate-400">
                            {guia.cliente}
                          </p>

                          <p className="mt-2 font-bold">
                            {seleccionada
                              ? "✅ SELECCIONADA"
                              : "Seleccionar guía"}
                          </p>

                        </button>

                      );
                    }
                  )}

                </div>

              </div>

            )}

            {/* =================================================
                GUÍA SELECCIONADA
            ================================================= */}

            {guiaSeleccionada && (

              <div className="rounded-xl border border-orange-500/30 bg-orange-500/10 p-5">

                <p className="text-sm font-bold text-slate-400">
                  GUÍA
                </p>

                <p className="mt-1 text-3xl font-black text-orange-400">
                  {guiaSeleccionada.numero}
                </p>

                <p className="mt-2 text-sm text-slate-300">
                  Guía cargada automáticamente.
                </p>

              </div>

            )}

            {/* =================================================
                QUIÉN ENVÍA
            ================================================= */}

            <div className="rounded-xl border border-slate-700 bg-[#111827] p-5">

              <h3 className="mb-5 text-lg font-black">
                📤 QUIÉN ENVÍA
              </h3>

              <div className="grid gap-5 md:grid-cols-3">

                <div>

                  <label className="mb-2 block font-bold">
                    Nombre
                  </label>

                  <input
                    type="text"
                    value={
                      clienteEnvia
                    }
                    onChange={(e) =>
                      setClienteEnvia(
                        e.target.value
                      )
                    }
                    placeholder="Nombre de quien envía"
                    className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white outline-none focus:border-orange-500"
                  />

                </div>

                <div>

                  <label className="mb-2 block font-bold">
                    📞 Teléfono
                  </label>

                  <input
                    type="text"
                    value={
                      telefonoEnvia
                    }
                    onChange={(e) =>
                      setTelefonoEnvia(
                        e.target.value
                      )
                    }
                    placeholder="Ej: 9795-9210 o 865-389-7216"
                    className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white outline-none focus:border-orange-500"
                  />

                  <p className="mt-2 text-xs text-slate-500">
                    WhatsApp detectará automáticamente Honduras o USA.
                  </p>

                </div>

                <div>

                  <label className="mb-2 block font-bold">
                    ✉️ Correo
                  </label>

                  <input
                    type="email"
                    value={
                      correoEnvia
                    }
                    onChange={(e) =>
                      setCorreoEnvia(
                        e.target.value
                      )
                    }
                    placeholder="Correo electrónico"
                    className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white outline-none focus:border-orange-500"
                  />

                </div>

              </div>

            </div>

            {/* =================================================
                QUIÉN RECIBE — DATOS
            ================================================= */}

            <div className="grid gap-5 md:grid-cols-2">

              <div>

                <label className="mb-2 block font-bold">
                  👤 Nombre de quien recibe
                </label>

                <input
                  type="text"
                  value={
                    clienteRecibe
                  }
                  onChange={(e) =>
                    setClienteRecibe(
                      e.target.value
                    )
                  }
                  className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white outline-none focus:border-orange-500"
                />

              </div>

              <div>

                <label className="mb-2 block font-bold">
                  📞 Teléfono de quien recibe
                </label>

                <input
                  type="text"
                  value={
                    telefonoRecibe
                  }
                  onChange={(e) =>
                    setTelefonoRecibe(
                      e.target.value
                    )
                  }
                  className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white outline-none focus:border-orange-500"
                />

              </div>

            </div>

            {/* =================================================
                PAÍS
            ================================================= */}

            <div>

              <label className="mb-2 block font-bold">
                🌎 PAÍS DESTINO
              </label>

              <select
                value={
                  paisDestino
                }
                onChange={(e) =>
                  setPaisDestino(
                    e.target.value
                  )
                }
                className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white outline-none focus:border-orange-500"
              >

                <option value="Honduras">
                  🇭🇳 Honduras
                </option>

                <option value="Guatemala">
                  🇬🇹 Guatemala
                </option>

                <option value="El Salvador">
                  🇸🇻 El Salvador
                </option>

                <option value="Nicaragua">
                  🇳🇮 Nicaragua
                </option>

              </select>

            </div>

            {/* =================================================
                OBSERVACIONES
            ================================================= */}

            <div>

              <label className="mb-2 block font-bold">
                📝 OBSERVACIONES
              </label>

              <textarea
                rows={3}
                value={
                  observaciones
                }
                onChange={(e) =>
                  setObservaciones(
                    e.target.value
                  )
                }
                placeholder="Ejemplo: Ropa & zapatos"
                className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white outline-none focus:border-orange-500"
              />

            </div>

            {/* =================================================
                MONTO / ESTADO
            ================================================= */}

            <div className="grid gap-5 md:grid-cols-2">

              <div>

                <label className="mb-2 block font-bold">
                  💰 MONTO
                </label>

                <input
                  type="number"
                  min="0"
                  step="0.01"
                  value={
                    monto
                  }
                  onChange={(e) =>
                    setMonto(
                      e.target.value
                    )
                  }
                  placeholder="0.00"
                  className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white outline-none focus:border-orange-500"
                />

              </div>

              <div>

                <label className="mb-2 block font-bold">
                  ESTADO DEL PAGO
                </label>

                <select
                  value={
                    estado
                  }
                  onChange={(e) => {

                    setEstado(
                      e.target.value
                    );

                    if (
                      e.target.value !==
                      "Pagado"
                    ) {
                      setMetodoPago("");
                    }

                  }}
                  className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white outline-none focus:border-orange-500"
                >

                  <option value="Pendiente">
                    🟡 Pendiente
                  </option>

                  <option value="Pagado">
                    🟢 Pagado
                  </option>

                </select>

              </div>

            </div>

            {/* =================================================
                MÉTODO
            ================================================= */}

            {estado ===
              "Pagado" && (

              <div>

                <label className="mb-2 block font-bold">
                  💳 MÉTODO DE PAGO
                </label>

                <select
                  value={
                    metodoPago
                  }
                  onChange={(e) =>
                    setMetodoPago(
                      e.target.value
                    )
                  }
                  className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white outline-none focus:border-orange-500"
                >

                  <option value="">
                    Seleccionar método
                  </option>

                  <option value="Cash">
                    💵 Cash
                  </option>

                  <option value="Cheque">
                    🧾 Cheque
                  </option>

                  <option value="Zelle">
                    📱 Zelle
                  </option>

                  <option value="Transferencia">
                    🏦 Transferencia
                  </option>

                </select>

              </div>

            )}

            {/* =================================================
                GENERAR
            ================================================= */}

            <button
              type="submit"
              disabled={
                guardando ||
                !clienteRecibe ||
                !guiaSeleccionada ||
                !clienteEnvia ||
                !telefonoEnvia
              }
              className="w-full rounded-xl bg-orange-500 p-5 text-lg font-black text-white transition hover:bg-orange-600 disabled:cursor-not-allowed disabled:bg-slate-600"
            >

              {guardando
                ? "GUARDANDO RECIBO..."
                : "💾 GENERAR RECIBO"}

            </button>

          </form>

          {mensaje && (

            <div
              className={`mt-5 rounded-xl p-4 font-bold ${
                mensaje.includes(
                  "correctamente"
                ) ||
                mensaje.includes(
                  "automáticamente"
                )
                  ? "border border-green-500/30 bg-green-500/10 text-green-400"
                  : "border border-yellow-500/30 bg-yellow-500/10 text-yellow-300"
              }`}
            >
              {mensaje}
            </div>

          )}

        </div>

        {/* =====================================================
            RECIBOS REGISTRADOS
        ===================================================== */}
        <div className="mt-8 overflow-hidden rounded-2xl border border-slate-700 bg-[#172033] shadow-xl">
          <div className="border-b border-slate-700 p-6">
            <h2 className="text-2xl font-black">
              Recibos Registrados
            </h2>
            <p className="mt-1 text-sm text-slate-400">
              Desde aquí puedes imprimir, enviar por WhatsApp, editar o borrar un recibo.
            </p>
          </div>

          {recibos.length === 0 ? (
            <div className="p-8 text-slate-400">
              No hay recibos registrados todavía.
            </div>
          ) : (
            <>
              {/* =================================================
                  VISTA ESCRITORIO
              ================================================= */}
              <div className="hidden w-full overflow-hidden md:block">
                <table className="w-full table-fixed text-left text-xs">
                  <colgroup>
                    <col className="w-[9%]" />
                    <col className="w-[7%]" />
                    <col className="w-[11%]" />
                    <col className="w-[11%]" />
                    <col className="w-[7%]" />
                    <col className="w-[10%]" />
                    <col className="w-[7%]" />
                    <col className="w-[7%]" />
                    <col className="w-[7%]" />
                    <col className="w-[8%]" />
                    <col className="w-[16%]" />
                  </colgroup>
                  <thead className="bg-[#263248] text-xs text-slate-300">
                    <tr>
                      <th className="p-2">Recibo</th>
                      <th className="p-2">Guía</th>
                      <th className="p-2">Quién envía</th>
                      <th className="p-2">Quién recibe</th>
                      <th className="p-2">Destino</th>
                      <th className="p-2">Contenido</th>
                      <th className="p-2">Monto</th>
                      <th className="p-2">Estado</th>
                      <th className="p-2">Método</th>
                      <th className="p-2">Fecha</th>
                      <th className="p-2">Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    {recibos.map((recibo) => (
                      <tr
                        key={String(recibo.id)}
                        className="border-t border-slate-700 hover:bg-slate-800/70"
                      >
                        <td className="p-2 font-black text-blue-400 break-words">
                          {recibo.numero || "-"}
                        </td>
                        <td className="p-2 font-black text-orange-400 break-words">
                          {recibo.numero_guia || "-"}
                        </td>
                        <td className="p-2 align-top">
                          <p className="font-bold break-words">{recibo.cliente || "-"}</p>
                          <p className="text-sm text-slate-400">
                            📞 {recibo.telefono || "-"}
                          </p>
                        </td>
                        <td className="p-2 align-top">
                          <p className="font-bold break-words">
                            {recibo.destinatario || "-"}
                          </p>
                          <p className="text-sm text-slate-400">
                            📞 {recibo.telefono_destinatario || "-"}
                          </p>
                        </td>
                        <td className="p-2 align-top break-words">
                          {recibo.pais_destino || "-"}
                        </td>
                        <td className="p-2 align-top">
                          <p className="truncate">
                            {recibo.observaciones || "-"}
                          </p>
                        </td>
                        <td className="p-2 align-top font-black text-green-400 whitespace-nowrap">
                          $
                          {Number(recibo.monto || 0).toLocaleString("en-US", {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2,
                          })}
                        </td>
                        <td className="p-2 align-top">
                          <span
                            className={`rounded-full px-3 py-2 text-xs font-black ${
                              recibo.estado === "Pagado"
                                ? "bg-green-500/20 text-green-400"
                                : "bg-yellow-500/20 text-yellow-400"
                            }`}
                          >
                            {recibo.estado || "Pendiente"}
                          </span>
                        </td>
                        <td className="p-2 align-top break-words">
                          {recibo.metodo_pago || "-"}
                        </td>
                        <td className="p-2 align-top text-[11px] text-slate-400 break-words">
                          {fechaRecibo(recibo.fecha)}
                        </td>
                        <td className="p-2 align-top">
                          <div className="flex flex-wrap gap-1">
                            <button
                              type="button"
                              onClick={() => imprimirRecibo(recibo)}
                              className="whitespace-nowrap rounded-lg bg-blue-600 px-2 py-1.5 text-[11px] font-black hover:bg-blue-500"
                            >
                              🖨️ Imprimir 2
                            </button>
                            <button
                              type="button"
                              onClick={() => enviarWhatsApp(recibo)}
                              className="whitespace-nowrap rounded-lg bg-green-600 px-2 py-1.5 text-[11px] font-black hover:bg-green-500"
                            >
                              🟢 WhatsApp
                            </button>
                            <button
                              type="button"
                              onClick={() => abrirEditar(recibo)}
                              className="whitespace-nowrap rounded-lg bg-indigo-600 px-2 py-1.5 text-[11px] font-black hover:bg-indigo-500"
                            >
                              ✏️ Editar
                            </button>
                            <button
                              type="button"
                              onClick={() => borrarRecibo(recibo)}
                              className="whitespace-nowrap rounded-lg bg-red-600 px-2 py-1.5 text-[11px] font-black hover:bg-red-500"
                            >
                              🗑️ Borrar
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* =================================================
                  VISTA CELULAR
              ================================================= */}
              <div className="space-y-4 p-4 md:hidden">
                {recibos.map((recibo) => (
                  <div
                    key={String(recibo.id)}
                    className="rounded-2xl border border-slate-700 bg-[#111827] p-4 shadow-lg"
                  >
                    <div className="flex items-start justify-between gap-3 border-b border-slate-700 pb-4">
                      <div className="min-w-0">
                        <p className="text-xs font-bold text-slate-400">RECIBO</p>
                        <p className="truncate text-lg font-black text-blue-400">
                          {recibo.numero || "-"}
                        </p>
                      </div>
                      <div className="min-w-0 text-right">
                        <p className="text-xs font-bold text-slate-400">GUÍA</p>
                        <p className="truncate text-lg font-black text-orange-400">
                          {recibo.numero_guia || "-"}
                        </p>
                      </div>
                    </div>

                    <div className="grid gap-3 pt-4">
                      <div>
                        <p className="text-xs font-bold text-slate-400">QUIÉN ENVÍA</p>
                        <p className="font-bold">{recibo.cliente || "-"}</p>
                        <p className="text-sm text-slate-400">
                          📞 {recibo.telefono || "-"}
                        </p>
                      </div>

                      <div>
                        <p className="text-xs font-bold text-slate-400">QUIÉN RECIBE</p>
                        <p className="font-bold">{recibo.destinatario || "-"}</p>
                        <p className="text-sm text-slate-400">
                          📞 {recibo.telefono_destinatario || "-"}
                        </p>
                      </div>

                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <p className="text-xs font-bold text-slate-400">DESTINO</p>
                          <p className="font-bold">{recibo.pais_destino || "-"}</p>
                        </div>
                        <div>
                          <p className="text-xs font-bold text-slate-400">FECHA</p>
                          <p className="text-sm text-slate-300">
                            {fechaRecibo(recibo.fecha)}
                          </p>
                        </div>
                      </div>

                      <div>
                        <p className="text-xs font-bold text-slate-400">CONTENIDO</p>
                        <p className="break-words text-slate-200">
                          {recibo.observaciones || "-"}
                        </p>
                      </div>

                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <p className="text-xs font-bold text-slate-400">MONTO</p>
                          <p className="font-black text-green-400">
                            ${Number(recibo.monto || 0).toLocaleString("en-US", {
                              minimumFractionDigits: 2,
                              maximumFractionDigits: 2,
                            })}
                          </p>
                        </div>
                        <div>
                          <p className="text-xs font-bold text-slate-400">ESTADO</p>
                          <span
                            className={`inline-block rounded-full px-3 py-1 text-xs font-black ${
                              recibo.estado === "Pagado"
                                ? "bg-green-500/20 text-green-400"
                                : "bg-yellow-500/20 text-yellow-400"
                            }`}
                          >
                            {recibo.estado || "Pendiente"}
                          </span>
                        </div>
                      </div>

                      <div>
                        <p className="text-xs font-bold text-slate-400">MÉTODO DE PAGO</p>
                        <p>{recibo.metodo_pago || "-"}</p>
                      </div>
                    </div>

                    <div className="mt-5 grid grid-cols-2 gap-2">
                      <button
                        type="button"
                        onClick={() => imprimirRecibo(recibo)}
                        className="rounded-lg bg-blue-600 px-3 py-3 text-sm font-black hover:bg-blue-500"
                      >
                        🖨️ Imprimir 2
                      </button>
                      <button
                        type="button"
                        onClick={() => enviarWhatsApp(recibo)}
                        className="rounded-lg bg-green-600 px-3 py-3 text-sm font-black hover:bg-green-500"
                      >
                        🟢 WhatsApp
                      </button>
                      <button
                        type="button"
                        onClick={() => abrirEditar(recibo)}
                        className="rounded-lg bg-indigo-600 px-3 py-3 text-sm font-black hover:bg-indigo-500"
                      >
                        ✏️ Editar
                      </button>
                      <button
                        type="button"
                        onClick={() => borrarRecibo(recibo)}
                        className="rounded-lg bg-red-600 px-3 py-3 text-sm font-black hover:bg-red-500"
                      >
                        🗑️ Borrar
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>

        {/* =====================================================
            MODAL EDITAR
        ===================================================== */}

        {reciboEditando && (

          <div className="fixed inset-0 z-[100] flex items-center justify-center overflow-auto bg-black/75 p-5">

            <div className="my-10 w-full max-w-4xl rounded-2xl border border-slate-600 bg-[#172033] p-6 shadow-2xl">

              <div className="mb-6 flex items-center justify-between">

                <div>

                  <h2 className="text-2xl font-black">
                    ✏️ EDITAR RECIBO
                  </h2>

                  <p className="mt-1 text-slate-400">
                    {reciboEditando.numero ||
                      "-"}
                    {" · "}
                    Guía{" "}
                    {reciboEditando.numero_guia ||
                      "-"}
                  </p>

                </div>

                <button
                  type="button"
                  onClick={() =>
                    setReciboEditando(
                      null
                    )
                  }
                  disabled={
                    guardandoEdicion
                  }
                  className="rounded-lg bg-slate-700 px-4 py-2 font-black hover:bg-slate-600"
                >
                  ✕
                </button>

              </div>

              <div className="grid gap-5 md:grid-cols-2">

                <div>

                  <label className="mb-2 block font-bold">
                    Quién envía
                  </label>

                  <input
                    value={
                      editCliente
                    }
                    onChange={(e) =>
                      setEditCliente(
                        e.target.value
                      )
                    }
                    className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white"
                  />

                </div>

                <div>

                  <label className="mb-2 block font-bold">
                    Teléfono de quien envía
                  </label>

                  <input
                    value={
                      editTelefono
                    }
                    onChange={(e) =>
                      setEditTelefono(
                        e.target.value
                      )
                    }
                    className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white"
                  />

                </div>

                <div>

                  <label className="mb-2 block font-bold">
                    Quién recibe
                  </label>

                  <input
                    value={
                      editDestinatario
                    }
                    onChange={(e) =>
                      setEditDestinatario(
                        e.target.value
                      )
                    }
                    className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white"
                  />

                </div>

                <div>

                  <label className="mb-2 block font-bold">
                    Teléfono de quien recibe
                  </label>

                  <input
                    value={
                      editTelefonoDestinatario
                    }
                    onChange={(e) =>
                      setEditTelefonoDestinatario(
                        e.target.value
                      )
                    }
                    className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white"
                  />

                </div>

                <div>

                  <label className="mb-2 block font-bold">
                    País destino
                  </label>

                  <select
                    value={
                      editPaisDestino
                    }
                    onChange={(e) =>
                      setEditPaisDestino(
                        e.target.value
                      )
                    }
                    className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white"
                  >

                    <option value="Honduras">
                      🇭🇳 Honduras
                    </option>

                    <option value="Guatemala">
                      🇬🇹 Guatemala
                    </option>

                    <option value="El Salvador">
                      🇸🇻 El Salvador
                    </option>

                    <option value="Nicaragua">
                      🇳🇮 Nicaragua
                    </option>

                  </select>

                </div>

                <div>

                  <label className="mb-2 block font-bold">
                    Monto
                  </label>

                  <input
                    type="number"
                    min="0"
                    step="0.01"
                    value={
                      editMonto
                    }
                    onChange={(e) =>
                      setEditMonto(
                        e.target.value
                      )
                    }
                    className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white"
                  />

                </div>

                <div>

                  <label className="mb-2 block font-bold">
                    Estado
                  </label>

                  <select
                    value={
                      editEstado
                    }
                    onChange={(e) => {

                      setEditEstado(
                        e.target.value
                      );

                      if (
                        e.target.value !==
                        "Pagado"
                      ) {
                        setEditMetodoPago(
                          ""
                        );
                      }

                    }}
                    className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white"
                  >

                    <option value="Pendiente">
                      🟡 Pendiente
                    </option>

                    <option value="Pagado">
                      🟢 Pagado
                    </option>

                  </select>

                </div>

                {editEstado ===
                  "Pagado" && (

                  <div>

                    <label className="mb-2 block font-bold">
                      Método de pago
                    </label>

                    <select
                      value={
                        editMetodoPago
                      }
                      onChange={(e) =>
                        setEditMetodoPago(
                          e.target.value
                        )
                      }
                      className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white"
                    >

                      <option value="">
                        Seleccionar método
                      </option>

                      <option value="Cash">
                        💵 Cash
                      </option>

                      <option value="Cheque">
                        🧾 Cheque
                      </option>

                      <option value="Zelle">
                        📱 Zelle
                      </option>

                      <option value="Transferencia">
                        🏦 Transferencia
                      </option>

                    </select>

                  </div>

                )}

              </div>

              <div className="mt-5">

                <label className="mb-2 block font-bold">
                  📝 Observaciones
                </label>

                <textarea
                  rows={3}
                  value={
                    editObservaciones
                  }
                  onChange={(e) =>
                    setEditObservaciones(
                      e.target.value
                    )
                  }
                  className="w-full rounded-xl border border-slate-600 bg-[#263248] p-4 text-white"
                />

              </div>

              <div className="mt-7 grid gap-3 md:grid-cols-2">

                <button
                  type="button"
                  onClick={() =>
                    setReciboEditando(
                      null
                    )
                  }
                  disabled={
                    guardandoEdicion
                  }
                  className="rounded-xl bg-slate-600 p-4 font-black hover:bg-slate-500"
                >
                  CANCELAR
                </button>

                <button
                  type="button"
                  onClick={
                    guardarEdicion
                  }
                  disabled={
                    guardandoEdicion
                  }
                  className="rounded-xl bg-blue-600 p-4 font-black hover:bg-blue-500 disabled:bg-slate-600"
                >
                  {guardandoEdicion
                    ? "GUARDANDO..."
                    : "💾 GUARDAR CAMBIOS"}
                </button>

              </div>

            </div>

          </div>

        )}

      </section>

    </main>
  );
}