(function () {
  'use strict';

  var configEl = document.getElementById('webmcp-config');
  if (!configEl) {
    return;
  }

  var modelContext = navigator.modelContext || document.modelContext;
  if (!modelContext || typeof modelContext.registerTool !== 'function') {
    return;
  }

  var contactUrl = configEl.dataset.contactUrl || '/contact';
  var pageName = configEl.dataset.pageName || '';
  var recaptchaRequired = configEl.dataset.recaptchaRequired === 'true';
  var services = [];
  var pages = {};

  try {
    services = JSON.parse(configEl.dataset.services || '[]');
  } catch (e) {
    services = [];
  }

  try {
    pages = JSON.parse(configEl.dataset.pages || '{}');
  } catch (e) {
    pages = {};
  }

  function textResult(payload) {
    return {
      content: [{
        type: 'text',
        text: typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2),
      }],
    };
  }

  function getCsrfToken() {
    var match = document.cookie.match(/(?:^|;\s*)csrftoken=([^;]+)/);
    return match ? decodeURIComponent(match[1]) : '';
  }

  function resolvePageUrl(slug) {
    var page = pages[slug];
    if (page && page.url) {
      return page.url;
    }

    var service = services.find(function (entry) {
      return entry.slug === slug;
    });
    return service ? service.url : null;
  }

  function findPage(query) {
    var normalized = String(query || '').trim().toLowerCase();
    if (!normalized) {
      return null;
    }

    var keys = Object.keys(pages);
    for (var i = 0; i < keys.length; i += 1) {
      var slug = keys[i];
      var page = pages[slug];
      if (
        slug.toLowerCase() === normalized ||
        page.name.toLowerCase() === normalized ||
        page.name.toLowerCase().indexOf(normalized) !== -1
      ) {
        return {
          slug: slug,
          name: page.name,
          summary: page.summary,
          url: page.url || resolvePageUrl(slug),
        };
      }
    }

    return null;
  }

  async function getRecaptchaToken() {
    if (!recaptchaRequired) {
      return null;
    }

    if (!window.grecaptcha || typeof window.grecaptcha.execute !== 'function') {
      throw new Error(
        'reCAPTCHA is required in production. Use the HTML contact form in a browser session, ' +
        'or enable DEBUG for audit demos without captcha.'
      );
    }

    var widget = document.querySelector('.g-recaptcha');
    var siteKey = widget ? widget.getAttribute('data-sitekey') : null;
    if (!siteKey) {
      var script = document.querySelector('script[src*="recaptcha"]');
      if (script && script.src) {
        var keyMatch = script.src.match(/[?&]render=([^&]+)/);
        siteKey = keyMatch ? decodeURIComponent(keyMatch[1]) : null;
      }
    }

    if (!siteKey) {
      throw new Error('reCAPTCHA site key not found on the contact page.');
    }

    return window.grecaptcha.execute(siteKey, { action: 'contact' });
  }

  async function submitContactInquiry(input) {
    var formData = new FormData();
    formData.append('name', input.name);
    formData.append('email', input.email);
    formData.append('subject', input.subject);
    formData.append('message', input.message || '');
    formData.append('csrfmiddlewaretoken', getCsrfToken());

    if (recaptchaRequired) {
      var token = await getRecaptchaToken();
      formData.append('g-recaptcha-response', token);
    }

    var response = await fetch(contactUrl, {
      method: 'POST',
      body: formData,
      credentials: 'same-origin',
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
      },
    });

    var html = await response.text();
    if (html.indexOf("We'll be in contact shortly!") !== -1) {
      return textResult({
        success: true,
        message: 'Contact inquiry submitted successfully.',
      });
    }

    if (html.indexOf('There was an error submitting') !== -1) {
      return textResult({
        success: false,
        error: 'Submission failed validation (often reCAPTCHA in production).',
      });
    }

    if (html.indexOf('is required') !== -1) {
      return textResult({
        success: false,
        error: 'Missing required fields: name, email, and subject are required.',
      });
    }

    return textResult({
      success: false,
      error: 'Unexpected response from contact endpoint.',
      status: response.status,
    });
  }

  modelContext.registerTool({
    name: 'list_services',
    description: 'List AI ML Operations service pages with name, URL, and summary.',
    inputSchema: {
      type: 'object',
      properties: {},
    },
    annotations: { readOnlyHint: true },
    execute: function () {
      var results = services.map(function (service) {
        return {
          name: service.name,
          slug: service.slug,
          url: service.url || resolvePageUrl(service.slug),
          summary: service.summary,
        };
      });
      return textResult({ services: results });
    },
  });

  modelContext.registerTool({
    name: 'get_page_content',
    description: 'Look up a public page by slug or service name and return its URL and summary.',
    inputSchema: {
      type: 'object',
      properties: {
        query: {
          type: 'string',
          description: 'Page slug (e.g. forward_deployed) or service name (e.g. AI Agents).',
        },
      },
      required: ['query'],
    },
    annotations: { readOnlyHint: true },
    execute: function (input) {
      var page = findPage(input.query);
      if (!page) {
        return textResult({
          success: false,
          error: 'No page found for query: ' + input.query,
        });
      }
      return textResult({ success: true, page: page });
    },
  });

  modelContext.registerTool({
    name: 'navigate_to_service',
    description: 'Resolve a service slug or name to its canonical marketing page URL.',
    inputSchema: {
      type: 'object',
      properties: {
        service: {
          type: 'string',
          description: 'Service slug or display name.',
        },
      },
      required: ['service'],
    },
    annotations: { readOnlyHint: true },
    execute: function (input) {
      var page = findPage(input.service);
      if (!page) {
        return textResult({
          success: false,
          error: 'Unknown service: ' + input.service,
        });
      }
      return textResult({
        success: true,
        url: page.url,
        name: page.name,
        summary: page.summary,
      });
    },
  });

  modelContext.registerTool({
    name: 'open_contact_with_subject',
    description: 'Build a contact page URL with a pre-filled subject for hosting, pricing, or service inquiries.',
    inputSchema: {
      type: 'object',
      properties: {
        subject: {
          type: 'string',
          description: 'Subject line to pre-fill on the contact form.',
        },
      },
      required: ['subject'],
    },
    annotations: { readOnlyHint: true },
    execute: function (input) {
      var url = new URL(contactUrl, window.location.origin);
      url.searchParams.set('subject', input.subject);
      return textResult({
        success: true,
        url: url.toString(),
        subject: input.subject,
      });
    },
  });

  if (pageName === 'contact') {
    modelContext.registerTool({
      name: 'submit_contact_inquiry',
      description: 'Submit a contact inquiry to AI ML Operations. Requires name, email, and subject.',
      inputSchema: {
        type: 'object',
        properties: {
          name: { type: 'string', description: 'Sender full name.' },
          email: { type: 'string', description: 'Sender email address.' },
          subject: { type: 'string', description: 'Inquiry subject line.' },
          message: { type: 'string', description: 'Optional message body.' },
        },
        required: ['name', 'email', 'subject'],
      },
      annotations: { readOnlyHint: false },
      execute: submitContactInquiry,
    });
  }
})();
