/* ============================================================
   SE42 · Landing — instalación inteligente (PWA)
   Detecta dispositivo y actúa: Android/Chrome → prompt nativo,
   iOS/Safari → modal con pasos, escritorio/instalada → abrir app.
   ============================================================ */
const { useEffect: useInsEffect, useRef: useInsRef, useState: useInsState } = React;

function useInstall(appUrl) {
  const deferred = useInsRef(null);
  const [canPrompt, setCanPrompt] = useInsState(false);
  const [installed, setInstalled] = useInsState(false);
  const [iosOpen, setIosOpen] = useInsState(false);

  const isIOS = typeof navigator !== "undefined" &&
    /iphone|ipad|ipod/i.test(navigator.userAgent) && !("MSStream" in window);
  const isStandalone = typeof window !== "undefined" &&
    (window.matchMedia("(display-mode: standalone)").matches || navigator.standalone === true);

  useInsEffect(() => {
    const onBIP = (e) => { e.preventDefault(); deferred.current = e; setCanPrompt(true); };
    const onInstalled = () => { setInstalled(true); setCanPrompt(false); deferred.current = null; };
    window.addEventListener("beforeinstallprompt", onBIP);
    window.addEventListener("appinstalled", onInstalled);
    return () => {
      window.removeEventListener("beforeinstallprompt", onBIP);
      window.removeEventListener("appinstalled", onInstalled);
    };
  }, []);

  // 'prompt' = instalación nativa | 'ios' = pasos manuales | 'open' = abrir app
  const mode = (isStandalone || installed) ? "open" : (canPrompt ? "prompt" : (isIOS ? "ios" : "open"));

  const onInstall = async (e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (mode === "prompt" && deferred.current) {
      deferred.current.prompt();
      try { await deferred.current.userChoice; } catch (err) {}
      deferred.current = null;
      setCanPrompt(false);
      return;
    }
    if (mode === "ios") { setIosOpen(true); return; }
    window.open(appUrl, "_blank", "noopener");
  };

  return { mode, onInstall, iosOpen, closeIos: () => setIosOpen(false), appUrl };
}

/* Botón de instalación — mantiene el estilo pill + texto dinámico */
function InstallPill({ t, install, label, className = "", iconSize = 16 }) {
  const text = install.mode === "open" ? t.install.open : label;
  const icon = install.mode === "open" ? "external" : "download";
  return (
    <a className={"pill " + className} href={install.appUrl} onClick={install.onInstall}
       target="_blank" rel="noopener">
      <Icon name={icon} size={iconSize} />
      <span className="pill__label">
        <span className="pill__label-row">{text}</span>
        <span className="pill__label-row" aria-hidden="true">{text}</span>
      </span>
    </a>
  );
}

/* Modal iOS — pasos para añadir a la pantalla de inicio */
function InstallModal({ t, shots, onClose }) {
  useInsEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [onClose]);
  const ins = t.install;
  return (
    <div className="imodal" role="dialog" aria-modal="true" aria-label={ins.eyebrow} onClick={onClose}>
      <div className="imodal__card" onClick={(e) => e.stopPropagation()}>
        <button className="imodal__close" onClick={onClose} aria-label={ins.close}><Icon name="close" size={20} /></button>
        <p className="eyebrow imodal__eyebrow">{ins.eyebrow}</p>
        <h2 className="imodal__title"><Headline lead={ins.lead} accent={ins.accent} /></h2>
        <p className="imodal__intro">{ins.intro}</p>
        <div className="imodal__shots">
          <figure>
            <div className="imodal__shot"><img src={shots[0]} alt="" /></div>
            <figcaption>{ins.shareCap}</figcaption>
          </figure>
          <figure>
            <div className="imodal__shot"><img src={shots[1]} alt="" /></div>
            <figcaption>{ins.addCap}</figcaption>
          </figure>
        </div>
        <ol className="imodal__steps">
          {ins.steps.map((s, i) => <li key={i}><span className="imodal__n">{i + 1}</span>{s}</li>)}
        </ol>
        <button className="pill pill--lg imodal__ok" onClick={onClose}>{ins.close}</button>
      </div>
    </div>
  );
}

Object.assign(window, { useInstall, InstallPill, InstallModal });
