import { ref, computed, type ComputedRef, type Ref } from "vue";
import type { Column } from "../types";

export type ColumnVisibilityState = {
  hiddenColumns: Ref<Set<string>>;
  visibleColumns: ComputedRef<Column[]>;
  toggleColumn: (key: string) => void;
  resetVisibility: () => void;
};

export function useColumnVisibility(
  slug: string,
  columns: Ref<Column[]>,
): ColumnVisibilityState {
  const STORAGE_KEY = `builder.table.${slug}.hidden_columns`;

  function loadFromStorage(): Set<string> {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        return new Set<string>(JSON.parse(stored));
      }
    } catch {
      // ignore parse errors
    }

    // Default: columns with hidden === true
    return new Set(columns.value.filter((c) => c.hidden).map((c) => c.key));
  }

  const hiddenColumns = ref<Set<string>>(loadFromStorage());

  const visibleColumns = computed(() =>
    columns.value.filter((c) => !hiddenColumns.value.has(c.key)),
  );

  function toggleColumn(key: string): void {
    const next = new Set(hiddenColumns.value);
    if (next.has(key)) {
      next.delete(key);
    } else {
      next.add(key);
    }
    hiddenColumns.value = next;
    localStorage.setItem(STORAGE_KEY, JSON.stringify(Array.from(next)));
  }

  function resetVisibility(): void {
    const defaults = new Set(
      columns.value.filter((c) => c.hidden).map((c) => c.key),
    );
    hiddenColumns.value = defaults;
    localStorage.removeItem(STORAGE_KEY);
  }

  return { hiddenColumns, visibleColumns, toggleColumn, resetVisibility };
}
