/**
 * Row highlighting for transaction rows on the Banking page — TWO independent
 * mechanisms (Import tab → Umsätze, Reconcile → Positionen):
 *
 * 1. MARKS (checkbox, multi): checking a row's checkbox toggles a persistent
 *    amber mark (`bk-row--marked`) that is KEPT until unchecked — survives
 *    reloads, tab switches and re-fetches (ids in localStorage, keyed per
 *    list). Marking multiple rows is ONLY possible via the checkboxes.
 * 2. CURRENT ROW (plain row click, single): clicking anywhere else on a row
 *    highlights ONLY that row (`bk-row--current`); clicking another row moves
 *    the highlight there, clicking the same row again removes it. Exactly one
 *    row per list can be current.
 *
 * Purely a visual work-aid: nothing is sent to Laravel / iDempiere.
 */
export const useBankingMarks = (listKey: string) => {
  const storageKey = 'logship_banking_marks_' + listKey
  const activeStorageKey = storageKey + '_active'
  // useState → one shared Set per list across component instances (keep-alive safe)
  const marked = useState<string[]>('bankingMarks:' + listKey, () => [])
  const active = useState<string>('bankingActive:' + listKey, () => '')

  const load = () => {
    if (!import.meta.client) return
    try {
      const raw = localStorage.getItem(storageKey)
      const arr = raw ? JSON.parse(raw) : []
      if (Array.isArray(arr)) marked.value = arr.map(String)
      active.value = localStorage.getItem(activeStorageKey) || ''
    } catch { /* ignore — no persistence available */ }
  }
  const persist = () => {
    if (!import.meta.client) return
    try {
      localStorage.setItem(storageKey, JSON.stringify(marked.value))
      localStorage.setItem(activeStorageKey, active.value)
    } catch { /* ignore */ }
  }

  if (import.meta.client && marked.value.length === 0 && !active.value) load()

  const markedSet = computed(() => new Set(marked.value))
  const isMarked = (id: any) => markedSet.value.has(String(id))
  const toggleMark = (id: any) => {
    const key = String(id)
    marked.value = isMarked(key) ? marked.value.filter(k => k !== key) : [...marked.value, key]
    persist()
  }
  const clearMarks = () => { marked.value = []; persist() }
  const count = computed(() => marked.value.length)

  const isActive = (id: any) => active.value !== '' && active.value === String(id)
  const clearActive = () => { active.value = ''; persist() }

  /**
   * Row click handler: make this row the single CURRENT row (click again →
   * off) — unless the click landed on an interactive child (button / link /
   * input / label), which keeps its own behaviour. Never touches the marks:
   * multi-marking is checkbox-only.
   */
  const onRowClick = (e: MouseEvent, id: any) => {
    const target = e?.target as HTMLElement | null
    if (target?.closest?.('button, a, input, select, textarea, label')) return
    active.value = isActive(id) ? '' : String(id)
    persist()
  }

  return { marked, isMarked, toggleMark, clearMarks, count, isActive, clearActive, onRowClick }
}
