"use client";

import { createContext, useContext, useState, useEffect } from "react";
import citiesData from "@/data/city.json";
import { isRootCity } from "@/lib/rootCity";

const ProvinceContext = createContext();

export const ProvinceProvider = ({ children }) => {
  const [hostName, setHostName] = useState("");
  const matched = citiesData.find((city) =>
    hostName.includes(city.domain.split(".")[0]),
  );
  // دامنهٔ ریشه (nobat724) شهر نیست → «شهری انتخاب نشده».
  const isProvinceInclude = isRootCity(matched) ? null : matched;

  useEffect(() => {
    if (typeof window !== "undefined") {
      setHostName(window.location.hostname);
    }
  }, []);

  return (
    <ProvinceContext.Provider value={{ isProvinceInclude, cityId: isProvinceInclude?.id ?? null }}>
      {children}
    </ProvinceContext.Provider>
  );
};

export const useProvince = () => useContext(ProvinceContext);
