/* SEO compartido para casamia.ec.
   - setSeo() escribe title, description, canonical, Open Graph, Twitter y robots.
   - jsonLd() inyecta datos estructurados (schema.org) con un id estable.
   Las URLs canónicas asumen casamia.ec/propiedad/<id>-<slug> y
   casamia.ec/propiedades, /contacto, /publicar. Si la estructura real del sitio
   es distinta, cambia SEO.site y SEO.paths y todo lo demás se recalcula. */
const SEO = {
  site: 'https://casamia.ec',
  nombre: 'casamia.ec',
  logo: 'https://casamia.ec/assets/logo-casamia.png',
  ogImage: 'https://casamia.ec/assets/logo-casamia.png',
  paths: { inicio: '/', propiedades: '/propiedades', propiedad: '/propiedad/', contacto: '/contacto', publicar: '/publicar', creditos: '/creditos-hipotecarios-ecuador/' },
  telefono: '+593988957054',
  correo: 'hola@casamia.ec',
  redes: ['https://web.facebook.com/casamia.ec.quito/', 'https://www.instagram.com/casamia.ecuador/', 'https://www.tiktok.com/@casamia.ecuador']
};
const slugify = (s = '') => s.toString().normalize('NFD').replace(/[\u0300-\u036f]/g, '')
  .toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 70);
const propertyUrl = (p) => SEO.site + SEO.paths.propiedad + p.id + '-' + slugify(p.titulo);
const absUrl = (u = '') => /^https?:/.test(u) ? u : SEO.site + '/' + u.replace(/^\//, '');
const recorta = (s = '', max = 158) => {
  const t = s.replace(/\s+/g, ' ').trim();
  if (t.length <= max) return t;
  const corte = t.slice(0, max);
  return corte.slice(0, corte.lastIndexOf(' ')).replace(/[,;:.]$/, '') + '…';
};

function meta(attr, key, content) {
  if (!content) return;
  let el = document.head.querySelector(`meta[${attr}="${key}"]`);
  if (!el) { el = document.createElement('meta'); el.setAttribute(attr, key); document.head.appendChild(el); }
  el.setAttribute('content', content);
}
function linkRel(rel, href) {
  if (!href) return;
  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);
}
/* Los alternates se auto-referencian: deben apuntar siempre a la canónica. */
function setAlternates(href) {
  ['es-EC', 'x-default'].forEach(lang => {
    let el = document.head.querySelector(`link[rel="alternate"][hreflang="${lang}"]`);
    if (!el) {
      el = document.createElement('link');
      el.setAttribute('rel', 'alternate'); el.setAttribute('hreflang', lang);
      document.head.appendChild(el);
    }
    el.setAttribute('href', href);
  });
}

/* title/description/canonical + tarjetas sociales. index:false para páginas privadas. */
function setSeo(o = {}) {
  if (o.title) document.title = o.title;
  const desc = o.description ? recorta(o.description) : '';
  meta('name', 'description', desc);
  if (o.canonical) { linkRel('canonical', absUrl(o.canonical)); setAlternates(absUrl(o.canonical)); }
  meta('name', 'robots', o.index === false ? 'noindex,nofollow' : 'index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1');
  meta('property', 'og:site_name', SEO.nombre);
  meta('property', 'og:locale', 'es_EC');
  meta('property', 'og:type', o.ogType || 'website');
  meta('property', 'og:title', o.ogTitle || o.title);
  meta('property', 'og:description', desc);
  meta('property', 'og:url', absUrl(o.canonical || location.pathname));
  meta('name', 'twitter:card', o.image ? 'summary_large_image' : 'summary');
  meta('name', 'twitter:title', o.ogTitle || o.title);
  meta('name', 'twitter:description', desc);
  if (o.image) {
    meta('property', 'og:image', absUrl(o.image));
    meta('property', 'og:image:alt', o.imageAlt || o.title || SEO.nombre);
    meta('name', 'twitter:image', absUrl(o.image));
  }
  if (o.keywords) meta('name', 'keywords', o.keywords);
}

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

const orgLd = () => ({
  '@context': 'https://schema.org', '@type': 'RealEstateAgent', '@id': SEO.site + '/#organizacion',
  name: SEO.nombre, url: SEO.site, logo: SEO.logo, image: SEO.logo,
  description: 'Portal inmobiliario en Ecuador: casas, departamentos y terrenos en venta y arriendo en Quito y los valles, con financiamiento BIESS, VIP, Miti-Miti y banca privada.',
  telephone: SEO.telefono, email: SEO.correo, priceRange: '$$',
  areaServed: [{ '@type': 'City', name: 'Quito' }, { '@type': 'AdministrativeArea', name: 'Pichincha' }],
  address: { '@type': 'PostalAddress', addressLocality: 'Quito', addressRegion: 'Pichincha', addressCountry: 'EC' },
  openingHoursSpecification: [{ '@type': 'OpeningHoursSpecification', dayOfWeek: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], opens: '00:00', closes: '23:59' }],
  sameAs: SEO.redes
});
const siteLd = () => ({
  '@context': 'https://schema.org', '@type': 'WebSite', '@id': SEO.site + '/#sitio',
  url: SEO.site, name: SEO.nombre, inLanguage: 'es-EC',
  publisher: { '@id': SEO.site + '/#organizacion' },
  potentialAction: {
    '@type': 'SearchAction',
    target: { '@type': 'EntryPoint', urlTemplate: SEO.site + SEO.paths.propiedades + '?q={search_term_string}' },
    'query-input': 'required name=search_term_string'
  }
});
const breadcrumbLd = (items) => ({
  '@context': 'https://schema.org', '@type': 'BreadcrumbList',
  itemListElement: items.map(([name, url], i) => ({
    '@type': 'ListItem', position: i + 1, name, item: url ? absUrl(url) : undefined
  }))
});

/* Ficha de una propiedad: RealEstateListing + Offer + Residence/Accommodation. */
function propertyLd(p) {
  const url = propertyUrl(p);
  const arrienda = /arriendo|renta/i.test(p.operacion || '');
  const alojamiento = {
    '@type': p.tipo === 'Terreno' ? 'Place' : (/departamento|suite/i.test(p.tipo) ? 'Apartment' : 'SingleFamilyResidence'),
    name: p.titulo,
    address: {
      '@type': 'PostalAddress', streetAddress: p.direccion || undefined,
      addressLocality: p.ciudad, addressRegion: p.ciudad === 'Quito' ? 'Pichincha' : undefined,
      addressCountry: 'EC'
    },
    floorSize: p.area ? { '@type': 'QuantitativeValue', value: p.area, unitCode: 'MTK' } : undefined,
    numberOfRooms: p.habitaciones || undefined,
    numberOfBedrooms: p.habitaciones || undefined,
    numberOfBathroomsTotal: p.banos || undefined,
    amenityFeature: (p.amenidades || []).map(a => ({ '@type': 'LocationFeatureSpecification', name: a, value: true })),
    geo: (p.lat && p.lng) ? { '@type': 'GeoCoordinates', latitude: p.lat, longitude: p.lng } : undefined
  };
  return {
    '@context': 'https://schema.org', '@type': 'RealEstateListing', '@id': url + '#anuncio',
    url, name: p.titulo, description: recorta(p.descripcion || '', 300),
    datePosted: p.fecha, inLanguage: 'es-EC',
    image: (p.fotos || []).slice(0, 8),
    isPartOf: { '@id': SEO.site + '/#sitio' },
    provider: { '@id': SEO.site + '/#organizacion' },
    about: alojamiento,
    containedInPlace: { '@type': 'Place', name: p.sector + ', ' + p.ciudad },
    offers: {
      '@type': 'Offer', price: p.precio, priceCurrency: 'USD', availability: 'https://schema.org/InStock',
      businessFunction: arrienda ? 'http://purl.org/goodrelations/v1#LeaseOut' : 'http://purl.org/goodrelations/v1#Sell',
      url, seller: { '@id': SEO.site + '/#organizacion' },
      ...(arrienda ? { priceSpecification: { '@type': 'UnitPriceSpecification', price: p.precio, priceCurrency: 'USD', unitText: 'MES' } } : {})
    }
  };
}

const itemListLd = (list, nombre, url) => ({
  '@context': 'https://schema.org', '@type': 'ItemList', name: nombre,
  url: absUrl(url), numberOfItems: list.length,
  itemListElement: list.slice(0, 30).map((p, i) => ({
    '@type': 'ListItem', position: i + 1, url: propertyUrl(p), name: p.titulo
  }))
});

const faqLd = (pares) => ({
  '@context': 'https://schema.org', '@type': 'FAQPage',
  mainEntity: pares.map(([q, a]) => ({ '@type': 'Question', name: q, acceptedAnswer: { '@type': 'Answer', text: a } }))
});

/* Texto de descripción de una propiedad, pensado para el snippet de Google. */
function propertyDescription(p) {
  const partes = [
    p.tipo + (p.operacion ? ' en ' + p.operacion.toLowerCase() : ''),
    'en ' + p.sector + ', ' + p.ciudad,
    p.precio ? 'por $' + Number(p.precio).toLocaleString('es-EC').replace(/,/g, '.') : ''
  ].filter(Boolean).join(' ');
  const specs = [
    p.habitaciones ? p.habitaciones + (p.habitaciones === 1 ? ' dormitorio' : ' dormitorios') : '',
    p.banos ? p.banos + (p.banos === 1 ? ' baño' : ' baños') : '',
    p.parqueaderos ? p.parqueaderos + (p.parqueaderos === 1 ? ' parqueadero' : ' parqueaderos') : '',
    p.area ? Number(p.area).toLocaleString('es-EC').replace(/,/g, '.') + ' m²' : ''
  ].filter(Boolean).join(' · ');
  const fin = p.financiamiento ? ' Aplica a ' + p.financiamiento + '.' : '';
  return recorta(partes + '. ' + specs + '.' + fin + ' Fotos, ubicación y contacto directo en casamia.ec.');
}

Object.assign(window, { SEO, setSeo, setAlternates, jsonLd, slugify, propertyUrl, absUrl, recorta, orgLd, siteLd, breadcrumbLd, propertyLd, itemListLd, faqLd, propertyDescription });
