"use client";

import { useEffect, useState } from "react";
import { X, Share, Plus } from "lucide-react";

const DISMISSED_KEY = "pwa-install-dismissed";

type Prompt = "android" | "ios";

function isIos() {
  return (
    /iphone|ipad|ipod/i.test(navigator.userAgent) ||
    // iPad on iOS 13+ reports as Mac
    (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1)
  );
}

function isInStandaloneMode() {
  return (
    "standalone" in window.navigator &&
    (window.navigator as { standalone?: boolean }).standalone === true
  );
}

export function InstallPrompt() {
  const [prompt, setPrompt] = useState<Prompt | null>(null);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const [deferredEvent, setDeferredEvent] = useState<any>(null);

  useEffect(() => {
    if (localStorage.getItem(DISMISSED_KEY)) return;

    // Android / Chrome desktop — beforeinstallprompt fires
    const handler = (e: Event) => {
      e.preventDefault();
      setDeferredEvent(e);
      setPrompt("android");
    };
    window.addEventListener("beforeinstallprompt", handler);

    // iOS — no beforeinstallprompt; defer setState out of the synchronous
    // effect body to satisfy react-hooks/set-state-in-effect.
    let iosTimer: ReturnType<typeof setTimeout> | undefined;
    if (isIos() && !isInStandaloneMode()) {
      iosTimer = setTimeout(() => setPrompt("ios"), 0);
    }

    return () => {
      window.removeEventListener("beforeinstallprompt", handler);
      clearTimeout(iosTimer);
    };
  }, []);

  function dismiss() {
    localStorage.setItem(DISMISSED_KEY, "1");
    setPrompt(null);
  }

  async function install() {
    if (!deferredEvent) return;
    deferredEvent.prompt();
    const { outcome } = await deferredEvent.userChoice;
    if (outcome === "accepted" || outcome === "dismissed") {
      dismiss();
    }
  }

  if (!prompt) return null;

  return (
    <div
      role="banner"
      className="fixed bottom-[80px] left-0 right-0 z-50 flex items-start gap-3 px-4 py-3 sm:bottom-4 sm:left-1/2 sm:right-auto sm:-translate-x-1/2 sm:px-5 sm:py-4"
      style={{
        background: "var(--card)",
        border: "0.5px solid var(--hair-2)",
        borderRadius: "var(--r-lg)",
        boxShadow: "var(--shadow-pop)",
        margin: "0 14px",
      }}
    >
      <div
        className="mt-0.5 size-10 shrink-0 overflow-hidden flex items-center justify-center"
        style={{
          borderRadius: 8,
          background: "var(--ink)",
          color: "var(--paper)",
          fontFamily: "var(--serif)",
          fontSize: 18,
          fontWeight: 500,
        }}
      >
        f
      </div>

      <div className="flex-1 text-[13.5px]">
        <p className="font-medium leading-snug text-[var(--ink)] m-0">
          Add famapp to your home screen
        </p>

        {prompt === "android" && (
          <>
            <p className="mt-1 muted text-[12.5px] m-0">
              Install for a faster, app-like experience.
            </p>
            <button onClick={install} className="btn btn-sm btn-primary mt-2">
              Install
            </button>
          </>
        )}

        {prompt === "ios" && (
          <p className="mt-1 muted text-[12.5px] m-0">
            Tap <Share className="inline-block size-3.5 align-text-bottom" aria-label="Share" />{" "}
            then{" "}
            <strong className="font-medium">
              <Plus className="inline-block size-3 align-text-bottom" />
              &nbsp;Add to Home Screen
            </strong>
            .
          </p>
        )}
      </div>

      <button
        onClick={dismiss}
        aria-label="Dismiss"
        className="mt-0.5 shrink-0 rounded p-1 text-[var(--ink-mute)] hover:bg-[var(--shade)]"
      >
        <X className="size-4" />
      </button>
    </div>
  );
}
