"use client"

export type WaiverStatus = "draft" | "active" | "archived"

export interface VendorWaiverTemplate {
  id: string
  vendorId: string
  name: string
  /** "pdf" = use pdfUrl; "template" = use content */
  type: "pdf" | "template"
  pdfUrl?: string
  content?: string
  status: WaiverStatus
  version: number
  createdAt: string
  updatedAt: string
}

const KEY = "beachlyfe_vendor_waivers_v1"

function canUse() {
  return typeof window !== "undefined" && window.localStorage != null
}

function getAll(): VendorWaiverTemplate[] {
  if (!canUse()) return []
  try {
    const raw = localStorage.getItem(KEY)
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}

function saveAll(list: VendorWaiverTemplate[]) {
  localStorage.setItem(KEY, JSON.stringify(list))
}

function genId() {
  return `waiver_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`
}

export function getVendorWaivers(vendorId: string): VendorWaiverTemplate[] {
  return getAll().filter((w) => w.vendorId === vendorId)
}

export function getVendorWaiverById(waiverId: string, vendorId: string): VendorWaiverTemplate | null {
  const list = getAll()
  return list.find((w) => w.id === waiverId && w.vendorId === vendorId) ?? null
}

export function getActiveWaiver(vendorId: string): VendorWaiverTemplate | null {
  return getVendorWaivers(vendorId).find((w) => w.status === "active") ?? null
}

export function addVendorWaiver(
  vendorId: string,
  data: { name: string; type: "pdf" | "template"; pdfUrl?: string; content?: string }
): VendorWaiverTemplate {
  const existing = getVendorWaivers(vendorId)
  const version = existing.length === 0 ? 1 : Math.max(...existing.map((w) => w.version), 0) + 1
  const now = new Date().toISOString()
  const record: VendorWaiverTemplate = {
    id: genId(),
    vendorId,
    name: data.name.trim(),
    type: data.type,
    pdfUrl: data.pdfUrl,
    content: data.content,
    status: "draft",
    version,
    createdAt: now,
    updatedAt: now,
  }
  const list = getAll()
  list.push(record)
  saveAll(list)
  return record
}

export function updateVendorWaiver(
  waiverId: string,
  vendorId: string,
  updates: Partial<Pick<VendorWaiverTemplate, "name" | "pdfUrl" | "content" | "status">>
): VendorWaiverTemplate | null {
  const list = getAll()
  const idx = list.findIndex((w) => w.id === waiverId && w.vendorId === vendorId)
  if (idx === -1) return null
  const next = { ...list[idx], ...updates, updatedAt: new Date().toISOString() }
  list[idx] = next
  saveAll(list)
  return next
}

/** Set waiver to ACTIVE; set any other ACTIVE for this vendor to ARCHIVED (one ACTIVE per vendor). */
export function publishWaiver(waiverId: string, vendorId: string): VendorWaiverTemplate | null {
  const list = getAll()
  list.forEach((w) => {
    if (w.vendorId === vendorId && w.status === "active") {
      w.status = "archived"
      w.updatedAt = new Date().toISOString()
    }
  })
  const idx = list.findIndex((w) => w.id === waiverId && w.vendorId === vendorId)
  if (idx === -1) return null
  list[idx].status = "active"
  list[idx].updatedAt = new Date().toISOString()
  saveAll(list)
  return list[idx]
}

export function deleteVendorWaiver(waiverId: string, vendorId: string): boolean {
  const list = getAll().filter((w) => !(w.id === waiverId && w.vendorId === vendorId))
  if (list.length === getAll().length) return false
  saveAll(list)
  return true
}
