"use client"

import { useEffect, useRef } from "react"
import { useOrgSettings } from "@/lib/api/hooks/use-org-settings"
import {
  apiOrgPolicyToStore,
  apiOrgSettingsMeta,
} from "@/lib/admin-settings/map-api-org-settings"
import { useOrgSettingsStore } from "@/lib/admin-settings/org-settings-store"

export function OrgSettingsSync() {
  const { data } = useOrgSettings()
  const hydratingRef = useRef(false)

  useEffect(() => {
    if (!data) return
    try {
      hydratingRef.current = true
      const mapped = apiOrgPolicyToStore(data.policy)
      const meta = apiOrgSettingsMeta(data)
      useOrgSettingsStore.getState().hydrateFromApi(mapped, meta)
    } catch (err) {
      console.error("org settings hydrate failed", err)
    } finally {
      queueMicrotask(() => {
        hydratingRef.current = false
      })
    }
  }, [data])

  return null
}
