import type { IProject } from '../types';

export type ProjectSegment = 'residential' | 'commercial';

export const PROJECT_SEGMENT_OVERRIDES_KEY = 'project-segment-overrides';

export function readProjectSegmentOverrides(): Record<string, ProjectSegment> {
  try {
    const raw = localStorage.getItem(PROJECT_SEGMENT_OVERRIDES_KEY);
    if (!raw) return {};
    const parsed = JSON.parse(raw) as Record<string, ProjectSegment>;
    return parsed && typeof parsed === 'object' ? parsed : {};
  } catch {
    return {};
  }
}

export function clearProjectSegmentOverride(projectId: string): void {
  try {
    const raw = localStorage.getItem(PROJECT_SEGMENT_OVERRIDES_KEY);
    if (!raw) return;
    const parsed = JSON.parse(raw) as Record<string, ProjectSegment>;
    if (parsed && typeof parsed === 'object') {
      delete parsed[projectId];
      localStorage.setItem(PROJECT_SEGMENT_OVERRIDES_KEY, JSON.stringify(parsed));
    }
  } catch (e) {
    console.warn('Failed to clear project segment override:', e);
  }
}

/** Ưu tiên trường segment từ server (MongoDB); sau đó override local (nếu truyền); cuối cùng là suy luận. */
export function resolveProjectSegment(
  site: IProject,
  storageOverrides?: Record<string, ProjectSegment> | null
): ProjectSegment {
  // 1. Prioritize explicit segment from server (case-insensitive check)
  const serverSegment = site.segment || (site as any).projectType || (site as any).type || (site as any).portfolioType;
  if (serverSegment) {
    const s = String(serverSegment).toLowerCase();
    if (s.includes('residential')) return 'residential';
    if (s.includes('commercial')) return 'commercial';
  }

  const id =
    typeof site._id === 'string'
      ? site._id
      : site._id != null && typeof (site._id as { toString?: () => string }).toString === 'function'
        ? String((site._id as { toString: () => string }).toString())
        : '';

  // 2. Fallback to storage overrides (UI overrides)
  const fromReactState = id && storageOverrides ? storageOverrides[id] : undefined;
  const fromStorage =
    fromReactState ?? (id ? readProjectSegmentOverrides()[id] : undefined);
  if (fromStorage) return fromStorage;

  // 3. Final fallback: inference from name/code/address
  return inferProjectSegmentFromSite(site);
}

/** Phân loại từ dữ liệu dự án (không đọc override localStorage). */
export function inferProjectSegmentFromSite(site: IProject): ProjectSegment {
  const projectMeta = site as IProject & Record<string, unknown>;
  const explicitSegmentKeys = ['segment', 'projectType', 'type', 'category', 'portfolioType'] as const;

  for (const key of explicitSegmentKeys) {
    const rawValue = projectMeta[key];
    if (typeof rawValue === 'string') {
      const normalized = rawValue.toLowerCase();
      if (normalized.includes('residential')) return 'residential';
      if (normalized.includes('commercial')) return 'commercial';
    }
  }

  const combinedText = `${site.name} ${site.code} ${site.location.address}`.toLowerCase();
  const residentialKeywords = ['residential', 'khu dan cu', 'chung cu', 'can ho', 'nha o', 'villa', 'housing'];
  if (residentialKeywords.some((keyword) => combinedText.includes(keyword))) {
    return 'residential';
  }

  return 'commercial';
}

/** Dùng cho Topbar / ProjectSelector: segment từ server trước, rồi localStorage, rồi suy luận. */
export function getDisplayedProjectSegment(site: IProject): ProjectSegment {
  return resolveProjectSegment(site, null);
}
