const SITE_NAME = 'Trainingstagebuch';
const SITE_URL = 'https://tt-tagebuch.de';
const DEFAULT_IMAGE = `${SITE_URL}/android-chrome-512x512.png`;

const DEFAULT_SEO = {
  title: 'Trainingstagebuch – Vereinsverwaltung für Tischtennis, Trainingsplanung & Turniere',
  description: 'Trainingstagebuch ist die Software für Tischtennisvereine: Mitgliederverwaltung, Trainingsplanung, Trainingstagebuch, Gruppen, Turniere, Team-Management, Statistiken und MyTischtennis-Integration.',
  robots: 'index,follow'
};

const ROUTE_SEO = {
  '/': {
    title: DEFAULT_SEO.title,
    description: DEFAULT_SEO.description,
    robots: 'index,follow'
  },
  '/login': {
    title: 'Login | Trainingstagebuch',
    description: 'Im Trainingstagebuch einloggen und Vereinsdaten, Trainingsplanung, Mitglieder und Turniere verwalten.',
    robots: 'noindex,follow'
  },
  '/register': {
    title: 'Registrieren | Trainingstagebuch',
    description: 'Kostenlos im Trainingstagebuch registrieren und die Vereinsverwaltung für Tischtennisvereine kennenlernen.',
    robots: 'noindex,follow'
  },
  '/activate': {
    title: 'Konto aktivieren | Trainingstagebuch',
    description: 'Aktivierung des Benutzerkontos im Trainingstagebuch.',
    robots: 'noindex,follow'
  },
  '/forgot-password': {
    title: 'Passwort vergessen | Trainingstagebuch',
    description: 'Zugang zum Trainingstagebuch wiederherstellen.',
    robots: 'noindex,follow'
  },
  '/reset-password': {
    title: 'Passwort zurücksetzen | Trainingstagebuch',
    description: 'Passwort im Trainingstagebuch sicher zurücksetzen.',
    robots: 'noindex,follow'
  },
  '/impressum': {
    title: 'Impressum | Trainingstagebuch',
    description: 'Impressum von Trainingstagebuch.',
    robots: 'noindex,follow'
  },
  '/datenschutz': {
    title: 'Datenschutzerklärung | Trainingstagebuch',
    description: 'Datenschutzerklärung von Trainingstagebuch.',
    robots: 'noindex,follow'
  }
};

function normalizePath(path = '/') {
  if (!path || path === '') return '/';
  if (path === '/') return '/';
  return path.endsWith('/') ? path.slice(0, -1) : path;
}

export function getSeoConfigForPath(path) {
  const normalizedPath = normalizePath(path);
  const matchedPrefix = Object.keys(ROUTE_SEO)
    .filter((routePath) => routePath !== '/' && normalizedPath.startsWith(routePath))
    .sort((a, b) => b.length - a.length)[0];

  const routeSeo = (matchedPrefix && ROUTE_SEO[matchedPrefix]) || ROUTE_SEO[normalizedPath] || DEFAULT_SEO;
  const canonicalPath = normalizedPath === '/' ? '' : normalizedPath;

  return {
    title: routeSeo.title || DEFAULT_SEO.title,
    description: routeSeo.description || DEFAULT_SEO.description,
    robots: routeSeo.robots || DEFAULT_SEO.robots,
    canonical: `${SITE_URL}${canonicalPath}`,
    url: `${SITE_URL}${canonicalPath}`,
    image: DEFAULT_IMAGE
  };
}

function upsertMeta(selector, attributes) {
  let element = document.head.querySelector(selector);

  if (!element) {
    element = document.createElement('meta');
    document.head.appendChild(element);
  }

  Object.entries(attributes).forEach(([key, value]) => {
    element.setAttribute(key, value);
  });
}

function upsertLink(selector, attributes) {
  let element = document.head.querySelector(selector);

  if (!element) {
    element = document.createElement('link');
    document.head.appendChild(element);
  }

  Object.entries(attributes).forEach(([key, value]) => {
    element.setAttribute(key, value);
  });
}

export function applySeoForPath(path) {
  if (typeof document === 'undefined') {
    return;
  }

  const seo = getSeoConfigForPath(path);

  document.title = seo.title;

  upsertMeta('meta[name="description"]', { name: 'description', content: seo.description });
  upsertMeta('meta[name="robots"]', { name: 'robots', content: seo.robots });
  upsertMeta('meta[property="og:type"]', { property: 'og:type', content: 'website' });
  upsertMeta('meta[property="og:site_name"]', { property: 'og:site_name', content: SITE_NAME });
  upsertMeta('meta[property="og:title"]', { property: 'og:title', content: seo.title });
  upsertMeta('meta[property="og:description"]', { property: 'og:description', content: seo.description });
  upsertMeta('meta[property="og:url"]', { property: 'og:url', content: seo.url });
  upsertMeta('meta[property="og:image"]', { property: 'og:image', content: seo.image });
  upsertMeta('meta[name="twitter:card"]', { name: 'twitter:card', content: 'summary_large_image' });
  upsertMeta('meta[name="twitter:title"]', { name: 'twitter:title', content: seo.title });
  upsertMeta('meta[name="twitter:description"]', { name: 'twitter:description', content: seo.description });
  upsertMeta('meta[name="twitter:image"]', { name: 'twitter:image', content: seo.image });
  upsertLink('link[rel="canonical"]', { rel: 'canonical', href: seo.canonical });
}
