// SEO + AI metadata — per-route titles, descriptions, Open Graph, and JSON-LD.
// Updates document head reactively when the route changes.

const SITE = {
  name: 'Tailored Mediation',
  url: 'https://tailoredmediation.com',
  defaultDescription: 'Mediation, arbitration, special master, and forensic neutral services for AI, software, IP, and cybersecurity disputes. Daniel B. Garrie, Esq. — founder of Law & Forensics, Harvard Extension adjunct, author of 300+ articles and 20 books.',
  ogImage: 'https://tailoredmediation.com/assets/og-card.jpg',
  twitter: '@dbgarrie',
};

const ROUTE_META = {
  'home': {
    title: 'Tailored Mediation — Daniel B. Garrie, Esq. · World-class Mediator, Arbitrator, Special Master & Forensic Neutral',
    description: 'Tailored Mediation is the practice of Daniel B. Garrie, Esq. — a world-class mediator, arbitrator, special master, and forensic neutral with 20+ years resolving high-stakes disputes in AI, software, IP, cybersecurity, and digital forensics.',
    keywords: 'mediator, arbitrator, special master, forensic neutral, AI disputes mediation, cybersecurity mediation, eDiscovery, technical neutral, Daniel Garrie',
  },
  'services': {
    title: 'Engagements — Mediation, Arbitration, Special Master, Forensic Neutral · Tailored Mediation',
    description: 'Five engagement types: high-stakes mediation, special master & discovery referee, forensic neutral, AI disputes tribunal services, and arbitration. Each with practice areas and representative matters.',
    keywords: 'mediation services, special master, discovery referee, forensic neutral, AI arbitration, technical neutral',
  },
  'process': {
    title: 'Process & Methodology — Per-Engagement Deep Dives · Tailored Mediation',
    description: 'How each engagement runs, phase by phase. Mediation, special master, forensic neutral, AI disputes, arbitration — protocols, deliverables, timelines, and the five principles that hold across every role.',
    keywords: 'mediation process, special master process, forensic neutral protocol, ESI protocol, AI arbitration framework',
  },
  'intake': {
    title: 'Match Intake — Eight Confidential Questions · Tailored Mediation',
    description: 'Confidential matter request that routes to a vetted neutral with subject-matter fluency for your dispute. Eight considered questions, five minutes.',
    keywords: 'mediation intake, neutral match, retention, special master appointment',
  },
  'insights': {
    title: 'Insights — Articles on Technical Dispute Resolution · Daniel B. Garrie',
    description: 'Working notebook on technically complex dispute resolution: AI hallucinations in litigation, forensic data as a mediation asset, the evolution of the technical neutral.',
    keywords: 'AI litigation, forensic mediation, special masters, technical dispute resolution, Daniel Garrie articles',
  },
  'publications': {
    title: 'Publications & Books — Daniel B. Garrie · 20+ Books, 300+ Articles',
    description: 'Curated publications: books and treatises (Plugged In, Cybersecurity & the Courthouse, Law Firm Cybersecurity), law-review articles (Harvard Nat\u2019l Sec. J., Cardozo L. Rev., Brooklyn J. Int\u2019l L.), book chapters, and trade press.',
    keywords: 'Daniel Garrie books, Daniel Garrie articles, cybersecurity treatise, plugged in, eDiscovery treatise',
  },
  'speaking': {
    title: 'Speaking & Events — 600+ Engagements · Daniel B. Garrie',
    description: 'Past and upcoming speaking engagements. RSA Conference, ABA, Harvard Extension, Tel Aviv Cyber Week, Sedona Conference, judicial colleges, and more. Booking inquiries welcome.',
    keywords: 'Daniel Garrie speaker, CLE speaker, cybersecurity conference, AI mediation keynote, judicial college speaker',
  },
  'faq': {
    title: 'FAQ — Frequently Asked Questions for Counsel · Tailored Mediation',
    description: 'Quick answers and deep-dive questions on retention, conflicts, timeline, evidence handling, AI tribunal procedures, and engagement fees.',
    keywords: 'mediation FAQ, special master FAQ, forensic neutral FAQ, retention questions',
  },
  'engagement-terms': {
    title: 'Engagement Terms — Retention Paths, Fees, Process · Tailored Mediation',
    description: 'How retention works — court-appointed, party-stipulated, and administered engagements. Six-step retention process; factors that shape per-matter fee scoping.',
    keywords: 'mediator retention, special master fees, forensic neutral fees, party-stipulated neutral',
  },
  'about': {
    title: 'About Daniel B. Garrie, Esq. — Mediator, Arbitrator, Special Master, Forensic Neutral',
    description: 'Daniel B. Garrie, Esq. — founder of Law & Forensics, adjunct at Harvard Extension School, author of 20+ books and 400+ publications cited in 500+ articles and judicial opinions. 20+ years at the intersection of law and technology.',
    keywords: 'Daniel B Garrie biography, Daniel Garrie credentials, Law and Forensics founder, Harvard cybersecurity adjunct, technical neutral',
  },
  'what-is': {
    title: 'What is Tailored Mediation? — A Practice for Technical Disputes',
    description: 'Tailored mediation is alternative dispute resolution scoped to the matter — its technical character, scale, venue, and risk tolerance. Origins, characteristics, and when the model fits.',
    keywords: 'what is tailored mediation, technical mediation, custom mediation, ADR for AI disputes',
  },
  'tailored-vs-standard': {
    title: 'Tailored vs. Standard Mediation — A Comparison for Counsel',
    description: 'Side-by-side: process design, neutral profile, evidence handling, confidentiality, timelines, costs, and outcomes. When tailored mediation fits and when standard is the right tool.',
    keywords: 'tailored mediation vs standard mediation, technical mediator, ADR comparison',
  },
  'notable-matters': {
    title: 'Notable Matters — Anonymized Representative Engagements · Tailored Mediation',
    description: 'Anonymized representative matters across AI, cyber insurance, trade secret, eDiscovery, smart contracts, privacy, cross-border commercial, and patent litigation. No party names; matter type, role, technical issue, and outcome category only.',
    keywords: 'notable matters, representative engagements, AI arbitration, trade secret special master, cyber insurance mediator',
  },
  'mediation': {
    title: 'Mediation — Privately-administered for technically complex disputes · Tailored Mediation',
    description: 'High-stakes mediation for AI, cyber, trade secret, smart contracts, and cross-border commercial disputes. Daniel B. Garrie reads source code AND case law in the room.',
    keywords: 'mediation, technical mediator, AI mediation, cyber mediation, trade secret mediation, smart contract mediation',
  },
  'special-master': {
    title: 'Special Master — Court-appointed discovery referee · Tailored Mediation',
    description: 'eDiscovery Special Master and Discovery Referee for technically complex litigation. ESI protocols, TAR/CAL validation, spoliation findings, source-code review.',
    keywords: 'special master, discovery referee, eDiscovery special master, ESI protocol, FRCP 37 spoliation',
  },
  'forensic-neutral': {
    title: 'Forensic Neutral — Independent third-party technical expert · Tailored Mediation',
    description: 'Tribunal-appointed forensic neutral for trade secret, IP, fraud, employment, bankruptcy, deepfake authentication, smart-contract on-chain forensics.',
    keywords: 'forensic neutral, deepfake authentication, on-chain forensics, chain of custody, FRE 901',
  },
  'ai-disputes': {
    title: 'AI Disputes — Tribunal services · Tailored Mediation',
    description: 'Arbitrator and protocol architect for AI disputes — model output liability, training data IP, hallucination, algorithmic bias, generative IP, embedded ML in safety-critical products.',
    keywords: 'AI disputes, AI arbitration, model output liability, training data IP, hallucination dispute, algorithmic bias',
  },
  'arbitration': {
    title: 'Arbitration — Sole or panel · Tailored Mediation',
    description: 'Sole and panel arbitrator for technically complex commercial matters. SaaS SLA, data breach coverage, cryptocurrency, software licensing, patent validity/infringement, smart contracts.',
    keywords: 'arbitration, technical arbitrator, SaaS arbitration, cyber insurance arbitration, software licensing arbitration',
  },
  'explore': {
    title: 'Explore — Sitemap & Wayfinding · Tailored Mediation',
    description: 'Discovery hub for tailoredmediation.com. Three sections, sixteen pages: About / Practice / Writing & Voice. Pick where to start by who Daniel is, by the matter you have, or by the body of work behind the practice.',
    keywords: 'site map, tailored mediation index, navigation, explore practice',
  },
  'contact': {
    title: 'Contact — Tailored Mediation · Daniel B. Garrie, Esq.',
    description: 'Reach the practice. Direct retentions, speaking inquiries, press. By appointment. Anchor in-person venues: LA, NYC, Tel Aviv, Geneva, Singapore. Additional venues by arrangement; virtual or hybrid wherever else.',
    keywords: 'contact Daniel Garrie, mediation contact, neutral booking',
  },
  'legal': {
    title: 'Legal — Privacy, Terms, Disclaimer, Accessibility · Tailored Mediation',
    description: 'Privacy policy, terms of use, disclaimer, and accessibility statement for tailoredmediation.com.',
    keywords: 'privacy policy, terms of use, accessibility, ADR disclaimer',
  },
};

const PERSON_JSONLD = {
  '@context': 'https://schema.org',
  '@type': 'Person',
  '@id': 'https://tailoredmediation.com/#daniel-garrie',
  name: 'Daniel B. Garrie',
  honorificSuffix: 'Esq.',
  jobTitle: 'Mediator · Arbitrator · Special Master · Forensic Neutral',
  description: 'Daniel B. Garrie, Esq. — mediator, arbitrator, special master, and forensic neutral. Founder of Law & Forensics LLC; adjunct at Harvard Extension School. 20+ years at the intersection of law and technology. Author of 20+ books and 300+ articles cited in 500+ articles and judicial opinions.',
  url: 'https://tailoredmediation.com',
  image: 'https://tailoredmediation.com/assets/dg-portrait.jpg',
  sameAs: [
    'https://www.lawandforensics.com',
    'https://scholar.google.com/citations?user=daniel+garrie',
  ],
  alumniOf: [
    { '@type': 'CollegeOrUniversity', name: 'Rutgers School of Law' },
    { '@type': 'CollegeOrUniversity', name: 'Brandeis University' },
  ],
  worksFor: [
    { '@type': 'Organization', name: 'Law & Forensics LLC', url: 'https://www.lawandforensics.com' },
    { '@type': 'CollegeOrUniversity', name: 'Harvard Extension School', url: 'https://extension.harvard.edu' },
  ],
  award: [
    'Distinguished Neutral, Academy of Court Appointed Masters',
    'Distinguished Neutral, CPR Institute for Conflict Prevention & Resolution',
    'Fellow, Ponemon Institute for Data Privacy and Protection',
    'Fellow, Academy of Court Appointed Neutrals',
    'Co-inventor, U.S. Patents 10546129, 10528738, 9990498, 9990497',
  ],
  knowsAbout: [
    'Mediation', 'Arbitration', 'Special Master', 'Forensic Neutral',
    'Artificial Intelligence Disputes', 'Cybersecurity', 'eDiscovery',
    'Digital Forensics', 'Smart Contracts', 'Cryptocurrency',
    'Cyber Insurance Coverage', 'Trade Secret', 'Patent Litigation',
    'Privacy Law', 'GDPR', 'CCPA',
  ],
};

const ORGANIZATION_JSONLD = {
  '@context': 'https://schema.org',
  '@type': 'ProfessionalService',
  '@id': 'https://tailoredmediation.com/#org',
  name: 'Tailored Mediation',
  alternateName: 'Tailored Mediation \u2014 Daniel B. Garrie, Esq.',
  url: 'https://tailoredmediation.com',
  logo: 'https://tailoredmediation.com/assets/dg-portrait-sm.jpg',
  image: 'https://tailoredmediation.com/assets/dg-portrait.jpg',
  description: 'Mediation, arbitration, special master, and forensic neutral services for technically complex disputes. Daniel B. Garrie, Esq. resolves high-stakes matters in AI, software, IP, cybersecurity, and digital forensics across more than ten venues globally.',
  founder: { '@id': 'https://tailoredmediation.com/#daniel-garrie' },
  employee: { '@id': 'https://tailoredmediation.com/#daniel-garrie' },
  serviceType: ['Mediation', 'Arbitration', 'Special Master', 'Forensic Neutral', 'Discovery Referee'],
  areaServed: [
    { '@type': 'Place', name: 'Worldwide' },
    { '@type': 'City', name: 'Los Angeles', address: { '@type': 'PostalAddress', addressRegion: 'CA', addressCountry: 'US' } },
    { '@type': 'City', name: 'New York',    address: { '@type': 'PostalAddress', addressRegion: 'NY', addressCountry: 'US' } },
    { '@type': 'City', name: 'Tel Aviv',    address: { '@type': 'PostalAddress', addressCountry: 'IL' } },
    { '@type': 'City', name: 'Geneva',      address: { '@type': 'PostalAddress', addressCountry: 'CH' } },
    { '@type': 'City', name: 'Singapore',   address: { '@type': 'PostalAddress', addressCountry: 'SG' } },
  ],
  contactPoint: {
    '@type': 'ContactPoint',
    contactType: 'customer service',
    email: 'matters@tailoredmediation.com',
    areaServed: 'Worldwide',
    availableLanguage: ['en'],
  },
};

// Article schema generator — used when an article-* route is active.
// articleId is the unique slug (e.g. 'hallucinations'); meta comes from window.articles.
function makeArticleJSONLD(articleId) {
  const article = (window.articles || []).find(a => a.id === articleId);
  if (!article) return null;
  // Convert "March 14, 2026" → ISO 8601 date
  const dateText = article.date || '';
  let datePub = '';
  try {
    const d = new Date(dateText);
    if (!isNaN(d.getTime())) datePub = d.toISOString().slice(0, 10);
  } catch (e) {}
  return {
    '@context': 'https://schema.org',
    '@type': 'Article',
    '@id': `https://tailoredmediation.com/insights/${articleId}#article`,
    mainEntityOfPage: `https://tailoredmediation.com/insights/${articleId}`,
    headline: article.title,
    description: article.deck,
    articleSection: article.cat,
    keywords: (article.tags || []).join(', '),
    datePublished: datePub,
    dateModified: datePub,
    author: { '@id': 'https://tailoredmediation.com/#daniel-garrie' },
    publisher: { '@id': 'https://tailoredmediation.com/#org' },
    image: 'https://tailoredmediation.com/assets/og-card.jpg',
  };
}

// FAQ schema generator — for the /faq page.
function makeFAQJSONLD() {
  if (!window.QUICK_FAQS && !window.DEEP_FAQ_SECTIONS) return null;
  const items = [];
  (window.QUICK_FAQS || []).forEach(f => items.push({
    '@type': 'Question', name: f.q,
    acceptedAnswer: { '@type': 'Answer', text: f.a },
  }));
  (window.DEEP_FAQ_SECTIONS || []).forEach(s => {
    (s.qs || []).forEach(qa => items.push({
      '@type': 'Question', name: qa.q,
      acceptedAnswer: { '@type': 'Answer', text: qa.a },
    }));
  });
  if (items.length === 0) return null;
  return {
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    '@id': 'https://tailoredmediation.com/faq#faqpage',
    mainEntity: items,
  };
}

function makeBreadcrumb(page) {
  const map = {
    'home': [{ name: 'Home', item: 'https://tailoredmediation.com/' }],
    'about': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'About', item: 'https://tailoredmediation.com/about' }],
    'services': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Engagements', item: 'https://tailoredmediation.com/services' }],
    'process': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Process', item: 'https://tailoredmediation.com/process' }],
    'insights': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Insights', item: 'https://tailoredmediation.com/insights' }],
    'publications': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Publications', item: 'https://tailoredmediation.com/publications' }],
    'speaking': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Speaking', item: 'https://tailoredmediation.com/speaking' }],
    'faq': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'FAQ', item: 'https://tailoredmediation.com/faq' }],
    'engagement-terms': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Engagement Terms', item: 'https://tailoredmediation.com/engagement-terms' }],
    'what-is': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'What is Tailored Mediation', item: 'https://tailoredmediation.com/what-is-tailored-mediation' }],
    'tailored-vs-standard': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'What is Tailored Mediation', item: 'https://tailoredmediation.com/what-is-tailored-mediation' }, { name: 'Tailored vs. Standard', item: 'https://tailoredmediation.com/tailored-vs-standard-mediation' }],
    'notable-matters': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Practice', item: 'https://tailoredmediation.com/services' }, { name: 'Notable Matters', item: 'https://tailoredmediation.com/notable-matters' }],
    'mediation': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Practice', item: 'https://tailoredmediation.com/services' }, { name: 'Mediation', item: 'https://tailoredmediation.com/mediation' }],
    'special-master': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Practice', item: 'https://tailoredmediation.com/services' }, { name: 'Special Master', item: 'https://tailoredmediation.com/special-master' }],
    'forensic-neutral': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Practice', item: 'https://tailoredmediation.com/services' }, { name: 'Forensic Neutral', item: 'https://tailoredmediation.com/forensic-neutral' }],
    'ai-disputes': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Practice', item: 'https://tailoredmediation.com/services' }, { name: 'AI Disputes', item: 'https://tailoredmediation.com/ai-disputes' }],
    'arbitration': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Practice', item: 'https://tailoredmediation.com/services' }, { name: 'Arbitration', item: 'https://tailoredmediation.com/arbitration' }],
    'explore': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Explore', item: 'https://tailoredmediation.com/explore' }],
    'intake': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Intake', item: 'https://tailoredmediation.com/intake' }],
    'contact': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Contact', item: 'https://tailoredmediation.com/contact' }],
    'legal': [{ name: 'Home', item: 'https://tailoredmediation.com/' }, { name: 'Legal', item: 'https://tailoredmediation.com/legal' }],
  };
  const items = map[page] || map['home'];
  return {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: items.map((it, i) => ({
      '@type': 'ListItem',
      position: i + 1,
      name: it.name,
      item: it.item,
    })),
  };
}

function setMeta(name, value, attr = 'name') {
  if (!value) return;
  let el = document.querySelector(`meta[${attr}="${name}"]`);
  if (!el) {
    el = document.createElement('meta');
    el.setAttribute(attr, name);
    document.head.appendChild(el);
  }
  el.setAttribute('content', value);
}

function setLink(rel, href) {
  let el = document.querySelector(`link[rel="${rel}"]`);
  if (!el) {
    el = document.createElement('link');
    el.setAttribute('rel', rel);
    document.head.appendChild(el);
  }
  el.setAttribute('href', href);
}

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

function removeJSONLD(id) {
  const el = document.getElementById(id);
  if (el) el.remove();
}

// Truncate a string to ~155 characters (Google's typical SERP cutoff).
function clamp(s, n = 155) {
  if (!s) return s;
  if (s.length <= n) return s;
  return s.slice(0, n - 1).replace(/\s+\S*$/, '') + '\u2026';
}

// Public component — drop in App, pass current `page`.
function SEO({ page }) {
  React.useEffect(() => {
    // Article routes carry meta drawn from the article object.
    let meta = ROUTE_META[page];
    let isArticle = false;
    let articleId = null;
    if (!meta && typeof page === 'string' && page.startsWith('article-')) {
      isArticle = true;
      articleId = page.replace('article-', '');
      const article = (window.articles || []).find(a => a.id === articleId);
      if (article) {
        meta = {
          title: `${article.title} \u00b7 Insights from the Bench \u00b7 Daniel B. Garrie`,
          description: article.deck,
          keywords: (article.tags || []).concat([article.cat, 'Daniel Garrie', 'mediation', 'arbitration']).join(', '),
        };
      }
    }
    if (!meta) meta = ROUTE_META['home'];

    document.title = meta.title;
    setMeta('description', clamp(meta.description, 158));
    setMeta('keywords', meta.keywords);

    // Canonical URL — must match the routes in /index.html and sitemap.xml
    const PATH_MAP = {
      'home': '',
      'what-is': 'what-is-tailored-mediation',
      'tailored-vs-standard': 'tailored-vs-standard-mediation',
    };
    const path =
      isArticle ? `insights/${articleId}` :
      PATH_MAP[page] !== undefined ? PATH_MAP[page] :
      page;
    const url = `https://tailoredmediation.com/${path}`;
    setLink('canonical', url);

    // Open Graph
    setMeta('og:title', meta.title, 'property');
    setMeta('og:description', clamp(meta.description, 200), 'property');
    setMeta('og:url', url, 'property');
    setMeta('og:image', SITE.ogImage, 'property');
    setMeta('og:image:width', '1200', 'property');
    setMeta('og:image:height', '630', 'property');
    setMeta('og:image:alt', 'Tailored Mediation \u2014 Daniel B. Garrie, Esq.', 'property');
    setMeta('og:type', isArticle ? 'article' : 'website', 'property');
    setMeta('og:site_name', SITE.name, 'property');
    setMeta('og:locale', 'en_US', 'property');

    // Article-specific OG
    if (isArticle) {
      const article = (window.articles || []).find(a => a.id === articleId);
      if (article) {
        setMeta('article:author', 'Daniel B. Garrie, Esq.', 'property');
        setMeta('article:section', article.cat, 'property');
        try {
          const d = new Date(article.date);
          if (!isNaN(d.getTime())) setMeta('article:published_time', d.toISOString(), 'property');
        } catch (e) {}
        (article.tags || []).forEach(t => {
          // article:tag can repeat, but with only one tag meta, latest wins.
          // For multi-tag fidelity we'd need separate <meta> elements; this is approximate.
        });
      }
    }

    // Twitter
    setMeta('twitter:card', 'summary_large_image');
    setMeta('twitter:title', meta.title);
    setMeta('twitter:description', clamp(meta.description, 200));
    setMeta('twitter:image', SITE.ogImage);
    setMeta('twitter:image:alt', 'Tailored Mediation \u2014 Daniel B. Garrie, Esq.');

    // Robots — index everything except intake (private form)
    setMeta('robots', page === 'intake' ? 'noindex, follow' : 'index, follow, max-image-preview:large');

    // Always-on JSON-LD
    injectJSONLD('jsonld-person', PERSON_JSONLD);
    injectJSONLD('jsonld-org', ORGANIZATION_JSONLD);
    injectJSONLD('jsonld-breadcrumb', makeBreadcrumb(isArticle ? 'insights' : page));

    // Article JSON-LD only on article routes
    if (isArticle && articleId) {
      const data = makeArticleJSONLD(articleId);
      if (data) injectJSONLD('jsonld-article', data); else removeJSONLD('jsonld-article');
    } else {
      removeJSONLD('jsonld-article');
    }

    // FAQ JSON-LD only on FAQ page
    if (page === 'faq') {
      const data = makeFAQJSONLD();
      if (data) injectJSONLD('jsonld-faq', data); else removeJSONLD('jsonld-faq');
    } else {
      removeJSONLD('jsonld-faq');
    }
  }, [page]);
  return null;
}

Object.assign(window, { SEO, ROUTE_META, PERSON_JSONLD, ORGANIZATION_JSONLD });
