import { useState } from "react";
import { Download, PlusSquare, Share } from "lucide-react";
import { Modal } from "./Modal";
import { useInstallPrompt } from "../lib/useInstallPrompt";

export function InstallAppPrompt({ compact = false }: { compact?: boolean }) {
  const { state, install } = useInstallPrompt();
  const [iosOpen, setIosOpen] = useState(false);
  const buttonClassName = compact
    ? "btn btn-secondary h-9 w-9 shrink-0 justify-center p-0"
    : "btn btn-secondary w-full justify-start";

  if (state === "unsupported" || state === "installed") return null;
  if (state === "ios-instructions") {
    return (
      <>
        <button
          type="button"
          className={buttonClassName}
          aria-label="Instalar AgendaMax"
          title={compact ? "Instalar AgendaMax" : undefined}
          onClick={() => setIosOpen(true)}
        >
          <Download className="h-4 w-4" />
          <span className={compact ? "sr-only" : undefined}>Instalar AgendaMax</span>
        </button>
        <Modal open={iosOpen} onClose={() => setIosOpen(false)} title="Instalar AgendaMax" subtitle="Safari lo añade a tu pantalla de inicio.">
          <div className="safe-area-bottom">
            <ol className="space-y-3 text-sm text-slate-600">
              <li className="flex gap-3"><Share className="mt-0.5 h-5 w-5 shrink-0 text-brand-600" /><span>Toca <strong>Compartir</strong> en la barra de Safari.</span></li>
              <li className="flex gap-3"><PlusSquare className="mt-0.5 h-5 w-5 shrink-0 text-brand-600" /><span>Elige <strong>Añadir a pantalla de inicio</strong> y confirma.</span></li>
            </ol>
          </div>
        </Modal>
      </>
    );
  }
  return (
    <button
      type="button"
      className={buttonClassName}
      aria-label="Instalar AgendaMax"
      title={compact ? "Instalar AgendaMax" : undefined}
      onClick={() => void install()}
    >
      <Download className="h-4 w-4" />
      <span className={compact ? "sr-only" : undefined}>Instalar AgendaMax</span>
    </button>
  );
}
