"use client"

export type VendorQRType = "vendor_profile" | "inventory_item" | "rack" | "beach_hub"

export interface VendorQRRecord {
  id: string
  vendorId: string
  type: VendorQRType
  label: string
  /** Display destination for tracking (e.g. URL or path). Used for QR payload where allowed by mutation rules. */
  destination?: string
  /** For item: itemId; for vendor_profile: optional path; rack/beach_hub: admin-only */
  targetId?: string
  scanCount: number
  createdAt: string
}

export interface QRScanLog {
  id: string
  qrId: string
  scannedAt: string
  /** Mock: optional device/location */
  userAgent?: string
}

const QR_KEY = "beachlyfe_vendor_qr_v1"
const SCANS_KEY = "beachlyfe_vendor_qr_scans_v1"

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

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

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

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

export function getVendorQRs(vendorId: string): VendorQRRecord[] {
  return getAll().filter((q) => q.vendorId === vendorId)
}

export function getVendorQRById(qrId: string, vendorId: string): VendorQRRecord | null {
  const list = getAll()
  const q = list.find((r) => r.id === qrId && r.vendorId === vendorId)
  return q ?? null
}

export function addVendorQR(
  vendorId: string,
  data: Omit<VendorQRRecord, "id" | "vendorId" | "scanCount" | "createdAt">
): VendorQRRecord {
  const record: VendorQRRecord = {
    ...data,
    id: genId("qr"),
    vendorId,
    scanCount: 0,
    createdAt: new Date().toISOString(),
  }
  const list = getAll()
  list.push(record)
  saveAll(list)
  return record
}

export function updateVendorQR(
  qrId: string,
  vendorId: string,
  updates: Partial<Pick<VendorQRRecord, "label" | "destination" | "targetId" | "type">>
): VendorQRRecord | null {
  const list = getAll()
  const idx = list.findIndex((r) => r.id === qrId && r.vendorId === vendorId)
  if (idx < 0) return null
  list[idx] = { ...list[idx], ...updates }
  saveAll(list)
  return list[idx]
}

export function deleteVendorQR(qrId: string, vendorId: string): boolean {
  const list = getAll()
  const next = list.filter((r) => !(r.id === qrId && r.vendorId === vendorId))
  if (next.length === list.length) return false
  saveAll(next)
  return true
}

export function logQRScan(qrId: string) {
  if (!canUse()) return
  const list = getAll()
  const q = list.find((r) => r.id === qrId)
  if (q) {
    q.scanCount += 1
    saveAll(list)
  }
  try {
    const raw = localStorage.getItem(SCANS_KEY)
    const scans: QRScanLog[] = raw ? JSON.parse(raw) : []
    scans.push({
      id: genId("scan"),
      qrId,
      scannedAt: new Date().toISOString(),
      userAgent: typeof navigator !== "undefined" ? navigator.userAgent?.slice(0, 80) : undefined,
    })
    localStorage.setItem(SCANS_KEY, JSON.stringify(scans))
  } catch {
    // ignore
  }
}

export function getQRScanLogs(qrId: string): QRScanLog[] {
  if (!canUse()) return []
  try {
    const raw = localStorage.getItem(SCANS_KEY)
    const list: QRScanLog[] = raw ? JSON.parse(raw) : []
    return list.filter((s) => s.qrId === qrId).sort((a, b) => new Date(b.scannedAt).getTime() - new Date(a.scannedAt).getTime())
  } catch {
    return []
  }
}
