"use client";

import { useEffect, useState } from "react";
import { trackPwaInstalled } from "@/lib/analytics";

// Extend the BeforeInstallPromptEvent type (not in standard lib)
interface BeforeInstallPromptEvent extends Event {
  prompt(): Promise<void>;
  readonly userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
}

// ─── Storage keys ────────────────────────────────────────────────────────────
const KEY_SNOOZED_UNTIL = "tia_install_snoozed_until"; // timestamp ms — re-ask after this
const KEY_VISIT_COUNT   = "tia_install_visit_count";   // int — increment on each page load
const KEY_INSTALLED     = "tia_installed";              // "1" once the user installs

// How many sessions before we first ask (0-indexed — show on the 3rd session)
const MIN_VISITS   = 3;
// How long to wait before re-asking after a "Later" tap (2 days)
const SNOOZE_MS    = 2 * 24 * 60 * 60 * 1000;
// After a hard "No thanks" wait 7 days
const LONG_SNOOZE_MS = 7 * 24 * 60 * 60 * 1000;

function isSnoozed(): boolean {
  const until = localStorage.getItem(KEY_SNOOZED_UNTIL);
  return !!until && Date.now() < Number(until);
}

function snooze(hard = false) {
  localStorage.setItem(KEY_SNOOZED_UNTIL, String(Date.now() + (hard ? LONG_SNOOZE_MS : SNOOZE_MS)));
}

function incrementVisit(): number {
  const current = Number(localStorage.getItem(KEY_VISIT_COUNT) || "0");
  const next = current + 1;
  localStorage.setItem(KEY_VISIT_COUNT, String(next));
  return next;
}

// ─── iOS instructions banner ─────────────────────────────────────────────────
function IOSInstallInstructions({
  onLater, onNo,
}: { onLater: () => void; onNo: () => void }) {
  return (
    <div className="fixed bottom-4 left-4 right-4 z-50 bg-white dark:bg-gray-800 border border-rose-100 dark:border-gray-700 rounded-2xl shadow-xl p-4">
      <div className="flex justify-between items-start mb-2">
        <div className="flex items-center gap-2">
          <span className="text-2xl">🌸</span>
          <div>
            <p className="font-semibold text-gray-900 dark:text-white text-sm">Add Tia to Home Screen</p>
            <p className="text-xs text-gray-500 dark:text-gray-400">Works like a native app — loads instantly</p>
          </div>
        </div>
      </div>
      <div className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 mb-3 bg-gray-50 dark:bg-gray-700/50 rounded-xl px-3 py-2">
        <span>Tap</span>
        <span className="inline-flex items-center justify-center w-7 h-7 bg-white dark:bg-gray-600 rounded-md text-base shadow-sm border border-gray-200 dark:border-gray-500">⬆️</span>
        <span>then choose</span>
        <span className="font-semibold">"Add to Home Screen"</span>
      </div>
      <div className="flex gap-2">
        <button
          onClick={onNo}
          className="flex-1 py-2 rounded-xl text-sm text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700"
        >
          No thanks
        </button>
        <button
          onClick={onLater}
          className="flex-1 py-2 rounded-xl text-sm font-semibold bg-rose-400 text-white"
        >
          Remind me later
        </button>
      </div>
    </div>
  );
}

// ─── Main component ───────────────────────────────────────────────────────────
export function InstallPrompt() {
  const [deferred, setDeferred] = useState<BeforeInstallPromptEvent | null>(null);
  const [isIOS, setIsIOS]       = useState(false);
  const [show, setShow]         = useState(false); // start hidden to avoid flash

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

    // Already installed as PWA — never show
    if (window.matchMedia("(display-mode: standalone)").matches) return;
    if (localStorage.getItem(KEY_INSTALLED) === "1") return;

    // Track visit count; don't ask until the user has had a few sessions
    const visits = incrementVisit();
    if (visits < MIN_VISITS) return;

    // Currently snoozed from a previous "Later" tap
    if (isSnoozed()) return;

    // iOS Safari — no native install event, we show manual instructions
    const ios      = /iphone|ipad|ipod/i.test(navigator.userAgent);
    const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    if (ios && isSafari) {
      setIsIOS(true);
      setShow(true);
    }

    // Android / Chrome — capture the browser's deferred install prompt
    const handler = (e: Event) => {
      e.preventDefault();
      setDeferred(e as BeforeInstallPromptEvent);
      setShow(true);
    };
    window.addEventListener("beforeinstallprompt", handler);
    return () => window.removeEventListener("beforeinstallprompt", handler);
  }, []);

  // "Remind me later" — snooze for 7 days
  const handleLater = () => {
    setShow(false);
    snooze(false);
  };

  // "No thanks" — snooze for 30 days
  const handleNo = () => {
    setShow(false);
    snooze(true);
  };

  // Android: user tapped Install
  const handleInstall = async () => {
    if (!deferred) return;
    await deferred.prompt();
    const { outcome } = await deferred.userChoice;
    if (outcome === "accepted") {
      localStorage.setItem(KEY_INSTALLED, "1");
      trackPwaInstalled();
      setDeferred(null);
      setShow(false);
    } else {
      // They dismissed the native prompt — snooze our custom one too
      handleLater();
    }
  };

  if (!show) return null;

  // iOS: show manual instructions
  if (isIOS) {
    return <IOSInstallInstructions onLater={handleLater} onNo={handleNo} />;
  }

  // Android / Chrome: show install button
  if (deferred) {
    return (
      <div className="fixed bottom-4 left-4 right-4 z-50 bg-white dark:bg-gray-800 border border-rose-100 dark:border-gray-700 rounded-2xl shadow-xl p-4 flex items-center gap-3">
        <span className="text-2xl">🌸</span>
        <div className="flex-1">
          <p className="font-semibold text-gray-900 dark:text-white text-sm">Install Tia</p>
          <p className="text-xs text-gray-500 dark:text-gray-400">Add to home screen — loads instantly</p>
        </div>
        <button onClick={handleLater} className="text-gray-400 dark:text-gray-500 p-1 text-lg" aria-label="Later">✕</button>
        <button
          onClick={handleInstall}
          className="px-4 py-2 bg-rose-400 text-white rounded-xl text-sm font-semibold whitespace-nowrap"
        >
          Install
        </button>
      </div>
    );
  }

  return null;
}
