/* InstalarAppRow → window. Botón fijo en Perfil "Agregar acceso al
   teléfono". Distinto del banner (InstalarBanner): el banner es
   temporal y se puede dismissar; este row vive permanente en el
   Perfil mientras la app NO esté instalada. Misma lógica de detección
   y de disparo (prompt nativo en Android/Desktop, modal con
   instrucciones en iOS).

   Props: ninguno.
*/
(function () {
  const { useEffect, useState } = React;

  function InstalarAppRow() {
    const [instalada, setInstalada] = useState(
      typeof window.estaInstalada === "function" ? window.estaInstalada() : false
    );
    const [hayPrompt, setHayPrompt] = useState(!!window.deferredInstallPrompt);
    const [modalIOS, setModalIOS] = useState(false);
    const iosSafari = typeof window.esIOS === "function" && window.esIOS();

    useEffect(() => {
      function onInstallable() { setHayPrompt(true); }
      function onInstalled() {
        setInstalada(true);
        setHayPrompt(false);
      }
      window.addEventListener("cultord:installable", onInstallable);
      window.addEventListener("cultord:installed", onInstalled);
      return () => {
        window.removeEventListener("cultord:installable", onInstallable);
        window.removeEventListener("cultord:installed", onInstalled);
      };
    }, []);

    // Ya instalada o sin soporte (no es iOS y no hay prompt) → no
    // mostrar el row. En browsers desktop sin PWA support esto también
    // se esconde (Firefox desktop sin flag, etc.).
    if (instalada) return null;
    if (!iosSafari && !hayPrompt) return null;

    async function handleTap() {
      if (iosSafari && !hayPrompt) {
        setModalIOS(true);
        return;
      }
      const prompt = window.deferredInstallPrompt;
      if (!prompt) return;
      try {
        prompt.prompt();
        const choice = await prompt.userChoice;
        window.deferredInstallPrompt = null;
        setHayPrompt(false);
        if (choice && choice.outcome === "accepted") {
          setInstalada(true);
        }
      } catch (e) {
        console.warn("[InstalarAppRow] prompt falló:", e);
      }
    }

    return (
      <React.Fragment>
        <button
          type="button"
          onClick={handleTap}
          className="card-soft w-full flex items-center gap-3 px-4 py-3 text-left active:scale-[0.99] transition mb-2"
        >
          <div className="w-11 h-11 rounded-full bg-[#DCE7F7] dark:bg-blue-900/40 flex items-center justify-center text-xl flex-shrink-0">
            📱
          </div>
          <div className="flex-1 min-w-0">
            <div className="font-black text-sm text-[#3C3C3C] dark:text-gray-100">
              Agregar acceso al teléfono
            </div>
            <div className="text-xs font-semibold text-[#777] dark:text-gray-400 mt-0.5">
              Accede rápido desde tu pantalla de inicio
            </div>
          </div>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden className="text-[#9AA0A6] flex-shrink-0">
            <path d="M9 6l6 6-6 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>

        {window.ModalInstalarIOS && (
          <window.ModalInstalarIOS
            abierto={modalIOS}
            onClose={() => setModalIOS(false)}
          />
        )}
      </React.Fragment>
    );
  }

  window.InstalarAppRow = InstalarAppRow;
})();
