'use client';

import { useEffect, useState } from 'react';
import { HydratedIsland } from '@/components/HydratedIsland';
import { InstallSheet } from '@/components/ui/domain/InstallSheet';
import { captureCaught } from '@/lib/observability';
import {
  installSheetOnCooldown,
  isStandaloneDisplayMode,
  startInstallSheetCooldown,
} from '@/lib/offline/offlineContinuity';

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

function InstallSheetHostInner() {
  const [promptEvent, setPromptEvent] = useState<BeforeInstallPromptEvent | null>(null);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    if (isStandaloneDisplayMode() || installSheetOnCooldown()) return;

    const handleBeforeInstall = (event: Event) => {
      event.preventDefault();
      setPromptEvent(event as BeforeInstallPromptEvent);
      setOpen(true);
    };

    const handleInstalled = () => {
      setOpen(false);
      setPromptEvent(null);
      startInstallSheetCooldown();
    };

    window.addEventListener('beforeinstallprompt', handleBeforeInstall);
    window.addEventListener('appinstalled', handleInstalled);
    return () => {
      window.removeEventListener('beforeinstallprompt', handleBeforeInstall);
      window.removeEventListener('appinstalled', handleInstalled);
    };
  }, []);

  if (!promptEvent || isStandaloneDisplayMode()) return null;

  const resetInstallSheet = () => {
    setOpen(false);
    setPromptEvent(null);
    startInstallSheetCooldown();
  };

  return (
    <InstallSheet
      open={open}
      onOpenChange={(nextOpen) => {
        setOpen(nextOpen);
        if (!nextOpen) startInstallSheetCooldown();
      }}
      onInstall={() => {
        void promptEvent.prompt().catch((err) => {
          captureCaught(err, {
            scope: 'features.pwaInstall.InstallSheetHost.prompt',
            severity: 'warning',
          });
          resetInstallSheet();
        });
        void promptEvent.userChoice
          .then((choice) => {
            if (choice.outcome === 'accepted') {
              setOpen(false);
              setPromptEvent(null);
            } else {
              resetInstallSheet();
            }
          })
          .catch((err) => {
            captureCaught(err, {
              scope: 'features.pwaInstall.InstallSheetHost.userChoice',
              severity: 'warning',
            });
            resetInstallSheet();
          });
      }}
      onDismiss={() => {
        setOpen(false);
        startInstallSheetCooldown();
      }}
    />
  );
}

export function InstallSheetHost() {
  return (
    <HydratedIsland>
      <InstallSheetHostInner />
    </HydratedIsland>
  );
}
