import { locationData } from "../client/src/data/locationData";

const staticRoutes = [
  "",
  "/sell-your-house-fast.html",
  "/how-it-works.html",
  "/situations.html",
  "/locations.html",
  "/about.html",
  "/contact.html",
  "/privacy.html",
  "/terms.html",
  "/sell-as-is.html",
  "/foreclosure-help.html",
  "/sell-inherited-property.html",
  "/sell-during-divorce.html",
  "/seller-insights.html",
  "/compare-selling-options.html",
  "/blog.html",
  "/cash-sale-benefits.html",
];

const xmlEscape = (value: string) =>
  value.replace(/[<>&'\"]/g, character => ({
    "<": "&lt;",
    ">": "&gt;",
    "&": "&amp;",
    "'": "&apos;",
    "\"": "&quot;",
  })[character] ?? character);

function urlEntry(url: string, changeFrequency: "weekly" | "monthly", priority: string) {
  return [
    "  <url>",
    `    <loc>${xmlEscape(url)}</loc>`,
    `    <changefreq>${changeFrequency}</changefreq>`,
    `    <priority>${priority}</priority>`,
    "  </url>",
  ].join("\n");
}

export function buildSitemap(baseUrl: string) {
  const base = baseUrl.replace(/\/$/, "");
  const entries = staticRoutes.map(route => urlEntry(`${base}${route}`, "weekly", route === "" ? "1.0" : "0.8"));

  for (const [state, counties] of Object.entries(locationData)) {
    entries.push(urlEntry(`${base}/areas-we-serve/${state}/`, "monthly", "0.7"));
    for (const county of counties) {
      entries.push(urlEntry(`${base}/areas-we-serve/${state}/${county}/`, "monthly", "0.6"));
    }
  }

  return [
    '<?xml version="1.0" encoding="UTF-8"?>',
    '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
    ...entries,
    "</urlset>",
  ].join("\n");
}
