// hooks/useActiveOrg.ts (client)
"use client";
import { useEffect, useState, useCallback } from "react";
import Cookies from "js-cookie";

type Org = { id: string; name: string };
type Options = {};

export function useActiveOrg(_: Options = {}) {
  const [org, setOrg] = useState<Org | null>(null);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    // Single source of truth: cookie "active_org_id" for the active organization.
    const id = Cookies.get("active_org_id") || null;
    const name = (id ? localStorage.getItem("company_name") : null) || null;
    setOrg(id && name ? { id, name } : id ? { id, name: "" } : null);
    setReady(true);
  }, []);

  const selectOrg = useCallback((next: Org) => {
    // Persist the active organization in the cookie (server and other tabs read it)
    Cookies.set("active_org_id", next.id, { sameSite: "lax", secure: true });
    localStorage.setItem("company_name", next.name); // UI mirror
    setOrg(next);
  }, []);

  const clearOrg = useCallback(() => {
    Cookies.remove("active_org_id");
    localStorage.removeItem("company_name");
    setOrg(null);
  }, []);

  return { org, ready, selectOrg, clearOrg };
}