import type { TTenderDetails } from "@/lib/api/types/Tenders";
import { TENDER_SECTION_IDS } from "./constants";
import type { TenderNavItem } from "./types";
import {
  isValidRegionCode,
  shouldShowAiSummarySection,
  shouldShowDescriptionSection,
  shouldShowLotsSection,
  shouldShowTranslationSection,
} from "./tender-display-utils";

export const isValidDisplayCountryCode = (code: string) =>
  /^[A-Za-z]{2,3}$/.test(code);

function analyzeLocationVisibility(tender: TTenderDetails) {
  const countryNorm = tender.country_code?.trim().toUpperCase() ?? "";
  const hasCountry = isValidDisplayCountryCode(countryNorm);
  const currency = tender.currency?.trim().toUpperCase() ?? "";
  const hasCurrency = Boolean(currency);
  const hasEst =
    typeof tender.estimated_value === "number" &&
    Number.isFinite(tender.estimated_value) &&
    tender.estimated_value > 0;
  const hasRegion = isValidRegionCode(tender.region_code);
  const showLocation = hasCountry || hasCurrency || hasEst || hasRegion;
  return { showLocation };
}

export function getTenderNavItems(
  tender: TTenderDetails,
  options?: { showDocuments?: boolean },
): TenderNavItem[] {
  const { showLocation } = analyzeLocationVisibility(tender);
  const showDocuments = options?.showDocuments ?? true;

  const items: TenderNavItem[] = [
    { id: TENDER_SECTION_IDS.procurement, label: "Procurement" },
  ];
  if (shouldShowLotsSection(tender)) {
    items.push({ id: TENDER_SECTION_IDS.lots, label: "Lots" });
  }
  items.push({ id: TENDER_SECTION_IDS.timeline, label: "Timeline" });
  if (showLocation) {
    items.push({
      id: TENDER_SECTION_IDS.location,
      label: "Location & currency",
    });
  }
  if (shouldShowTranslationSection(tender)) {
    items.push({ id: TENDER_SECTION_IDS.translation, label: "Translation" });
  }
  if (showDocuments) {
    items.push({ id: TENDER_SECTION_IDS.documents, label: "Documents" });
  }
  if (shouldShowDescriptionSection(tender)) {
    items.push({ id: TENDER_SECTION_IDS.description, label: "Description" });
  }
  if (shouldShowAiSummarySection(tender)) {
    items.push({ id: TENDER_SECTION_IDS.aiSummary, label: "AI summary" });
  }
  return items;
}

export function shouldShowLocationSection(tender: TTenderDetails): boolean {
  return analyzeLocationVisibility(tender).showLocation;
}
