/* GCCReady — PageHead: per-route SEO / AEO / GEO / AI-search visibility.
 *
 * Mutates <head> on every render: title, meta description, canonical, OG tags,
 * Twitter card, and Schema.org JSON-LD blocks. Cleans up on unmount.
 *
 * Usage at the top of any page component:
 *   <PageHead
 *     title="GCCReady — US CPA Pathway"
 *     description="..."
 *     canonical="/certifications/us-cpa"
 *     schema={[orgSchema(), courseSchema({...})]}
 *   />
 */

const SITE_ORIGIN = 'https://gccready.com';
const SITE_NAME   = 'GCCReady';
const OG_IMAGE    = `${SITE_ORIGIN}/og-default.png`; // host this when ready
const TWITTER     = '@gccready';

function _setMeta(selector, attrs) {
  let el = document.head.querySelector(selector);
  if (!el) {
    el = document.createElement('meta');
    Object.entries(attrs.create || {}).forEach(([k, v]) => el.setAttribute(k, v));
    document.head.appendChild(el);
  }
  Object.entries(attrs.set || {}).forEach(([k, v]) => el.setAttribute(k, v));
}
function _setLink(rel, href) {
  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);
}
function _setSchemas(blocks) {
  // Remove previous gccready schema blocks
  document.head.querySelectorAll('script[data-gr-schema]').forEach((n) => n.remove());
  (blocks || []).forEach((obj, i) => {
    if (!obj) return;
    const s = document.createElement('script');
    s.type = 'application/ld+json';
    s.setAttribute('data-gr-schema', String(i));
    s.text = JSON.stringify(obj);
    document.head.appendChild(s);
  });
}

function PageHead({ title, description, canonical, ogImage, ogType = 'website', schema }) {
  React.useEffect(() => {
    const fullTitle = title ? `${title} — ${SITE_NAME}` : SITE_NAME;
    document.title = fullTitle;

    _setMeta('meta[name="description"]', { create:{name:'description'}, set:{content: description || ''} });
    _setMeta('meta[name="robots"]',      { create:{name:'robots'},      set:{content: 'index,follow,max-image-preview:large,max-snippet:-1'} });
    _setMeta('meta[name="theme-color"]', { create:{name:'theme-color'}, set:{content: '#0D1B2A'} });

    const url = canonical ? `${SITE_ORIGIN}${canonical}` : SITE_ORIGIN;
    _setLink('canonical', url);

    // Open Graph
    _setMeta('meta[property="og:title"]',       { create:{property:'og:title'},       set:{content: fullTitle} });
    _setMeta('meta[property="og:description"]', { create:{property:'og:description'}, set:{content: description || ''} });
    _setMeta('meta[property="og:type"]',        { create:{property:'og:type'},        set:{content: ogType} });
    _setMeta('meta[property="og:url"]',         { create:{property:'og:url'},         set:{content: url} });
    _setMeta('meta[property="og:image"]',       { create:{property:'og:image'},       set:{content: ogImage || OG_IMAGE} });
    _setMeta('meta[property="og:site_name"]',   { create:{property:'og:site_name'},   set:{content: SITE_NAME} });

    // Twitter
    _setMeta('meta[name="twitter:card"]',        { create:{name:'twitter:card'},        set:{content:'summary_large_image'} });
    _setMeta('meta[name="twitter:site"]',        { create:{name:'twitter:site'},        set:{content: TWITTER} });
    _setMeta('meta[name="twitter:title"]',       { create:{name:'twitter:title'},       set:{content: fullTitle} });
    _setMeta('meta[name="twitter:description"]', { create:{name:'twitter:description'}, set:{content: description || ''} });

    _setSchemas(schema);
  }, [title, description, canonical, ogImage, ogType, JSON.stringify(schema || [])]);

  return null;
}

/* ============================================================================
 * Schema.org builders — keep these light + composable
 * ========================================================================== */
function schemaOrganization() {
  return {
    '@context':'https://schema.org',
    '@type':'Organization',
    'name': SITE_NAME,
    'alternateName':'GCCReady — Career platform for India\'s GCCs',
    'url': SITE_ORIGIN,
    'logo': `${SITE_ORIGIN}/og-logo.png`,
    'description':'India\'s career platform for Global Capability Centres. Skill Badge, role pods, US CPA / CMA / EA / CFA / ACCA pathways, and Mini-GCC setup for US founders.',
    'sameAs': [
      'https://www.linkedin.com/company/gccready',
      'https://x.com/gccready',
      'https://www.youtube.com/@gccready',
    ],
    'contactPoint': {
      '@type':'ContactPoint',
      'contactType':'customer service',
      'email':'info@gccready.com',
      'areaServed':['IN','US','AE','UK'],
      'availableLanguage':['English','Hindi'],
    },
    'address': {
      '@type':'PostalAddress',
      'addressLocality':'Bengaluru',
      'addressRegion':'Karnataka',
      'addressCountry':'IN',
    },
  };
}

function schemaWebSite() {
  return {
    '@context':'https://schema.org',
    '@type':'WebSite',
    'name': SITE_NAME,
    'url': SITE_ORIGIN,
    'potentialAction': {
      '@type':'SearchAction',
      'target': `${SITE_ORIGIN}/resources/library?q={search_term_string}`,
      'query-input':'required name=search_term_string',
    },
  };
}

function schemaBreadcrumb(items) {
  return {
    '@context':'https://schema.org',
    '@type':'BreadcrumbList',
    'itemListElement': items.map((it, i) => ({
      '@type':'ListItem',
      'position': i + 1,
      'name': it.label,
      'item': it.href ? `${SITE_ORIGIN}${it.href}` : undefined,
    })),
  };
}

function schemaCourse({ name, description, slug, provider = SITE_NAME, mode = 'Online', credential, url }) {
  return {
    '@context':'https://schema.org',
    '@type':'Course',
    'name': name,
    'description': description,
    'provider': { '@type':'Organization', 'name': provider, 'url': SITE_ORIGIN },
    'url': url || `${SITE_ORIGIN}${slug}`,
    'educationalCredentialAwarded': credential || name,
    'hasCourseInstance': {
      '@type':'CourseInstance',
      'courseMode': mode,
      'courseWorkload':'PT5H',
    },
  };
}

function schemaFAQ(qa) {
  return {
    '@context':'https://schema.org',
    '@type':'FAQPage',
    'mainEntity': qa.map((p) => ({
      '@type':'Question',
      'name': p.q,
      'acceptedAnswer': { '@type':'Answer', 'text': p.a },
    })),
  };
}

function schemaCollection({ name, description, url, items }) {
  return {
    '@context':'https://schema.org',
    '@type':'CollectionPage',
    'name': name,
    'description': description,
    'url': `${SITE_ORIGIN}${url}`,
    'mainEntity': {
      '@type':'ItemList',
      'numberOfItems': items.length,
      'itemListElement': items.slice(0, 50).map((it, i) => ({
        '@type':'ListItem',
        'position': i + 1,
        'name': it.name,
        'url': `${SITE_ORIGIN}${it.url}`,
      })),
    },
  };
}

function schemaService({ name, description, slug, serviceType, areaServed = 'IN' }) {
  return {
    '@context':'https://schema.org',
    '@type':'Service',
    'name': name,
    'serviceType': serviceType,
    'description': description,
    'provider': { '@type':'Organization', 'name': SITE_NAME, 'url': SITE_ORIGIN },
    'url': `${SITE_ORIGIN}${slug}`,
    'areaServed': areaServed,
  };
}

Object.assign(window, {
  PageHead, SITE_ORIGIN, SITE_NAME,
  schemaOrganization, schemaWebSite, schemaBreadcrumb,
  schemaCourse, schemaFAQ, schemaCollection, schemaService,
});
