"use client"

import { useEffect } from "react"
import { mailBackgroundStyle } from "@/lib/mail-settings/constants"

type HtmlBgState = {
  mailBackground?: string
  layer: string
  fallback: string
}

function readHtmlBgState(): HtmlBgState {
  const html = document.documentElement
  return {
    mailBackground: html.dataset.mailBackground,
    layer: html.style.getPropertyValue("--mail-bg-layer"),
    fallback: html.style.getPropertyValue("--mail-bg-fallback"),
  }
}

function applyHtmlBgState(state: HtmlBgState) {
  const html = document.documentElement
  if (state.mailBackground) {
    html.dataset.mailBackground = state.mailBackground
  } else {
    delete html.dataset.mailBackground
  }
  if (state.layer) {
    html.style.setProperty("--mail-bg-layer", state.layer)
  } else {
    html.style.removeProperty("--mail-bg-layer")
  }
  if (state.fallback) {
    html.style.setProperty("--mail-bg-fallback", state.fallback)
  } else {
    html.style.removeProperty("--mail-bg-fallback")
  }
}

function clearHtmlBg() {
  const html = document.documentElement
  delete html.dataset.mailBackground
  html.style.removeProperty("--mail-bg-layer")
  html.style.removeProperty("--mail-bg-fallback")
}

/** Login shell: fixed Aurore bg (sm+), no user mail background, canvas on xs. */
export function LoginChrome({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    const saved = readHtmlBgState()
    clearHtmlBg()
    return () => applyHtmlBgState(saved)
  }, [])

  const aurora = mailBackgroundStyle("gradient-aurora")

  return (
    <div className="ultimail-login relative flex min-h-dvh flex-col bg-app-canvas sm:bg-transparent">
      <div
        className="pointer-events-none fixed inset-0 -z-10 hidden sm:block"
        style={{
          background: aurora.background,
          backgroundColor: aurora.fallbackColor,
        }}
        aria-hidden
      />
      {children}
    </div>
  )
}
