export const getAncestorByType = (node: any, type: string): any => {
  if (!node) return null;
  if (node.type === type) return node;
  if (node.ancestors && Array.isArray(node.ancestors)) {
    return node.ancestors.find((a: any) => a.type === type);
  }
  if (node.parent) {
    if (node.parent.type === type) return node.parent;
    return getAncestorByType(node.parent, type);
  }
  return null;
};

export const getRegionId = (loc: any, stateToRegionId: Record<string, string>, parsedDistricts: any[], parsedStates: any[]): string | null => {
  if (!loc) return null;
  if (typeof loc === 'string') {
    const dObj = parsedDistricts.find((d: any) => d.id === loc || d.districtName === loc);
    if (dObj) return getRegionId(dObj, stateToRegionId, parsedDistricts, parsedStates);
    const sObj = parsedStates.find((s: any) => s.id === loc || s.stateName === loc);
    if (sObj) return getRegionId(sObj, stateToRegionId, parsedDistricts, parsedStates);
    if (stateToRegionId[loc.toUpperCase()]) return stateToRegionId[loc.toUpperCase()];
    return null;
  }
  const regAncestor = getAncestorByType(loc, 'region');
  if (regAncestor?.id) return regAncestor.id;
  if (loc.type === 'region') return loc.id;
  const sName = loc.stateName || loc.state?.name || loc.state?.stateName;
  if (sName && stateToRegionId[sName.toUpperCase()]) return stateToRegionId[sName.toUpperCase()];
  if (loc.type === 'district' || loc.districtName) {
     const dName = loc.districtName || loc.name;
     const dObj = parsedDistricts.find((d: any) => d.districtName === dName || d.id === loc.id);
     if (dObj?.stateId) {
        const sObj = parsedStates.find((s: any) => s.id === dObj.stateId);
        if (sObj?.stateName && stateToRegionId[sObj.stateName.toUpperCase()]) return stateToRegionId[sObj.stateName.toUpperCase()];
     }
  }
  return null;
};

export const getZoneId = (loc: any, regionIdToZoneId: Record<string, string>, stateToRegionId: Record<string, string>, parsedDistricts: any[], parsedStates: any[]) => {
   if (!loc) return null;
   const zon = getAncestorByType(loc, 'zone');
   if (zon?.id) return zon.id;
   if (loc.type === 'zone') return loc.id;
   const rid = getRegionId(loc, stateToRegionId, parsedDistricts, parsedStates);
   if (rid && regionIdToZoneId[rid]) return regionIdToZoneId[rid];
   return loc.zoneId;
};
