// -- capitaldepas.com · SEO dinamico -----------------------------------------
//
// Hooks y helpers para actualizar title/description/canonical/OG y JSON-LD
// segun la pagina actual o el proyecto seleccionado.
// ----------------------------------------------------------------------------

const BASE_URL = 'https://www.capitaldepas.com';
const DEFAULT_OG_IMAGE = BASE_URL + '/images/og-cover.jpg';
const DEFAULT_TITLE = 'capitaldepas.com — Departamentos en preventa y venta en Mexico | CDMX, Cancun, Los Cabos';
const DEFAULT_DESC = 'Departamentos en preventa y venta en CDMX, Cancun, Los Cabos y mas. Desarrolladores verificados, hasta 20% por debajo del valor final, asesoria gratuita.';

// Per-page SEO config — canonical URLs use real paths, not hash fragments
const PAGE_SEO = {
  home:       { title: DEFAULT_TITLE, desc: DEFAULT_DESC, canonical: BASE_URL + '/' },
  listings:   { title: 'Proyectos de departamentos en preventa y venta en Mexico | capitaldepas.com', desc: 'Explora departamentos en preventa y venta en CDMX, Cancun, Los Cabos y mas. Filtra por zona, precio y tipo de credito.', canonical: BASE_URL + '/proyectos' },
  calculator: { title: 'Calculadora de Credito Hipotecario, Infonavit y Fovissste | capitaldepas.com', desc: 'Calcula tu mensualidad hipotecaria gratis. Compatible con credito bancario, Infonavit y Fovissste. Ingresa precio, enganche y plazo.', canonical: BASE_URL + '/calculadora' },
  map:        { title: 'Mapa de Desarrollos Inmobiliarios en Mexico | capitaldepas.com', desc: 'Mapa interactivo con la ubicacion de cada desarrollo en CDMX, Cancun, Los Cabos y mas ciudades de Mexico.', canonical: BASE_URL + '/mapa' },
  blog:       { title: 'Blog Inmobiliario — Guias y tendencias | capitaldepas.com', desc: 'Articulos sobre preventa, financiamiento hipotecario, Infonavit, plusvalia y tendencias del mercado inmobiliario en Mexico.', canonical: BASE_URL + '/blog' },
  contact:    { title: 'Contacto — Asesoria gratuita de departamentos | capitaldepas.com', desc: 'Habla con un asesor certificado sin costo. Te ayudamos a encontrar y comprar el departamento ideal en Mexico.', canonical: BASE_URL + '/contacto' },
};

function setMeta(selector, attr, value) {
  if (!value) return;
  let el = document.head.querySelector(selector);
  if (!el) {
    el = document.createElement('meta');
    const m = selector.match(/\[(.*?)="(.*?)"\]/);
    if (m) el.setAttribute(m[1], m[2]);
    document.head.appendChild(el);
  }
  el.setAttribute(attr, value);
}

function setLink(rel, href, extraAttr) {
  let el = document.head.querySelector('link[rel="' + rel + '"]' + (extraAttr ? '[' + extraAttr.k + '="' + extraAttr.v + '"]' : ''));
  if (!el) {
    el = document.createElement('link');
    el.setAttribute('rel', rel);
    if (extraAttr) el.setAttribute(extraAttr.k, extraAttr.v);
    document.head.appendChild(el);
  }
  el.setAttribute('href', href);
}

function setJsonLd(id, data) {
  let el = document.getElementById(id);
  if (!data) { if (el) el.remove(); return; }
  if (!el) {
    el = document.createElement('script');
    el.type = 'application/ld+json';
    el.id = id;
    document.head.appendChild(el);
  }
  el.textContent = JSON.stringify(data);
}

function applySeo({ title, description, canonical, image, robots }) {
  if (title) document.title = title;
  if (description) {
    setMeta('meta[name="description"]', 'content', description);
    setMeta('meta[property="og:description"]', 'content', description);
    setMeta('meta[name="twitter:description"]', 'content', description);
  }
  if (title) {
    setMeta('meta[property="og:title"]', 'content', title);
    setMeta('meta[name="twitter:title"]', 'content', title);
  }
  if (image) {
    setMeta('meta[property="og:image"]', 'content', image);
    setMeta('meta[name="twitter:image"]', 'content', image);
  }
  if (canonical) {
    setLink('canonical', canonical);
    setMeta('meta[property="og:url"]', 'content', canonical);
  }
  if (robots) setMeta('meta[name="robots"]', 'content', robots);
}

// Hook for logical pages — sets correct canonical per page
const usePageSeo = (pageKey) => {
  React.useEffect(() => {
    const cfg = PAGE_SEO[pageKey];
    if (!cfg) return;
    applySeo({ title: cfg.title, description: cfg.desc, canonical: cfg.canonical, image: DEFAULT_OG_IMAGE });
    setJsonLd('jsonld-project', null);
    setJsonLd('jsonld-breadcrumb', null);
    setJsonLd('jsonld-blog', null);
    try { window.capdepasTrack && window.capdepasTrack('page_view', { page: pageKey }); } catch(e) {}
  }, [pageKey]);
};

// Legacy alias kept for backward compatibility
const useSeo = (opts) => {
  React.useEffect(() => {
    applySeo(opts || {});
  }, [opts && opts.title, opts && opts.description, opts && opts.canonical, opts && opts.image]);
};

// SEO for individual project pages — uses RealEstateListing schema
const useProjectSeo = (prop) => {
  React.useEffect(() => {
    if (!prop) {
      setJsonLd('jsonld-project', null);
      setJsonLd('jsonld-breadcrumb', null);
      return;
    }
    const slug = prop.slug || prop.id;
    const url = BASE_URL + '/proyecto/' + encodeURIComponent(slug);
    const image = (prop.photos && prop.photos[0])
      ? (prop.photos[0].startsWith('http') ? prop.photos[0] : BASE_URL + prop.photos[0])
      : DEFAULT_OG_IMAGE;
    const title = prop.name + ' — ' + (prop.priceStr || '') + ' · ' + (prop.location || '') + ' | capitaldepas.com';
    const description = (prop.desc || ('Departamento en ' + (prop.type || 'preventa') + ' en ' + (prop.location || 'Mexico') + '. ' + (prop.beds || '') + ' rec, ' + (prop.sqm || '') + ' m2.')).slice(0, 300);

    applySeo({ title, description, canonical: url, image });

    // RealEstateListing schema (replaces Product — more semantically correct for RE)
    setJsonLd('jsonld-project', {
      '@context': 'https://schema.org',
      '@type': 'RealEstateListing',
      name: prop.name,
      description: prop.desc || description,
      image: image,
      url: url,
      datePosted: new Date().toISOString().split('T')[0],
      ...(prop.price ? { price: String(prop.price), priceCurrency: 'MXN' } : {}),
      ...(prop.sqm ? { floorSize: { '@type': 'QuantitativeValue', value: prop.sqm, unitCode: 'MTK' } } : {}),
      ...(prop.beds ? { numberOfRooms: prop.beds } : {}),
      address: {
        '@type': 'PostalAddress',
        addressLocality: prop.location || '',
        addressCountry: 'MX',
      },
      ...(prop.lat && prop.lng ? { geo: { '@type': 'GeoCoordinates', latitude: prop.lat, longitude: prop.lng } } : {}),
      ...(prop.developer ? { seller: { '@type': 'Organization', name: prop.developer } } : {}),
    });

    // BreadcrumbList — real paths, not hash fragments
    setJsonLd('jsonld-breadcrumb', {
      '@context': 'https://schema.org',
      '@type': 'BreadcrumbList',
      itemListElement: [
        { '@type': 'ListItem', position: 1, name: 'Inicio', item: BASE_URL + '/' },
        { '@type': 'ListItem', position: 2, name: 'Proyectos', item: BASE_URL + '/proyectos' },
        { '@type': 'ListItem', position: 3, name: prop.name, item: url },
      ],
    });
  }, [prop && (prop.slug || prop.id)]);
};

// SEO for individual blog posts — Article schema
const useBlogPostSeo = (post) => {
  React.useEffect(() => {
    if (!post) return;
    const url = BASE_URL + '/blog/' + post.slug;
    const image = post.image || DEFAULT_OG_IMAGE;
    const title = post.title + ' | capitaldepas.com';
    const description = (post.excerpt || post.title).slice(0, 300);
    applySeo({ title, description, canonical: url, image });
    setJsonLd('jsonld-blog', {
      '@context': 'https://schema.org',
      '@type': 'Article',
      headline: post.title,
      description: description,
      image: image,
      url: url,
      datePublished: post.date || '',
      author: { '@type': 'Organization', name: 'capitaldepas.com', url: BASE_URL },
      publisher: {
        '@type': 'Organization',
        name: 'capitaldepas.com',
        logo: { '@type': 'ImageObject', url: BASE_URL + '/images/logo.png' },
      },
    });
  }, [post && post.slug]);
};

const resetSeo = () => {
  const cfg = PAGE_SEO['home'];
  applySeo({ title: cfg.title, description: cfg.desc, canonical: cfg.canonical, image: DEFAULT_OG_IMAGE });
  setJsonLd('jsonld-project', null);
  setJsonLd('jsonld-breadcrumb', null);
  setJsonLd('jsonld-blog', null);
};

const usePageViewTracking = (pageKey, extra) => {
  React.useEffect(() => {
    try {
      if (window.capdepasTrack) window.capdepasTrack('page_view', Object.assign({ page: pageKey }, extra || {}));
    } catch(e) {}
  }, [pageKey]);
};

Object.assign(window, { useSeo, usePageSeo, useProjectSeo, useBlogPostSeo, applySeo, resetSeo, usePageViewTracking });
