// src/seo.jsx — per-route metadata for the hash-based MVP

const SEO_SITE = {
  name: "ACCORD GROUP",
  domain: "https://accordgroup.by",
  defaultImage: "/screenshots/01-home.jpg",
  email: "hello@accordgroup.by",
  phone: "+375447275017",
  telegram: "https://t.me/accord_supply",
};

const SEO_ROUTES = {
  home: {
    path: "/",
    title: "ACCORD GROUP — Импорт, экспорт и поставки под ключ",
    description: "B2B-импорт, экспорт, подбор поставщиков, закупки и международная логистика для компаний из РБ, РФ и СНГ.",
  },
  about: {
    path: "/#about",
    title: "О компании ACCORD GROUP — B2B-импорт, экспорт и логистика",
    description: "ACCORD GROUP помогает B2B-клиентам из РБ, РФ и СНГ с нестандартными поставками, закупками, агентированием и международной логистикой.",
  },
  services: {
    path: "/#services",
    title: "Услуги ACCORD GROUP — закупки, поставщики, логистика, импорт и экспорт",
    description: "Закупки под заказ, подбор поставщика, международная логистика, импорт, экспорт, агентирование и консультации по поставкам.",
  },
  contacts: {
    path: "/#contacts",
    title: "Контакты ACCORD GROUP — заявка на поставку или консультацию",
    description: "Свяжитесь с ACCORD GROUP, чтобы обсудить закупку, импорт, экспорт, логистику или подбор поставщика для B2B-задачи.",
  },
  request: {
    path: "/#request",
    title: "Оставить заявку — ACCORD GROUP",
    description: "Опишите задачу по поставке, закупке, логистике или подбору поставщика. ACCORD GROUP подготовит первичную оценку.",
    robots: "noindex,follow",
  },
  privacy: {
    path: "/#privacy",
    title: "Политика конфиденциальности — ACCORD GROUP",
    description: "Политика обработки персональных данных ACCORD GROUP.",
    robots: "noindex,follow",
  },
  consent: {
    path: "/#consent",
    title: "Согласие на обработку персональных данных — ACCORD GROUP",
    description: "Согласие на обработку персональных данных при отправке форм на сайте ACCORD GROUP.",
    robots: "noindex,follow",
  },
};

function absoluteUrl(path) {
  if (!path) return SEO_SITE.domain + "/";
  if (/^https?:\/\//.test(path)) return path;
  return SEO_SITE.domain.replace(/\/$/, "") + (path.startsWith("/") ? path : `/${path}`);
}

function setMeta(selector, attr, value) {
  let el = document.head.querySelector(selector);
  if (!el) {
    el = document.createElement("meta");
    const match = selector.match(/\[(name|property)="([^"]+)"\]/);
    if (match) el.setAttribute(match[1], match[2]);
    document.head.appendChild(el);
  }
  el.setAttribute(attr, value);
}

function setLink(rel, href) {
  let el = document.head.querySelector(`link[rel="${rel}"]`);
  if (!el) {
    el = document.createElement("link");
    el.setAttribute("rel", rel);
    document.head.appendChild(el);
  }
  el.setAttribute("href", href);
}

function setRouteJsonLd(route, cfg, url) {
  let el = document.getElementById("route-jsonld");
  if (!el) {
    el = document.createElement("script");
    el.type = "application/ld+json";
    el.id = "route-jsonld";
    document.head.appendChild(el);
  }
  el.textContent = JSON.stringify({
    "@context": "https://schema.org",
    "@type": "WebPage",
    "@id": `${url}#webpage`,
    url,
    name: cfg.title,
    description: cfg.description,
    inLanguage: "ru-RU",
    isPartOf: {
      "@id": `${SEO_SITE.domain}/#website`,
    },
    about: route === "services"
      ? {
          "@id": `${SEO_SITE.domain}/#service`,
        }
      : {
          "@id": `${SEO_SITE.domain}/#organization`,
        },
  });
}

function updateSeo(route) {
  const cfg = SEO_ROUTES[route] || SEO_ROUTES.home;
  const url = absoluteUrl(cfg.path);
  const image = absoluteUrl(SEO_SITE.defaultImage);
  const robots = cfg.robots || "index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1";

  document.title = cfg.title;
  document.documentElement.lang = "ru";
  setLink("canonical", url);
  setMeta('meta[name="description"]', "content", cfg.description);
  setMeta('meta[name="robots"]', "content", robots);
  setMeta('meta[property="og:title"]', "content", cfg.title);
  setMeta('meta[property="og:description"]', "content", cfg.description);
  setMeta('meta[property="og:url"]', "content", url);
  setMeta('meta[property="og:image"]', "content", image);
  setMeta('meta[name="twitter:title"]', "content", cfg.title);
  setMeta('meta[name="twitter:description"]', "content", cfg.description);
  setMeta('meta[name="twitter:image"]', "content", image);
  setRouteJsonLd(route, cfg, url);
}

Object.assign(window, {
  SEO_SITE,
  SEO_ROUTES,
  updateSeo,
});
