export type PublicShareRootType = "file" | "folder"

export function publicShareRootTypeStorageKey(token: string): string {
  return `public-share-root-type:${token}`
}

export function persistPublicShareRootType(token: string, rootType: PublicShareRootType): void {
  if (typeof window === "undefined") return
  sessionStorage.setItem(publicShareRootTypeStorageKey(token), rootType)
}

export function readPublicShareRootType(token: string): PublicShareRootType | null {
  if (typeof window === "undefined") return null
  const value = sessionStorage.getItem(publicShareRootTypeStorageKey(token))
  return value === "file" || value === "folder" ? value : null
}

/** Hide back on single-file shares — no folder listing to return to. */
export function shouldShowPublicShareEditorBack(
  rootType: PublicShareRootType | null | undefined,
  returnTo?: string | null,
  filePath?: string
): boolean {
  if (rootType === "file") return false
  if (rootType === "folder") return true
  const path = (filePath ?? "/").replace(/^\/+|\/+$/g, "")
  if (!path && !returnTo) return false
  return true
}

export function buildPublicShareEditHref(
  token: string,
  filePath: string,
  returnTo?: string,
  mode: "edit" | "view" = "edit",
  displayName?: string,
  editor: "office" | "richtext" | "ultidraw" = "office",
  shareRoot?: PublicShareRootType
): string {
  const trimmed = filePath.replace(/^\/+|\/+$/g, "")
  const base = `/drive/s/${encodeURIComponent(token)}/edit/${trimmed.split("/").map(encodeURIComponent).join("/")}`
  const params = new URLSearchParams()
  if (returnTo && returnTo.startsWith("/drive/s/")) {
    params.set("returnTo", returnTo)
  }
  if (mode === "view") {
    params.set("mode", "view")
  }
  if (editor === "richtext") {
    params.set("editor", "richtext")
  }
  if (editor === "ultidraw") {
    params.set("editor", "ultidraw")
  }
  if (displayName?.trim()) {
    params.set("name", displayName.trim())
  }
  if (shareRoot) {
    params.set("shareRoot", shareRoot)
  }
  const qs = params.toString()
  return qs ? `${base}?${qs}` : base
}

export function resolvePublicShareEditReturnTo(
  token: string,
  returnTo: string | null | undefined,
  filePath: string
): string {
  if (returnTo && returnTo.startsWith("/drive/s/")) return returnTo
  const parent = filePath.replace(/\/[^/]+$/, "") || "/"
  const trimmed = parent.replace(/^\/+|\/+$/g, "")
  if (!trimmed) return `/drive/s/${encodeURIComponent(token)}`
  return `/drive/s/${encodeURIComponent(token)}/${trimmed.split("/").map(encodeURIComponent).join("/")}`
}

export function filePathFromPublicEditSegments(
  token: string,
  segments: string[] | undefined
): string {
  if (!segments?.length) return "/"
  return "/" + segments.map((s) => decodeURIComponent(s)).join("/")
}
