import { useEffect, useState } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";

export type ViewMode = "list" | "grid";

/**
 * List/grid toggle, persisted per-screen (via `storageKey`) so the choice
 * survives app restarts. Starts as "list" until the stored value loads —
 * that first render is a brief, harmless flash of the default rather than
 * anything worth blocking on with a loading state.
 */
export function useViewMode(storageKey: string): [ViewMode, (mode: ViewMode) => void] {
  const [mode, setMode] = useState<ViewMode>("list");

  useEffect(() => {
    AsyncStorage.getItem(storageKey).then((stored) => {
      if (stored === "grid" || stored === "list") setMode(stored);
    });
  }, [storageKey]);

  const setAndPersist = (next: ViewMode) => {
    setMode(next);
    AsyncStorage.setItem(storageKey, next).catch(() => {});
  };

  return [mode, setAndPersist];
}
