"use client";

import * as React from "react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useToast } from "@/components/ui/toast";

type BeforeInstallPromptEvent = Event & {
  prompt: () => Promise<void>;
  userChoice: Promise<{ outcome: "accepted" | "dismissed"; platform: string }>;
};

const DISMISS_KEY = "sag.pwa.install_dismissed";
const DISMISS_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days

function isDismissedRecently(): boolean {
  if (typeof window === "undefined") return true;
  try {
    const raw = window.localStorage.getItem(DISMISS_KEY);
    if (!raw) return false;
    const ts = Number(raw);
    if (!Number.isFinite(ts)) return false;
    return Date.now() - ts < DISMISS_TTL_MS;
  } catch {
    return false;
  }
}

function markDismissed() {
  if (typeof window === "undefined") return;
  try {
    window.localStorage.setItem(DISMISS_KEY, String(Date.now()));
  } catch {
    // Storage may be disabled — best effort.
  }
}

/**
 * Tasteful PWA install banner. Listens for the browser's
 * `beforeinstallprompt` event and shows a small dismissable card pinned to
 * the bottom of the viewport. Dismissal persists for 7 days.
 *
 * Mount inside `/app/*` only — do not show on marketing pages.
 */
export function PwaInstallPrompt() {
  const { toast } = useToast();
  const [deferred, setDeferred] = React.useState<BeforeInstallPromptEvent | null>(null);
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    if (typeof window === "undefined") return;
    if (isDismissedRecently()) return;

    // If already installed (display-mode standalone) we should not prompt.
    try {
      if (window.matchMedia && window.matchMedia("(display-mode: standalone)").matches) {
        return;
      }
    } catch {
      // matchMedia may throw in old engines — ignore.
    }

    const onBeforeInstallPrompt = (e: Event) => {
      e.preventDefault();
      setDeferred(e as BeforeInstallPromptEvent);
      setVisible(true);
    };

    const onAppInstalled = () => {
      setDeferred(null);
      setVisible(false);
      markDismissed();
      toast({
        title: "SAG Manager installed",
        description: "Launch it from your home screen or app menu.",
        variant: "success",
      });
    };

    window.addEventListener("beforeinstallprompt", onBeforeInstallPrompt);
    window.addEventListener("appinstalled", onAppInstalled);

    return () => {
      window.removeEventListener("beforeinstallprompt", onBeforeInstallPrompt);
      window.removeEventListener("appinstalled", onAppInstalled);
    };
  }, [toast]);

  const handleInstall = React.useCallback(async () => {
    if (!deferred) return;
    try {
      await deferred.prompt();
      const choice = await deferred.userChoice;
      if (choice.outcome === "dismissed") {
        markDismissed();
      }
    } catch {
      // Prompt can only be called once — silently no-op on failure.
    } finally {
      setDeferred(null);
      setVisible(false);
    }
  }, [deferred]);

  const handleNotNow = React.useCallback(() => {
    markDismissed();
    setVisible(false);
  }, []);

  if (!visible || !deferred) return null;

  return (
    <div
      className="pointer-events-none fixed inset-x-0 bottom-4 z-40 flex justify-center px-4"
      aria-live="polite"
    >
      <Card className="pointer-events-auto flex w-full max-w-md items-center gap-3 p-3 shadow-lg">
        <div className="min-w-0 flex-1">
          <div className="text-sm font-medium">Install SAG Manager</div>
          <div className="text-xs text-muted-foreground">
            Get offline access and faster loads on this device.
          </div>
        </div>
        <div className="flex shrink-0 items-center gap-2">
          <Button type="button" size="sm" variant="ghost" onClick={handleNotNow}>
            Not now
          </Button>
          <Button type="button" size="sm" onClick={handleInstall}>
            Install
          </Button>
        </div>
      </Card>
    </div>
  );
}

export default PwaInstallPrompt;
