// SEO rules shared by the server (initial HTML for crawlers / link previews)
// and the browser (title + meta updates on client-side navigation).
// Pure functions — no Node or DOM APIs here.
// Languages: Romanian at the root, English under /en (same page paths).

/**
 * @typedef {{ products: any[], categories: {slug:string,name:string,name_en?:string,description:string,description_en?:string,count:number}[],
 *   series: Record<string,{text:string,text_en?:string,en?:string}>, projects: any[], company: Record<string, any>, siteUrl: string,
 *   seo?: Record<string, any>, services?: { green: any[] } }} SeoData
 * @typedef {{ status: number, lang: 'ro'|'en', title: string, description: string, path: string, basePath: string, image: string|null,
 *   noindex: boolean, type: string, jsonLd: object[] }} Seo
 */

const BRAND = 'Maksan'
/** Fallback share image if content/seo.json has none (1200×630, in git under public/og). */
const FALLBACK_IMAGE = '/og/maksan-og.jpg'

// Titles and descriptions of the fixed pages live in content/seo.json (Admin → SEO).
// Green-space services come from content/services.json (Admin → Servicii).

export const langOf = (pathname) => (pathname === '/en' || pathname.startsWith('/en/') ? 'en' : 'ro')
const stripLang = (p) => (langOf(p) === 'en' ? p.slice(3) || '/' : p)
/** Localized path for a language ("/produs/x" → "/en/produs/x"). */
export const localPath = (basePath, lang) => (lang === 'en' ? (basePath === '/' ? '/en' : `/en${basePath}`) : basePath)

function organization(d) {
  const c = d.company || {}
  return {
    '@context': 'https://schema.org',
    '@type': 'Organization',
    name: c.name || BRAND,
    alternateName: c.brand || BRAND,
    url: d.siteUrl + '/',
    logo: d.siteUrl + '/brand/maksan-mark.png',
    email: c.email || undefined,
    telephone: c.phone || undefined,
    foundingDate: c.founded ? String(c.founded) : undefined,
    taxID: c.cui || undefined,
    address: c.address
      ? { '@type': 'PostalAddress', streetAddress: c.address, addressLocality: 'București', addressCountry: 'RO' }
      : undefined,
  }
}

function breadcrumbs(d, lang, items) {
  return {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: items.map(([name, path], i) => ({ '@type': 'ListItem', position: i + 1, name, item: d.siteUrl + localPath(path, lang) })),
  }
}

/**
 * @param {string} pathname  full path, including /en for English
 * @param {SeoData} d
 * @returns {Seo}
 */
/** Shortens a description to ~160 characters at a word boundary. */
const clip = (s, n = 160) => {
  const t = String(s || '').replace(/\s+/g, ' ').trim()
  return t.length <= n ? t : t.slice(0, n - 1).replace(/\s+\S*$/, '') + '…'
}

export function seoFor(pathname, d) {
  const clean = pathname.replace(/\/+$/, '') || '/'
  const lang = langOf(clean)
  const path = stripLang(clean)
  const en = lang === 'en'
  const L = (ro, e) => (en ? e : ro)
  const defaultImage = (d.seo && d.seo._default && d.seo._default.image) || FALLBACK_IMAGE
  const base = { status: 200, lang, path: clean, basePath: path, image: defaultImage, noindex: false, type: 'website', jsonLd: [] }

  if (path === '/admin' || path.startsWith('/admin/')) {
    return { ...base, lang: 'ro', title: `Administrare · ${BRAND}`, description: '', noindex: true }
  }

  if (path === '/comparare') {
    return { ...base, title: `${L('Comparare produse', 'Compare products')} | ${BRAND}`, description: '', noindex: true }
  }

  const page = path !== '_default' && d.seo && d.seo[path]
  if (page) {
    const title = (en && page.title_en) || page.title || BRAND
    const description = (en && page.description_en) || page.description || ''
    return { ...base, title, description, image: page.image || base.image, jsonLd: path === '/' ? [organization(d)] : [] }
  }

  const catName = (c) => (en && c.name_en) || c.name

  const cat = path.match(/^\/echipamente\/([a-z0-9-]+)$/)
  if (cat) {
    const c = d.categories.find((x) => x.slug === cat[1])
    if (c) {
      const cover = d.products.find((p) => p.categorySlug === c.slug && p.images[0])
      const desc = (en && c.description_en) || c.description
      return {
        ...base,
        title: `${catName(c)} — ${c.count} ${L('produse', 'products')} | ${BRAND}`,
        description: clip(desc || `${catName(c)}: ${c.count} ${L('produse cu fișă tehnică.', 'products with technical sheets.')}`),
        image: cover ? cover.images[0].full : base.image,
        jsonLd: [breadcrumbs(d, lang, [[L('Acasă', 'Home'), '/'], [L('Echipamente', 'Equipment'), '/echipamente'], [catName(c), path]])],
      }
    }
  }

  const sv = path.match(/^\/spatii-verzi\/([a-z0-9-]+)$/)
  if (sv) {
    const g = ((d.services && d.services.green) || []).find((x) => x.slug === sv[1])
    if (g) {
      const t = (en && g.title_en) || g.title
      const items = (en && g.items_en && g.items_en.length ? g.items_en : g.items) || []
      return {
        ...base,
        title: `${t} | ${BRAND}`,
        description: clip(`${(en && g.intro_en) || g.intro} ${items.join('. ')}.`),
        image: (g.photos && g.photos[0]) || base.image,
        jsonLd: [breadcrumbs(d, lang, [[L('Acasă', 'Home'), '/'], [L('Spații verzi', 'Green spaces'), '/spatii-verzi'], [t, path]])],
      }
    }
  }

  const ser = path.match(/^\/serii\/([a-z0-9-]+)$/)
  if (ser) {
    const list = d.products.filter((p) => p.seriesSlug === ser[1])
    if (list.length) {
      const p0 = list[0]
      const info = d.series[ser[1]] || null
      const c = d.categories.find((x) => x.slug === p0.categorySlug)
      const category = c ? catName(c) : p0.category
      const label = en ? (info && info.en) || `${p0.series} Series` : `Seria ${p0.series}`
      const text = (en ? info && (info.text_en || info.text) : info && info.text) || ''
      const n = list.length
      const description = clip(
        `${label} — ${n} ${L(n === 1 ? 'produs' : 'produse', n === 1 ? 'product' : 'products')} (${category}), ${L('cu fișă tehnică EN 1176', 'with EN 1176 technical sheets')}. ${text}`,
      )
      return {
        ...base,
        title: `${label} — ${category} | ${BRAND}`,
        description,
        image: (list.find((p) => p.images[0]) || { images: [{ full: base.image }] }).images[0].full,
        jsonLd: [
          breadcrumbs(d, lang, [
            [L('Acasă', 'Home'), '/'],
            [L('Echipamente', 'Equipment'), '/echipamente'],
            [category, `/echipamente/${p0.categorySlug}`],
            [label, path],
          ]),
        ],
      }
    }
  }

  const prod = path.match(/^\/produs\/([a-z0-9-]+)$/)
  if (prod) {
    const p = d.products.find((x) => x.slug === prod[1])
    if (p) {
      const s = p.specs || {}
      const info = (p.seriesSlug && d.series[p.seriesSlug]) || null
      const c = d.categories.find((x) => x.slug === p.categorySlug)
      const category = c ? catName(c) : p.category
      const label = p.series ? (en ? (info && info.en) || `${p.series} Series` : `Seria ${p.series}`) : category
      const facts = [
        s.safetyZone && `${L('zonă de siguranță', 'safety zone')} ${s.safetyZone}`,
        s.fallHeight && `${L('înălțime de cădere', 'fall height')} ${s.fallHeight}`,
        s.age && `${L('vârstă', 'age')} ${s.age} ${L('ani', 'years')}`,
        s.users && `${s.users} ${L('utilizatori', 'users')}`,
      ].filter(Boolean)
      if (facts.length) facts[0] = facts[0][0].toUpperCase() + facts[0].slice(1)
      const text = (en ? p.description_en || (info && info.text_en) : p.description || (info && info.text)) || ''
      const description = clip(`${p.code} (${label}, ${category}). ${facts.length ? facts.join(', ') + '. ' : ''}${text}`)
      const image = p.images[0] ? p.images[0].full : base.image
      return {
        ...base,
        type: 'product',
        title: `${p.code} — ${label} | ${BRAND}`,
        description,
        image,
        jsonLd: [
          {
            '@context': 'https://schema.org',
            '@type': 'Product',
            name: `${p.code} — ${label}`,
            sku: p.code,
            category,
            description: text || description,
            image: p.images.slice(0, 5).map((i) => abs(d, i.full)),
            brand: { '@type': 'Brand', name: (d.company && d.company.partner) || 'IRMAK OYUNCAK' },
            additionalProperty: Object.entries({
              [L('Suprafață de amplasare', 'Footprint')]: s.footprint,
              [L('Zonă de siguranță', 'Safety zone')]: s.safetyZone,
              [L('Înălțime maximă', 'Maximum height')]: s.maxHeight,
              [L('Înălțime de cădere', 'Free fall height')]: s.fallHeight,
              [L('Număr de utilizatori', 'Users')]: s.users,
              [L('Grupă de vârstă (ani)', 'Age group (years)')]: s.age,
            })
              .filter(([, v]) => v)
              .map(([name, value]) => ({ '@type': 'PropertyValue', name, value })),
          },
          breadcrumbs(d, lang, [
            [L('Acasă', 'Home'), '/'],
            [L('Echipamente', 'Equipment'), '/echipamente'],
            [category, `/echipamente/${p.categorySlug}`],
            [p.code, path],
          ]),
        ],
      }
    }
  }

  return { ...base, status: 404, title: `${L('Pagina nu există', 'Page not found')} | ${BRAND}`, description: '', noindex: true }
}

export const abs = (d, url) => (/^https?:\/\//.test(url) ? url : d.siteUrl + url)

/** Builds the <head> tags managed by SEO (all carry data-seo so the browser can replace them). */
export function headTags(seo, d) {
  const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')
  const url = d.siteUrl + seo.path
  const alt = (l) => d.siteUrl + localPath(seo.basePath, l)
  const tags = [
    seo.description && `<meta data-seo name="description" content="${esc(seo.description)}">`,
    seo.noindex && '<meta data-seo name="robots" content="noindex, nofollow">',
    !seo.noindex && `<link data-seo rel="canonical" href="${esc(url)}">`,
    !seo.noindex && `<link data-seo rel="alternate" hreflang="ro" href="${esc(alt('ro'))}">`,
    !seo.noindex && `<link data-seo rel="alternate" hreflang="en" href="${esc(alt('en'))}">`,
    !seo.noindex && `<link data-seo rel="alternate" hreflang="x-default" href="${esc(alt('ro'))}">`,
    `<meta data-seo property="og:type" content="${seo.type === 'product' ? 'product' : 'website'}">`,
    `<meta data-seo property="og:site_name" content="${BRAND}">`,
    `<meta data-seo property="og:locale" content="${seo.lang === 'en' ? 'en_GB' : 'ro_RO'}">`,
    `<meta data-seo property="og:locale:alternate" content="${seo.lang === 'en' ? 'ro_RO' : 'en_GB'}">`,
    `<meta data-seo property="og:title" content="${esc(seo.title)}">`,
    seo.description && `<meta data-seo property="og:description" content="${esc(seo.description)}">`,
    `<meta data-seo property="og:url" content="${esc(url)}">`,
    seo.image && `<meta data-seo property="og:image" content="${esc(abs(d, seo.image))}">`,
    `<meta data-seo name="twitter:card" content="summary_large_image">`,
    seo.basePath === '/' && d.company && d.company.googleSiteVerification && `<meta data-seo name="google-site-verification" content="${esc(d.company.googleSiteVerification)}">`,
    ...seo.jsonLd.map((j) => `<script data-seo type="application/ld+json">${JSON.stringify(j).replace(/</g, '\\u003c')}</script>`),
  ]
  return tags.filter(Boolean).join('\n    ')
}

/** Sitemap entries: Romanian base paths of all indexable pages (English = same path under /en). */
export function sitemapPaths(d) {
  return [
    ...Object.keys(d.seo || {}).filter((k) => k.startsWith('/')),
    ...d.categories.map((c) => `/echipamente/${c.slug}`),
    ...((d.services && d.services.green) || []).map((g) => `/spatii-verzi/${g.slug}`),
    ...[...new Set(d.products.map((p) => p.seriesSlug).filter(Boolean))].map((slug) => `/serii/${slug}`),
    ...d.products.map((p) => `/produs/${p.slug}`),
  ]
}
