// seo.jsx — dynamic per-route meta + JSON-LD injection

const SITE_URL = 'https://lessotubos.com.br';

function _pathFor(lang, page, extra = {}) {
  // Use buildUrl from app.jsx if loaded, otherwise fall back to simple EN paths.
  if (window.buildUrl) return window.buildUrl(lang, page, extra);
  return '/';
}

function _upsertMeta(selector, attrs) {
  let el = document.head.querySelector(selector);
  if (!el) {
    el = document.createElement('meta');
    Object.keys(attrs).forEach(k => { if (k !== 'content') el.setAttribute(k, attrs[k]); });
    document.head.appendChild(el);
  }
  if (attrs.content !== undefined) el.setAttribute('content', attrs.content);
}

function _upsertLink(rel, href, extra = {}) {
  const sel = extra.hreflang
    ? `link[rel="${rel}"][hreflang="${extra.hreflang}"]`
    : `link[rel="${rel}"]`;
  let el = document.head.querySelector(sel);
  if (!el) {
    el = document.createElement('link');
    el.setAttribute('rel', rel);
    if (extra.hreflang) el.setAttribute('hreflang', extra.hreflang);
    document.head.appendChild(el);
  }
  el.setAttribute('href', href);
}

function _clearJsonLd() {
  document.head.querySelectorAll('script[data-seo-ld]').forEach(n => n.remove());
}

function _addJsonLd(obj) {
  const s = document.createElement('script');
  s.type = 'application/ld+json';
  s.setAttribute('data-seo-ld', '1');
  s.textContent = JSON.stringify(obj);
  document.head.appendChild(s);
}

function _compactText(value, max = 160) {
  return String(value || '').replace(/\*\*/g, '').replace(/\s+/g, ' ').trim().slice(0, max);
}

function _absoluteAssetUrl(value, fallback = '/assets/hero.jpg') {
  const src = value || fallback;
  if (/^https?:\/\//i.test(src)) return src;
  return SITE_URL + '/' + String(src).replace(/^\/+/, '');
}

function _pickNewsField(post, base, lang) {
  if (!post) return '';
  const suffixed = post[`${base}_${lang}`];
  if (suffixed) return suffixed;
  if (lang === 'pt') return post[base] || '';
  return post[`${base}_${lang}`] || post[base] || '';
}

function _findNewsPost(slug) {
  const news = window.NEWS || [];
  return Array.isArray(news) ? news.find(n => n && n.slug === slug) : null;
}

// 3-language lookup table for SEO copy. Each key returns an object keyed by
// lang code (pt/en/es). Used in place of binary conditionals after Spanish
// support was added 2026-05-18.
const SEO_COPY = {
  home: {
    title: {
      pt: 'LESSO Brasil — Tubos e Conexões para Água, Irrigação, Óleo & Gás e Mineração',
      en: 'LESSO Brazil — Pipes & Fittings for Water, Irrigation, Oil & Gas and Mining',
      es: 'LESSO Brasil — Tuberías y Accesorios para Agua, Riego, Petróleo y Gas y Minería',
    },
    desc: {
      pt: 'Tubos PE, RTP, compostos para mineração e conexões PP para distribuidores e projetos no Brasil. Peça seu orçamento.',
      en: 'PE, RTP, mining composite pipes and PP fittings for distributors and projects in Brazil. Request a quote.',
      es: 'Tuberías PE, RTP, compuestas para minería y accesorios PP para distribuidores y proyectos en Brasil. Solicite su cotización.',
    },
  },
  products: {
    title: {
      pt: 'Tubos e Conexões — LESSO Brasil',
      en: 'Pipes & Fittings — LESSO Brazil',
      es: 'Tuberías y Accesorios — LESSO Brasil',
    },
    desc: {
      pt: 'Linha completa de tubos PE, RTP, compostos para mineração e conexões PP para o mercado brasileiro.',
      en: 'Full range of PE, RTP, mining composite pipes and PP fittings for the Brazilian market.',
      es: 'Gama completa de tuberías PE, RTP, compuestas para minería y accesorios PP para el mercado brasileño.',
    },
  },
  about: {
    title: {
      pt: 'Sobre a LESSO — LESSO Brasil',
      en: 'About LESSO — LESSO Brazil',
      es: 'Sobre LESSO — LESSO Brasil',
    },
    desc: {
      pt: 'LESSO é um grupo global fundado em 1986, com 30+ bases de produção e presença em mais de 150 países.',
      en: 'LESSO is a global group founded in 1986, with 30+ manufacturing bases and presence in 150+ countries.',
      es: 'LESSO es un grupo global fundado en 1986, con más de 30 bases de producción y presencia en más de 150 países.',
    },
  },
  quality: {
    title: {
      pt: 'Qualidade & Downloads — LESSO Brasil',
      en: 'Quality & Downloads — LESSO Brazil',
      es: 'Calidad y Descargas — LESSO Brasil',
    },
    desc: {
      pt: 'Normas, certificações, catálogos PDF em português e FAQ técnico da LESSO Brasil.',
      en: 'Standards, certifications, PDF catalogs and technical FAQ from LESSO Brazil.',
      es: 'Normas, certificaciones, catálogos PDF y preguntas frecuentes técnicas de LESSO Brasil.',
    },
  },
  contact: {
    title: {
      pt: 'Contato — LESSO Brasil',
      en: 'Contact — LESSO Brazil',
      es: 'Contacto — LESSO Brasil',
    },
    desc: {
      pt: 'Fale com a LESSO Brasil. Orçamento, suporte técnico e parcerias para tubos e conexões.',
      en: 'Contact LESSO Brazil for quotes, technical support and partnerships on pipes and fittings.',
      es: 'Contacte con LESSO Brasil. Cotizaciones, soporte técnico y alianzas para tuberías y accesorios.',
    },
  },
  privacy: {
    title: {
      pt: 'Privacidade — LESSO Brasil',
      en: 'Privacy — LESSO Brazil',
      es: 'Privacidad — LESSO Brasil',
    },
    desc: {
      pt: 'Política de privacidade da LESSO Brasil — LGPD, tratamento de dados, cookies.',
      en: 'LESSO Brazil privacy policy — LGPD, data handling, cookies.',
      es: 'Política de privacidad de LESSO Brasil — LGPD, tratamiento de datos, cookies.',
    },
  },
  news: {
    title: {
      pt: 'Notícias — LESSO Brasil',
      en: 'News — LESSO Brazil',
      es: 'Noticias — LESSO Brasil',
    },
    desc: {
      pt: 'Notícias, projetos e atualizações da LESSO Brasil — lançamentos de produtos, obras, certificações e eventos do setor.',
      en: 'LESSO Brazil news, projects and updates — product launches, construction milestones, certifications and industry events.',
      es: 'Noticias, proyectos y actualizaciones de LESSO Brasil — lanzamientos de productos, obras, certificaciones y eventos del sector.',
    },
  },
  newsPost: {
    title: {
      pt: 'Notícia — LESSO Brasil',
      en: 'News article — LESSO Brazil',
      es: 'Noticia — LESSO Brasil',
    },
    desc: {
      pt: 'Leia esta notícia da LESSO Brasil — soluções em tubulações, válvulas, cabos e materiais para construção.',
      en: 'Read this LESSO Brazil news article — piping, valve, cable and building-material solutions.',
      es: 'Lea esta noticia de LESSO Brasil — soluciones en tuberías, válvulas, cables y materiales para construcción.',
    },
  },
  '404': {
    title: {
      pt: 'Página não encontrada — LESSO Brasil',
      en: 'Page not found — LESSO Brazil',
      es: 'Página no encontrada — LESSO Brasil',
    },
    desc: {
      pt: 'O link que você acessou não existe.',
      en: 'The page you requested does not exist.',
      es: 'La página que solicitó no existe.',
    },
  },
};

// Crumb names per lang.
const CRUMB = {
  home:     { pt: 'Início',              en: 'Home',                 es: 'Inicio' },
  products: { pt: 'Tubos e Conexões',    en: 'Pipes & Fittings',     es: 'Tuberías y Accesorios' },
  about:    { pt: 'Sobre',               en: 'About',                es: 'Sobre' },
  quality:  { pt: 'Qualidade & Downloads', en: 'Quality & Downloads', es: 'Calidad y Descargas' },
  contact:  { pt: 'Contato',             en: 'Contact',              es: 'Contacto' },
  privacy:  { pt: 'Privacidade',         en: 'Privacy',              es: 'Privacidad' },
  news:     { pt: 'Notícias',            en: 'News',                 es: 'Noticias' },
};

const HTML_LANG = { pt: 'pt-BR', en: 'en', es: 'es-419' };
const OG_LOCALE = { pt: 'pt_BR', en: 'en_US', es: 'es_ES' };
const HREFLANG  = { pt: 'pt-BR', en: 'en',    es: 'es-419' };
const COUNTRY_NAME = { pt: 'Brasil', en: 'Brazil', es: 'Brasil' };

function applySEO({ route, lang, t }) {
  const page = route.page || 'home';
  let title = '';
  let desc = '';
  let ogImage = SITE_URL + '/assets/hero.jpg';
  const ogLocale = OG_LOCALE[lang] || OG_LOCALE.en;
  const path = _pathFor(lang, page, route);

  if (SEO_COPY[page]) {
    title = SEO_COPY[page].title[lang] || SEO_COPY[page].title.en;
    desc  = SEO_COPY[page].desc[lang]  || SEO_COPY[page].desc.en;
  }
  if (page === 'product') {
    const p = (t.productList || []).find(x => x.slug === route.slug) || {};
    title = `${p.name || ''} — LESSO ${COUNTRY_NAME[lang] || 'Brazil'}`;
    desc = _compactText(p.desc, 160);
    if (p.image) ogImage = _absoluteAssetUrl(p.image);
  }
  if (page === 'newsPost') {
    const post = _findNewsPost(route.slug);
    if (post) {
      const postTitle = _pickNewsField(post, 'title', lang);
      const postSummary = _pickNewsField(post, 'summary', lang);
      const postBody = _pickNewsField(post, 'body', lang);
      if (postTitle) title = `${postTitle} — LESSO ${COUNTRY_NAME[lang] || 'Brazil'}`;
      desc = _compactText(postSummary || postBody || desc, 160);
      if (post.image) ogImage = _absoluteAssetUrl(post.image);
    }
  }

  const canonical = SITE_URL + path;
  document.title = title;
  document.documentElement.lang = HTML_LANG[lang] || 'en';

  // Mark 404 as noindex
  if (page === '404') {
    _upsertMeta('meta[name="robots"]', { name: 'robots', content: 'noindex, follow' });
  } else {
    _upsertMeta('meta[name="robots"]', { name: 'robots', content: 'index, follow, max-image-preview:large' });
  }

  _upsertMeta('meta[name="description"]', { name: 'description', content: desc });
  _upsertLink('canonical', canonical);
  // hreflang alternates — one link per supported language. The current lang
  // points at canonical, the others at their localized URL. x-default = pt.
  for (const lng of ['pt', 'en', 'es']) {
    const href = SITE_URL + _pathFor(lng, page, route);
    _upsertLink('alternate', href, { hreflang: HREFLANG[lng] });
  }
  _upsertLink('alternate', SITE_URL + _pathFor('pt', page, route), { hreflang: 'x-default' });

  _upsertMeta('meta[property="og:title"]', { property: 'og:title', content: title });
  _upsertMeta('meta[property="og:description"]', { property: 'og:description', content: desc });
  _upsertMeta('meta[property="og:url"]', { property: 'og:url', content: canonical });
  _upsertMeta('meta[property="og:image"]', { property: 'og:image', content: ogImage });
  _upsertMeta('meta[property="og:locale"]', { property: 'og:locale', content: ogLocale });
  _upsertMeta('meta[name="twitter:title"]', { name: 'twitter:title', content: title });
  _upsertMeta('meta[name="twitter:description"]', { name: 'twitter:description', content: desc });
  _upsertMeta('meta[name="twitter:image"]', { name: 'twitter:image', content: ogImage });

  // Dynamic JSON-LD per page
  _clearJsonLd();

  // Breadcrumb (skip on home)
  if (page !== 'home' && page !== '404') {
    const crumbs = [{ name: CRUMB.home[lang] || CRUMB.home.en, item: SITE_URL + _pathFor(lang, 'home') }];
    if (page === 'products' || page === 'product') {
      crumbs.push({ name: CRUMB.products[lang] || CRUMB.products.en, item: SITE_URL + _pathFor(lang, 'products') });
    }
    if (page === 'product') {
      const p = (t.productList || []).find(x => x.slug === route.slug);
      if (p) crumbs.push({ name: p.short, item: canonical });
    }
    if (page === 'news' || page === 'newsPost') {
      crumbs.push({ name: CRUMB.news[lang] || CRUMB.news.en, item: SITE_URL + _pathFor(lang, 'news') });
    }
    if (page === 'newsPost') {
      const post = _findNewsPost(route.slug);
      const postTitle = _pickNewsField(post, 'title', lang);
      if (postTitle) crumbs.push({ name: postTitle, item: canonical });
    }
    if (page === 'about')   crumbs.push({ name: CRUMB.about[lang]   || CRUMB.about.en,   item: canonical });
    if (page === 'quality') crumbs.push({ name: CRUMB.quality[lang] || CRUMB.quality.en, item: canonical });
    if (page === 'contact') crumbs.push({ name: CRUMB.contact[lang] || CRUMB.contact.en, item: canonical });
    if (page === 'privacy') crumbs.push({ name: CRUMB.privacy[lang] || CRUMB.privacy.en, item: canonical });
    _addJsonLd({
      '@context': 'https://schema.org',
      '@type': 'BreadcrumbList',
      itemListElement: crumbs.map((c, i) => ({
        '@type': 'ListItem', position: i + 1, name: c.name, item: c.item,
      })),
    });
  }

  // Product JSON-LD
  if (page === 'product') {
    const p = (t.productList || []).find(x => x.slug === route.slug);
    if (p) {
      _addJsonLd({
        '@context': 'https://schema.org',
        '@type': 'Product',
        name: p.name,
        description: p.desc,
        brand: { '@type': 'Brand', name: 'LESSO' },
        manufacturer: { '@id': SITE_URL + '/#organization' },
        category: p.tag,
        url: canonical,
        image: _absoluteAssetUrl(p.image),
      });
      if (Array.isArray(p.faqs) && p.faqs.length) {
        _addJsonLd({
          '@context': 'https://schema.org',
          '@type': 'FAQPage',
          mainEntity: p.faqs.map(f => ({
            '@type': 'Question',
            name: f.q,
            acceptedAnswer: { '@type': 'Answer', text: f.a },
          })),
        });
      }
    }
  }

  // News detail JSON-LD — Decap-authored title/summary/body/image should be
  // reflected in search/social metadata, not only in the visible React page.
  if (page === 'newsPost') {
    const post = _findNewsPost(route.slug);
    if (post) {
      const headline = _pickNewsField(post, 'title', lang);
      const description = _compactText(_pickNewsField(post, 'summary', lang) || _pickNewsField(post, 'body', lang), 200);
      _addJsonLd({
        '@context': 'https://schema.org',
        '@type': 'NewsArticle',
        headline,
        description,
        datePublished: post.date,
        dateModified: post.date,
        inLanguage: HTML_LANG[lang] || 'en',
        image: _absoluteAssetUrl(post.image),
        url: canonical,
        publisher: { '@id': SITE_URL + '/#organization' },
      });
    }
  }

  // Quality page FAQ schema
  if (page === 'quality' && t.quality && Array.isArray(t.quality.faqs) && t.quality.faqs.length) {
    _addJsonLd({
      '@context': 'https://schema.org',
      '@type': 'FAQPage',
      mainEntity: t.quality.faqs.map(f => ({
        '@type': 'Question',
        name: f.q,
        acceptedAnswer: { '@type': 'Answer', text: f.a },
      })),
    });
  }

  // Contact page — ContactPoint / LocalBusiness-lite
  if (page === 'contact') {
    _addJsonLd({
      '@context': 'https://schema.org',
      '@type': 'ContactPage',
      url: canonical,
      mainEntity: {
        '@id': SITE_URL + '/#organization',
      },
    });
  }
}

window.applySEO = applySEO;
