import { useLayoutEffect, useState } from "react"
import { readCoarsePointerMatches } from "@/hooks/use-touch-nav"
import { readLgMatches } from "@/hooks/use-lg-breakpoint"
import { MD_MIN_PX } from "@/hooks/use-md-breakpoint"
import { useMailSettingsStore } from "@/lib/stores/mail-settings-store"
import type { ReadingPaneMode } from "@/lib/mail-settings/types"

const MD_MQ = `(min-width: ${MD_MIN_PX}px)`
const LANDSCAPE_MQ = "(orientation: landscape)"

export function readMailSplitViewMatches(
  readingPane: ReadingPaneMode = "none"
): boolean {
  if (typeof window === "undefined") return false
  if (!window.matchMedia(MD_MQ).matches) return false

  const coarse = readCoarsePointerMatches()
  const tabletLandscape =
    coarse && window.matchMedia(LANDSCAPE_MQ).matches

  if (readLgMatches()) {
    if (readingPane === "right") return true
    if (readingPane === "none") return tabletLandscape
    return false
  }

  return tabletLandscape
}

export function useMailSplitView() {
  const readingPane = useMailSettingsStore((s) => s.readingPane)
  const [splitView, setSplitView] = useState(false)

  useLayoutEffect(() => {
    const mqlMd = window.matchMedia(MD_MQ)
    const mqlLandscape = window.matchMedia(LANDSCAPE_MQ)
    const mqlCoarse = window.matchMedia(
      "(hover: none) and (pointer: coarse)"
    )
    const update = () =>
      setSplitView(readMailSplitViewMatches(readingPane))
    update()
    mqlMd.addEventListener("change", update)
    mqlLandscape.addEventListener("change", update)
    mqlCoarse.addEventListener("change", update)
    window
      .matchMedia(`(min-width: 1024px)`)
      .addEventListener("change", update)
    return () => {
      mqlMd.removeEventListener("change", update)
      mqlLandscape.removeEventListener("change", update)
      mqlCoarse.removeEventListener("change", update)
      window
        .matchMedia(`(min-width: 1024px)`)
        .removeEventListener("change", update)
    }
  }, [readingPane])

  return splitView
}
