// PWA Install Prompt Component
"use client";

import { useEffect, useSyncExternalStore, useCallback, useReducer } from "react";

interface BeforeInstallPromptEvent extends Event {
  prompt(): Promise<void>;
  userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
}

type PromptState = {
  deferred: BeforeInstallPromptEvent | null;
  visible: boolean;
};

type PromptAction =
  | { type: "captured"; event: BeforeInstallPromptEvent }
  | { type: "show" }
  | { type: "hide" }
  | { type: "dismissed" }
  | { type: "reset" };

function promptReducer(state: PromptState, action: PromptAction): PromptState {
  switch (action.type) {
    case "captured":
      return { deferred: action.event, visible: false };
    case "show":
      return state.deferred ? { ...state, visible: true } : state;
    case "hide":
      return { deferred: null, visible: false };
    case "dismissed":
      return { ...state, visible: false };
    case "reset":
      return { deferred: null, visible: false };
  }
}

const INITIAL_PROMPT_STATE: PromptState = { deferred: null, visible: false };

export default function PWAInstallPrompt() {
  // `deferred` and `visible` are coupled — the prompt is only meaningful
  // when a deferred BeforeInstallPromptEvent has been captured. We keep
  // them in a single reducer so the related updates land in one render
  // instead of multiple cascading setState calls.
  const [prompt, dispatch] = useReducer(promptReducer, INITIAL_PROMPT_STATE);
  // Detect whether the app is already running in standalone (PWA) mode
  // and whether we're on the client. Both are pure reads of
  // browser-only state, so a lazy initializer that gates on
  // `typeof window` is enough — no useEffect needed.
  const isInstalled = useSyncExternalStore(
    () => () => {},
    () => typeof window !== "undefined" && window.matchMedia("(display-mode: standalone)").matches,
    () => false,
  );
  const mounted = useSyncExternalStore(
    () => () => {},
    () => true,
    () => false,
  );

  useEffect(() => {
    if (isInstalled) return;
    if (typeof window === "undefined") return;

    const handleBeforeInstall = (e: Event) => {
      e.preventDefault();
      dispatch({ type: "captured", event: e as BeforeInstallPromptEvent });
      // Show the prompt after 10s of dwell time so it doesn't immediately
      // interrupt first-time visitors.
      window.setTimeout(() => {
        dispatch({ type: "show" });
      }, 10000);
    };

    const handleAppInstalled = () => {
      dispatch({ type: "reset" });
    };

    window.addEventListener("beforeinstallprompt", handleBeforeInstall);
    window.addEventListener("appinstalled", handleAppInstalled);

    return () => {
      window.removeEventListener("beforeinstallprompt", handleBeforeInstall);
      window.removeEventListener("appinstalled", handleAppInstalled);
    };
  }, [isInstalled]);

  const handleInstall = useCallback(async () => {
    const deferred = prompt.deferred;
    if (!deferred) return;

    await deferred.prompt();
    const { outcome } = await deferred.userChoice;

    if (outcome === "accepted") {
      dispatch({ type: "reset" });
    } else {
      // User dismissed; just clear the deferred prompt so we don't
      // re-prompt for the same deferred event.
      dispatch({ type: "reset" });
    }
  }, [prompt.deferred]);

  const handleDismiss = useCallback(() => {
    dispatch({ type: "dismissed" });
    try {
      sessionStorage.setItem("pwa-install-dismissed", "true");
    } catch {
      // ignore
    }
  }, []);

  if (!mounted || !prompt.visible || isInstalled || !prompt.deferred) {
    return null;
  }

  return (
    <div className="fixed bottom-4 left-4 right-4 sm:left-auto sm:right-4 sm:w-80 bg-white rounded-2xl shadow-2xl border border-gray-200 p-4 z-50">
      <div className="flex items-start gap-3">
        <div className="w-12 h-12 bg-gradient-to-br from-emerald-600 to-emerald-500 rounded-xl flex items-center justify-center shrink-0">
          <svg className="w-6 h-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
          </svg>
        </div>
        <div className="flex-1">
          <h3 className="font-semibold text-gray-900">Install Route Commerce</h3>
          <p className="text-sm text-gray-500 mt-1">Add to your home screen for quick access</p>
        </div>
      </div>
      <div className="flex gap-2 mt-4">
        <button type="button"
          onClick={handleDismiss}
          className="flex-1 px-4 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 transition-colors"
        >
          Not now
        </button>
        <button type="button"
          onClick={handleInstall}
          className="flex-1 px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm font-medium hover:bg-emerald-500 transition-colors"
        >
          Install
        </button>
      </div>
    </div>
  );
}
