// LUXOMES — Dynamic per-page SEO
// Applies title, meta description, canonical URL, OpenGraph + JSON-LD per route.
// Called from App on every page change.

const SITE_URL = "https://luxomes.com";
const SITE_NAME = "LUXOMES";
const SITE_DESCRIPTION_DE = "Designorientierte Serviced Apartments in München, Nürnberg, Ingolstadt und Vilshofen — digitaler Check-in, Top-Lagen, faire Preise.";
const SITE_DESCRIPTION_EN = "Design-driven serviced apartments in Munich, Nuremberg, Ingolstadt and Vilshofen — digital check-in, prime locations, fair prices.";
const SITE_OG_IMAGE = SITE_URL + "/assets/og-image.jpg";

// Map of page → SEO meta. Functions allow lazy access to dynamic data (location, blog).
const PAGE_SEO = {
  home: (lang) => ({
    title: lang === "de"
      ? "LUXOMES — Serviced Apartments in Deutschland · Feel like Home"
      : "LUXOMES — Serviced Apartments in Germany · Feel like Home",
    description: lang === "de" ? SITE_DESCRIPTION_DE : SITE_DESCRIPTION_EN,
    keywords: "serviced apartments, kurzzeitvermietung, apartment münchen, apartment nürnberg, apartment ingolstadt, apartment vilshofen, aparthotel bayern, design apartment, business apartment, monatsapartment, feel like home",
    path: "/",
  }),
  management: (lang) => ({
    title: lang === "de"
      ? "Hausverwaltung für Kurzzeitvermietung & Aparthotels — LUXOMES Property Management"
      : "Property management for short-stay rentals & aparthotels — LUXOMES",
    description: lang === "de"
      ? "Professionelle Verwaltung Deiner Kurzzeitwohnung, Pension oder Deines Aparthotels. 15–25 % vom Netto-Umsatz, +31 % Mehrumsatz im Schnitt, 75–85 % Auslastung, 0 € Onboarding. Drei klare Pakete, transparent — für Gastgeber in der DACH-Region."
      : "Professional management of your short-stay rental, guesthouse or aparthotel. 15–25% of net revenue, +31% revenue uplift on average, 75–85% occupancy, €0 onboarding. Three transparent tiers — for hosts across the DACH region.",
    keywords: "hausverwaltung kurzzeitvermietung, airbnb property management dach, aparthotel verwaltung bayern, pension management, gästemanagement, short stay management, vermietungsverwaltung, channel manager dienstleister, full service vermietung",
    path: "/management",
  }),
  realestate: (lang) => ({
    title: lang === "de"
      ? "Master-Lease für Apartmenthäuser & Pensionen — LUXOMES vermietet auf 10 + 10 Jahre"
      : "Master lease for apartment buildings & guesthouses — LUXOMES leases for 10 + 10 years",
    description: lang === "de"
      ? "LUXOMES ist Dein verlässlicher Mieter: garantierte Festmiete, 10 Jahre Festlaufzeit plus 10-Jahres-Option, 0% Leerstandsrisiko. Wir mieten ganze Apartmenthäuser, Pensionen und Neubauprojekte in der DACH-Region — Du bekommst monatlich überwiesen."
      : "LUXOMES is your reliable tenant: guaranteed fixed rent, 10-year term plus 10-year extension, 0% vacancy risk. We lease whole apartment buildings, guesthouses and new-build projects across the DACH region — you get paid every month.",
    keywords: "master lease anbieter, generalmietvertrag dach, gewerblicher mieter apartmenthaus, langfristmieter pension, sale and lease back hotel, aparthotel betreiber, hospitality master tenant, garantierte miete vermieter, neubau master lease investor, immobilieninvestor langfristmieter",
    path: "/realestate",
  }),
  about: (lang) => ({
    title: lang === "de"
      ? "Über LUXOMES — Hospitality-Unternehmen aus Bayern seit 2020"
      : "About LUXOMES — Bavarian hospitality company since 2020",
    description: lang === "de"
      ? "Seit 2020 betreibt LUXOMES designorientierte Serviced Apartments und übernimmt die Verwaltung von Pensionen, Aparthotels und ganzen Apartmenthäusern in der DACH-Region. Über 40 Apartments, 4 Städte, festes Operations-Team."
      : "Since 2020 LUXOMES has been operating design-driven serviced apartments and managing guesthouses, aparthotels and entire apartment buildings across the DACH region. Over 40 apartments, 4 cities, dedicated operations team.",
    keywords: "luxomes über uns, hospitality unternehmen dach, serviced apartments betreiber bayern, aparthotel team, luxomes gmbh, hospitality dach region",
    path: "/about",
  }),
  contact: (lang) => ({
    title: lang === "de" ? "Kontakt — LUXOMES" : "Contact — LUXOMES",
    description: lang === "de"
      ? "Schreib uns oder ruf uns an. LUXOMES GmbH, An der Burg 5, 85716 Unterschleißheim. Tel: +49 89 693378930, info@luxomes.com."
      : "Write or call us. LUXOMES GmbH, An der Burg 5, 85716 Unterschleißheim, Germany. Phone: +49 89 693378930, info@luxomes.com.",
    keywords: "luxomes kontakt, serviced apartment anfrage",
    path: "/contact",
  }),
  blog: (lang) => ({
    title: lang === "de" ? "LUXOMES Blog — Case Studies aus der Praxis" : "LUXOMES Blog — Case studies from the field",
    description: lang === "de"
      ? "Konkrete Case Studies aus unserer Arbeit mit Eigentümern, Gastgebern und Investoren — was wir umgesetzt haben, welche Hebel funktioniert haben."
      : "Concrete case studies from our work with owners, hosts and investors — what we built and which levers worked.",
    keywords: "luxomes blog, case study kurzzeitvermietung, aparthotel umnutzung, vermietung erfahrungen",
    path: "/blog",
  }),
  "legal-impressum": (lang) => ({
    title: "Impressum — LUXOMES GmbH",
    description: "Pflichtangaben gemäß § 5 TMG für LUXOMES GmbH, An der Burg 5, 85716 Unterschleißheim.",
    keywords: "luxomes impressum, anbieterkennzeichnung",
    path: "/impressum",
    noindex: false,
  }),
  "legal-privacy": (lang) => ({
    title: lang === "de" ? "Datenschutzerklärung — LUXOMES" : "Privacy Policy — LUXOMES",
    description: lang === "de"
      ? "Datenschutzerklärung gemäß DSGVO, BDSG und TDDDG für LUXOMES GmbH."
      : "Privacy policy per GDPR, BDSG and TDDDG for LUXOMES GmbH.",
    keywords: "luxomes datenschutz, dsgvo privacy",
    path: "/datenschutz",
  }),
  "legal-agb": (lang) => ({
    title: "AGB — LUXOMES GmbH",
    description: lang === "de"
      ? "Allgemeine Geschäftsbedingungen für die Beherbergung in LUXOMES Serviced Apartments."
      : "Terms and conditions for accommodation in LUXOMES serviced apartments.",
    keywords: "luxomes agb, beherbergungsbedingungen, buchungsbedingungen",
    path: "/agb",
  }),
};

// Resolve SEO for any page including dynamic routes (location-*, blog-*).
function resolveSEO(page, lang) {
  if (PAGE_SEO[page]) return PAGE_SEO[page](lang);

  if (page.startsWith("location-")) {
    const rest = page.replace("location-", "");
    const [key, aptId] = rest.includes(":") ? rest.split(":", 2) : [rest, null];
    const loc = (window.LOCATIONS || []).find(l => l.key === key);
    const city = loc?.city || key;

    // Per-apartment deep page: tighter title with category name, focused
    // description, narrower keyword target. Bots see a distinct page per
    // apartment, which is what drives "studio apartment nürnberg"-style
    // ranking instead of a single broad city page.
    if (aptId && loc) {
      const cat = loc.categories.find(c => c.id === aptId);
      if (cat) {
        const catTitle = cat.title[lang] || cat.title.de;
        return {
          title: lang === "de"
            ? `${catTitle} in ${city} — LUXOMES Serviced Apartment`
            : `${catTitle} in ${city} — LUXOMES serviced apartment`,
          description: lang === "de"
            ? `${catTitle} in ${city}: ${cat.rooms} Zimmer, bis ${cat.guests} Gäste, ${cat.size} m². ${(cat.body?.de || "").slice(0, 130)}`
            : `${catTitle} in ${city}: ${cat.rooms} room(s), up to ${cat.guests} guests, ${cat.size} sqm. ${(cat.body?.en || "").slice(0, 130)}`,
          keywords: `${catTitle.toLowerCase()} ${city.toLowerCase()}, serviced apartment ${city.toLowerCase()}, ${cat.rooms === 1 ? "studio" : cat.rooms + " zimmer"} ${city.toLowerCase()}, business apartment ${city.toLowerCase()}, monatsapartment ${city.toLowerCase()}`,
          path: `/standorte/${key}/${aptId}`,
          location: loc,
          apartment: cat,
        };
      }
    }

    return {
      title: lang === "de"
        ? `Serviced Apartments in ${city} — LUXOMES`
        : `Serviced apartments in ${city} — LUXOMES`,
      description: lang === "de"
        ? `Designorientierte Serviced Apartments in ${city} — voll ausgestattet, digital, zentral. ${loc?.about?.de?.slice(0, 100) || ""}`
        : `Design-driven serviced apartments in ${city} — fully equipped, digital, central. ${loc?.about?.en?.slice(0, 100) || ""}`,
      keywords: `apartment ${city.toLowerCase()}, serviced apartment ${city.toLowerCase()}, monatsapartment ${city.toLowerCase()}, business apartment ${city.toLowerCase()}, kurzzeit ${city.toLowerCase()}`,
      path: `/standorte/${key}`,
      location: loc,
    };
  }

  if (page.startsWith("blog-")) {
    const slug = page.replace("blog-", "");
    const post = (window.BLOG_POSTS || []).find(p => p.slug === slug);
    if (post) {
      return {
        title: post.title[lang] + " — LUXOMES Blog",
        description: post.excerpt[lang],
        keywords: `luxomes case study, ${post.category[lang].toLowerCase()}, ${slug.replace(/-/g, " ")}`,
        path: `/blog/${slug}`,
        post,
      };
    }
  }

  // Fallback
  return PAGE_SEO.home(lang);
}

// Inject/update tag in <head>. Reuses existing tag if found.
function upsertMeta(key, attr, attrValue, content) {
  let tag = document.querySelector(`meta[${attr}="${attrValue}"]`);
  if (!tag) {
    tag = document.createElement("meta");
    tag.setAttribute(attr, attrValue);
    document.head.appendChild(tag);
  }
  tag.setAttribute("content", content);
}

function upsertLink(rel, href, hreflang) {
  const selector = hreflang
    ? `link[rel="${rel}"][hreflang="${hreflang}"]`
    : `link[rel="${rel}"]:not([hreflang])`;
  let tag = document.querySelector(selector);
  if (!tag) {
    tag = document.createElement("link");
    tag.setAttribute("rel", rel);
    if (hreflang) tag.setAttribute("hreflang", hreflang);
    document.head.appendChild(tag);
  }
  tag.setAttribute("href", href);
}

function replaceJSONLD(id, data) {
  let tag = document.getElementById(id);
  if (data == null) {
    if (tag) tag.remove();
    return;
  }
  if (!tag) {
    tag = document.createElement("script");
    tag.id = id;
    tag.type = "application/ld+json";
    document.head.appendChild(tag);
  }
  tag.textContent = JSON.stringify(data, null, 2);
}

// Build JSON-LD per page
function buildJSONLD(page, lang, seo) {
  const orgSchema = {
    "@context": "https://schema.org",
    "@type": "LodgingBusiness",
    "@id": SITE_URL + "/#org",
    name: SITE_NAME,
    legalName: "LUXOMES GmbH",
    url: SITE_URL,
    logo: SITE_URL + "/assets/luxomes-logo.png",
    image: SITE_OG_IMAGE,
    telephone: "+49 89 693378930",
    email: "info@luxomes.com",
    address: {
      "@type": "PostalAddress",
      streetAddress: "An der Burg 5",
      postalCode: "85716",
      addressLocality: "Unterschleißheim",
      addressRegion: "Bayern",
      addressCountry: "DE",
    },
  };

  // Build per-page extras
  const extras = [];

  // FAQPage on home — Google rich snippet
  if (page === "home") {
    const faqs = (window.FAQS || []).map(f => ({
      "@type": "Question",
      name: f.q[lang],
      acceptedAnswer: { "@type": "Answer", text: f.a[lang] },
    }));
    if (faqs.length > 0) {
      extras.push({
        "@context": "https://schema.org",
        "@type": "FAQPage",
        mainEntity: faqs,
      });
    }
  }

  // Service + FAQPage for /management — heavy B2B page, high ranking value.
  if (page === "management") {
    extras.push({
      "@context": "https://schema.org",
      "@type": "Service",
      "@id": SITE_URL + "/management#service",
      serviceType: lang === "de"
        ? "Verwaltung von Ferienwohnungen, Aparthotels und Pensionen"
        : "Property management for serviced apartments, aparthotels and guesthouses",
      name: lang === "de" ? "LUXOMES Property Management" : "LUXOMES Property Management",
      provider: { "@id": SITE_URL + "/#org" },
      areaServed: [
        { "@type": "Country", name: "Deutschland" },
        { "@type": "Country", name: "Österreich" },
        { "@type": "Country", name: "Schweiz" },
      ],
      audience: { "@type": "BusinessAudience", audienceType: lang === "de" ? "Eigentümer und Gastgeber" : "Owners and hosts" },
      offers: [
        { "@type": "Offer", name: "Basic", priceCurrency: "EUR", description: lang === "de" ? "15% vom Netto-Umsatz" : "15% of net revenue" },
        { "@type": "Offer", name: "Plus", priceCurrency: "EUR", description: lang === "de" ? "20% vom Netto-Umsatz" : "20% of net revenue" },
        { "@type": "Offer", name: "Premium", priceCurrency: "EUR", description: lang === "de" ? "25% vom Netto-Umsatz" : "25% of net revenue" },
      ],
    });
    // Re-use site-wide FAQs for the management page (same B2B intent).
    const faqs = (window.FAQS || []).map(f => ({
      "@type": "Question",
      name: f.q[lang],
      acceptedAnswer: { "@type": "Answer", text: f.a[lang] },
    }));
    if (faqs.length > 0) {
      extras.push({
        "@context": "https://schema.org",
        "@type": "FAQPage",
        mainEntity: faqs,
      });
    }
  }

  // Service + RealEstateAgent + FAQPage for /realestate — master-tenant business.
  if (page === "realestate") {
    extras.push({
      "@context": "https://schema.org",
      "@type": "Service",
      "@id": SITE_URL + "/realestate#service",
      serviceType: lang === "de"
        ? "Master-Lease / Generalmietvertrag für Apartmenthäuser, Pensionen und Aparthotels"
        : "Master lease for apartment buildings, guesthouses and aparthotels",
      name: lang === "de" ? "LUXOMES Master Lease" : "LUXOMES Master Lease",
      description: lang === "de"
        ? "LUXOMES schließt langfristige gewerbliche Mietverträge (10 Jahre Festlaufzeit plus 10-Jahres-Option) und garantiert Eigentümern eine vertraglich zugesicherte Monatsmiete."
        : "LUXOMES signs long-term commercial leases (10-year fixed term plus 10-year extension) and guarantees owners a contractually agreed monthly rent.",
      provider: { "@id": SITE_URL + "/#org" },
      areaServed: [
        { "@type": "Country", name: "Deutschland" },
        { "@type": "Country", name: "Österreich" },
        { "@type": "Country", name: "Schweiz" },
      ],
      audience: { "@type": "BusinessAudience", audienceType: lang === "de" ? "Eigentümer, Investoren, Bauträger" : "Owners, investors, developers" },
    });
    const reFaqs = (window.RE_FAQ || []).map(f => ({
      "@type": "Question",
      name: f.q[lang],
      acceptedAnswer: { "@type": "Answer", text: f.a[lang] },
    }));
    if (reFaqs.length > 0) {
      extras.push({
        "@context": "https://schema.org",
        "@type": "FAQPage",
        mainEntity: reFaqs,
      });
    }
  }

  // BlogPosting on individual blog posts
  if (page.startsWith("blog-") && seo.post) {
    const p = seo.post;
    extras.push({
      "@context": "https://schema.org",
      "@type": "BlogPosting",
      headline: p.title[lang],
      description: p.excerpt[lang],
      image: p.image.startsWith("http") ? p.image : SITE_URL + p.image,
      datePublished: p.date,
      dateModified: p.date,
      author: { "@type": "Organization", name: "LUXOMES" },
      publisher: {
        "@type": "Organization",
        name: SITE_NAME,
        logo: { "@type": "ImageObject", url: SITE_URL + "/assets/luxomes-logo.png" },
      },
      mainEntityOfPage: { "@type": "WebPage", "@id": SITE_URL + seo.path },
      articleSection: p.category[lang],
    });
    extras.push(buildBreadcrumb([
      { name: lang === "de" ? "Start" : "Home", url: SITE_URL + "/" },
      { name: "Blog", url: SITE_URL + "/blog" },
      { name: p.title[lang], url: SITE_URL + seo.path },
    ]));
  }

  // Blog index page
  if (page === "blog") {
    extras.push({
      "@context": "https://schema.org",
      "@type": "Blog",
      name: "LUXOMES Blog",
      url: SITE_URL + "/blog",
      blogPost: (window.BLOG_POSTS || []).map(p => ({
        "@type": "BlogPosting",
        headline: p.title[lang],
        url: SITE_URL + "/blog/" + p.slug,
        datePublished: p.date,
        image: p.image,
      })),
    });
  }

  // Place schema on location pages
  if (page.startsWith("location-") && seo.location) {
    const loc = seo.location;
    extras.push({
      "@context": "https://schema.org",
      "@type": "LodgingBusiness",
      name: `LUXOMES ${loc.city}`,
      url: SITE_URL + seo.path,
      image: loc.heroImages?.[0] || SITE_OG_IMAGE,
      description: loc.about?.[lang],
      address: {
        "@type": "PostalAddress",
        addressLocality: loc.city,
        addressRegion: "Bayern",
        addressCountry: "DE",
      },
      telephone: "+49 89 693378930",
    });

    // Apartment-specific Accommodation schema for deep pages — eligible
    // for rich snippets in Google Hotels & lodging search results.
    if (seo.apartment) {
      const cat = seo.apartment;
      extras.push({
        "@context": "https://schema.org",
        "@type": "Apartment",
        name: `${cat.title[lang]} — ${loc.city}`,
        url: SITE_URL + seo.path,
        image: cat.images?.[0],
        description: cat.body?.[lang],
        numberOfRooms: cat.rooms,
        occupancy: { "@type": "QuantitativeValue", maxValue: cat.guests },
        floorSize: { "@type": "QuantitativeValue", value: cat.size, unitCode: "MTK" }, // m²
        amenityFeature: [
          { "@type": "LocationFeatureSpecification", name: "WiFi",        value: true },
          { "@type": "LocationFeatureSpecification", name: "Kitchen",     value: true },
          { "@type": "LocationFeatureSpecification", name: "Self check-in", value: true },
          { "@type": "LocationFeatureSpecification", name: "Smart TV",    value: true },
          { "@type": "LocationFeatureSpecification", name: "Washing machine", value: true },
          { "@type": "LocationFeatureSpecification", name: "Workspace",   value: true },
        ],
        address: {
          "@type": "PostalAddress",
          addressLocality: loc.city,
          addressRegion: "Bayern",
          addressCountry: "DE",
        },
      });
      extras.push(buildBreadcrumb([
        { name: lang === "de" ? "Start" : "Home", url: SITE_URL + "/" },
        { name: lang === "de" ? "Standorte" : "Locations", url: SITE_URL + "/" },
        { name: loc.city, url: SITE_URL + "/standorte/" + loc.key },
        { name: cat.title[lang], url: SITE_URL + seo.path },
      ]));
    } else {
      extras.push(buildBreadcrumb([
        { name: lang === "de" ? "Start" : "Home", url: SITE_URL + "/" },
        { name: lang === "de" ? "Standorte" : "Locations", url: SITE_URL + "/" },
        { name: loc.city, url: SITE_URL + seo.path },
      ]));
    }
  }

  return extras;
}

function buildBreadcrumb(items) {
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: items.map((it, i) => ({
      "@type": "ListItem",
      position: i + 1,
      name: it.name,
      item: it.url,
    })),
  };
}

// Main entry — call on every page/lang change.
function applyPageSEO(page, lang) {
  const seo = resolveSEO(page, lang);

  // <title>
  document.title = seo.title;

  // Meta description, keywords
  upsertMeta("description", "name", "description", seo.description);
  if (seo.keywords) upsertMeta("keywords", "name", "keywords", seo.keywords);

  // Canonical URL
  upsertLink("canonical", SITE_URL + seo.path);

  // Robots noindex if requested
  upsertMeta("robots", "name", "robots", seo.noindex ? "noindex, follow" : "index, follow");

  // Open Graph
  upsertMeta("ogTitle", "property", "og:title", seo.title);
  upsertMeta("ogDesc", "property", "og:description", seo.description);
  upsertMeta("ogUrl", "property", "og:url", SITE_URL + seo.path);
  upsertMeta("ogType", "property", "og:type", page.startsWith("blog-") ? "article" : "website");
  upsertMeta("ogLocale", "property", "og:locale", lang === "de" ? "de_DE" : "en_US");

  // Twitter
  upsertMeta("twTitle", "name", "twitter:title", seo.title);
  upsertMeta("twDesc", "name", "twitter:description", seo.description);

  // hreflang — emit DE + EN + x-default alternates pointing at the same canonical
  // (SPA toggles language client-side, both languages live at the same URL).
  upsertLink("alternate", SITE_URL + seo.path, "de");
  upsertLink("alternate", SITE_URL + seo.path, "en");
  upsertLink("alternate", SITE_URL + seo.path, "x-default");
  // <html lang>
  document.documentElement.setAttribute("lang", lang);

  // Build per-page JSON-LD blocks
  const extras = buildJSONLD(page, lang, seo);
  // Clear all previous dynamic schemas (we re-add what's needed below)
  document.querySelectorAll('script[id^="ld-page-"]').forEach(s => s.remove());
  extras.forEach((data, i) => replaceJSONLD("ld-page-" + i, data));
}

window.applyPageSEO = applyPageSEO;
