import type { Metadata } from "next"
import { SUITE_TITLE_SEP } from "@/lib/suite/page-metadata"

export type DriveEditorKind = "docs" | "sheets" | "presentation" | "draw"

export const DRIVE_EDITOR_LABELS: Record<DriveEditorKind, string> = {
  docs: "UltiDocs",
  sheets: "Sheets",
  presentation: "Presentation",
  draw: "Draw",
}

export const DRIVE_EDITOR_FAVICONS: Record<DriveEditorKind, string> = {
  docs: "/drive/ultidocs-mark.svg",
  sheets: "/drive/ultisheets-mark.svg",
  presentation: "/drive/ultislides-mark.svg",
  draw: "/drive/ultidraw-mark.svg",
}

export function driveEditorDocumentTitle(
  titleSegment: string,
  kind: DriveEditorKind
): string {
  const trimmed = titleSegment.trim()
  const label = DRIVE_EDITOR_LABELS[kind]
  if (!trimmed) return label
  return `${trimmed}${SUITE_TITLE_SEP}${label}`
}

export function driveEditorPageMetadata(
  kind: DriveEditorKind,
  titleSegment?: string
): Metadata {
  const label = DRIVE_EDITOR_LABELS[kind]
  const favicon = DRIVE_EDITOR_FAVICONS[kind]

  return {
    title:
      titleSegment !== undefined
        ? {
            default: titleSegment,
            template: `%s${SUITE_TITLE_SEP}${label}`,
          }
        : label,
    icons: {
      icon: [{ url: favicon, type: "image/svg+xml" }],
      apple: [{ url: favicon, type: "image/svg+xml" }],
      shortcut: favicon,
    },
  }
}

function iconLinks(): HTMLLinkElement[] {
  return Array.from(
    document.querySelectorAll<HTMLLinkElement>(
      'link[rel="icon"], link[rel="shortcut icon"], link[rel="apple-touch-icon"]'
    )
  )
}

export function applyDriveEditorFavicon(kind: DriveEditorKind): () => void {
  const href = DRIVE_EDITOR_FAVICONS[kind]
  const links = iconLinks()
  const previous = links.map((link) => ({
    link,
    href: link.getAttribute("href"),
    type: link.getAttribute("type"),
  }))

  if (links.length === 0) {
    const link = document.createElement("link")
    link.rel = "icon"
    link.type = "image/svg+xml"
    link.href = href
    document.head.appendChild(link)
    return () => {
      link.remove()
    }
  }

  for (const link of links) {
    link.href = href
    link.type = "image/svg+xml"
  }

  return () => {
    for (const { link, href: prevHref, type } of previous) {
      if (prevHref == null) {
        link.remove()
        continue
      }
      link.href = prevHref
      if (type) link.type = type
      else link.removeAttribute("type")
    }
  }
}
