"use client"

import { useEffect, useState } from "react"
import { Download, Share, SquarePlus, X } from "lucide-react"
import {
  clearDeferredInstallPrompt,
  getDeferredInstallPrompt,
  subscribeInstallPrompt,
  type BeforeInstallPromptEvent,
} from "@/lib/pwa-install"

const DISMISS_KEY = "teecup-install-dismissed-until"
const DISMISS_COOLDOWN_DAYS = 14

function isStandalone() {
  if (typeof window === "undefined") return false
  const nav = window.navigator as Navigator & { standalone?: boolean }
  return window.matchMedia("(display-mode: standalone)").matches || nav.standalone === true
}

function isIOS() {
  if (typeof window === "undefined") return false
  return /iphone|ipad|ipod/i.test(window.navigator.userAgent)
}

function isDismissedForNow() {
  if (typeof window === "undefined") return true
  const raw = window.localStorage.getItem(DISMISS_KEY)
  if (!raw) return false
  const until = Number(raw)
  return Number.isFinite(until) && Date.now() < until
}

function dismissForNow() {
  const until = Date.now() + DISMISS_COOLDOWN_DAYS * 24 * 60 * 60 * 1000
  window.localStorage.setItem(DISMISS_KEY, String(until))
}

// PWA-installasjonsoppfordring (FEATURE_BACKLOG.md "PWA-installasjon").
// To distinkte varianter -- INGEN visning for andre nettlesere uten en
// reell installasjonsvei:
// - Android/Chrome-familien: ekte "Installer"-knapp via det fangede
//   beforeinstallprompt-eventet (lib/pwa-install.ts).
// - iOS Safari: Apple har ALDRI implementert beforeinstallprompt -- kun et
//   instruksjonsbanner (Del-ikon -> "Legg til på Hjemskjerm") er mulig.
export function InstallPrompt() {
  const [dismissed, setDismissed] = useState(true)
  const [platform, setPlatform] = useState<"android" | "ios" | "none">("none")
  const [deferredEvent, setDeferredEvent] = useState<BeforeInstallPromptEvent | null>(null)

  useEffect(() => {
    if (isStandalone() || isDismissedForNow()) return
    if (isIOS()) {
      setPlatform("ios")
      setDismissed(false)
      return
    }
    // Android/Chrome-familien: vis kun når/hvis eventet faktisk fyres --
    // andre nettlesere uten en reell installasjonsvei skal ikke vise noe.
    const existing = getDeferredInstallPrompt()
    if (existing) {
      setDeferredEvent(existing)
      setPlatform("android")
      setDismissed(false)
    }
    const unsubscribe = subscribeInstallPrompt((event) => {
      if (event) {
        setDeferredEvent(event)
        setPlatform("android")
        setDismissed(false)
      }
    })
    return unsubscribe
  }, [])

  if (dismissed || platform === "none") return null

  async function handleInstall() {
    if (!deferredEvent) return
    await deferredEvent.prompt()
    await deferredEvent.userChoice
    clearDeferredInstallPrompt()
    setDismissed(true)
  }

  function handleDismiss() {
    dismissForNow()
    setDismissed(true)
  }

  return (
    <div
      role="region"
      aria-label="Installer TeeCup"
      className="flex items-start gap-3 rounded-2xl border border-border bg-card p-4 shadow-md shadow-black/8"
    >
      <div className="mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-full bg-primary/15 text-primary">
        {platform === "ios" ? (
          <Share aria-hidden="true" className="size-5" />
        ) : (
          <Download aria-hidden="true" className="size-5" />
        )}
      </div>

      <div className="flex-1">
        <p className="text-sm font-bold text-foreground">Legg TeeCup til på hjemskjermen</p>
        {platform === "ios" ? (
          <p className="mt-1 text-sm leading-relaxed text-muted-foreground text-pretty">
            Trykk <Share aria-hidden="true" className="inline size-4 -translate-y-0.5" /> (Del) nederst i Safari,
            velg deretter <SquarePlus aria-hidden="true" className="inline size-4 -translate-y-0.5" />{" "}
            «Legg til på Hjem-skjerm».
          </p>
        ) : (
          <p className="mt-1 text-sm leading-relaxed text-muted-foreground text-pretty">
            Rask tilgang, fungerer som en egen app, og virker delvis uten nett.
          </p>
        )}

        <div className="mt-3 flex flex-wrap gap-2">
          {platform === "android" && (
            <button
              type="button"
              onClick={handleInstall}
              className="inline-flex min-h-[44px] items-center gap-1.5 rounded-lg bg-foreground px-4 text-sm font-bold text-background transition-colors hover:opacity-90"
            >
              <Download aria-hidden="true" className="size-4" />
              Installer
            </button>
          )}
          <button
            type="button"
            onClick={handleDismiss}
            className="inline-flex min-h-[44px] items-center gap-1.5 rounded-lg px-3 text-sm font-semibold text-muted-foreground transition-colors hover:text-foreground"
          >
            Ikke nå
          </button>
        </div>
      </div>

      <button
        type="button"
        onClick={handleDismiss}
        aria-label="Lukk installasjonsoppfordringen"
        className="flex size-11 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:text-foreground"
      >
        <X aria-hidden="true" className="size-4" />
      </button>
    </div>
  )
}
