import { useEffect, useState, useCallback } from "react";

const STORAGE_KEY = "tx.dockVisible";
const EVENT_NAME = "tx:dock-visibility-changed";

function readPref(): boolean {
  if (typeof window === "undefined") return true;
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (raw === null) return true;
    return raw !== "false";
  } catch {
    return true;
  }
}

/**
 * Reads the per-device "show app dock" preference and stays in sync
 * with other components that toggle it within the same tab (via a
 * custom event) or in another tab (via the native `storage` event).
 * Default = true (dock visible).
 */
export function useDockVisible(): [boolean, (next: boolean) => void] {
  const [visible, setVisible] = useState<boolean>(() => readPref());

  useEffect(() => {
    const onCustom = (e: Event) => {
      const ce = e as CustomEvent<{ visible: boolean }>;
      if (typeof ce.detail?.visible === "boolean") {
        setVisible(ce.detail.visible);
      } else {
        setVisible(readPref());
      }
    };
    const onStorage = (e: StorageEvent) => {
      if (e.key === STORAGE_KEY) setVisible(readPref());
    };
    window.addEventListener(EVENT_NAME, onCustom);
    window.addEventListener("storage", onStorage);
    return () => {
      window.removeEventListener(EVENT_NAME, onCustom);
      window.removeEventListener("storage", onStorage);
    };
  }, []);

  const set = useCallback((next: boolean) => {
    try {
      window.localStorage.setItem(STORAGE_KEY, next ? "true" : "false");
    } catch {
      // ignore quota / private-mode errors; in-memory state still updates
    }
    setVisible(next);
    window.dispatchEvent(
      new CustomEvent(EVENT_NAME, { detail: { visible: next } }),
    );
  }, []);

  return [visible, set];
}
