import { json, type LoaderFunctionArgs, type MetaFunction } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import React, { Suspense, useEffect } from "react";
import UAParser from "ua-parser-js"
import versionAtLeast from "semver/functions/gte"
import coerceSemver from "semver/functions/coerce"

export const meta: MetaFunction = () => {
  return [
    { title: "Tack Up Now!" },
    { name: "description", content: "Get equinelive notifications" },
  ];
};

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const userAgent = request.headers.get("user-agent")
  const os = new UAParser(userAgent ?? "").getOS()
  const isSupported =
      os.name !== "iOS" ||
      versionAtLeast(coerceSemver(os.version) ?? "0.0.0", "16.4.0")

  return json({ isSupported })
}

export default function Index() {
  
  const { isSupported } = useLoaderData<typeof loader>()

  return (
    <div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>
      <Suspense>
      <LandingMessage isSupported={isSupported}/>
      </Suspense>
    </div>
  );
}


function LandingMessage({ isSupported }: { isSupported: boolean }) {

  if (typeof window === "undefined") return <div>Loading</div>

  const isRunningPWA = ("standalone" in navigator && navigator.standalone as boolean) || matchMedia("(dislay-mode: standalone)").matches
  const notificationsEnabled = "Notification" in window && window.Notification.permission === "granted"
  const message = isRunningPWA && !notificationsEnabled
      ? "Enable notifications"
      : isSupported
      ? "Install Tack Up Now!"
      : "Sorry, your device doesn't support Tack Up Now! :("

  return <div><div>{message}</div></div>
}
