function extract({pages}) {
  const business = { values: {}, evidence: {}, activities: [] };
  const activityByName = new Map();

  function clean(value) {
    return String(value || '').replace(/\s+/g, ' ').trim();
  }
  function text(node) {
    return clean(node && (node.innerText || node.textContent));
  }
  function put(record, key, value, page) {
    if (value !== undefined && value !== '' && value !== null) {
      record.values[key] = value;
      record.evidence[key] = page.url;
    }
  }
  function iso(year, month, day) {
    const months = {january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12};
    const number = months[String(month).toLowerCase()];
    if (!number || !year || !day) return undefined;
    return String(year) + '-' + String(number).padStart(2, '0') + '-' + String(day).padStart(2, '0');
  }
  function dates(value, year) {
    const match = clean(value).match(/(January|February|March|April|May|June|July|August|September|October|November|December)\s+(\d{1,2})(?:\s*,\s*(\d{4}))?\s*-\s*(?:(January|February|March|April|May|June|July|August|September|October|November|December)\s+)?(\d{1,2})(?:\s*,\s*(\d{4}))?/i);
    if (!match) return {};
    const firstYear = match[3] || year;
    const lastYear = match[6] || firstYear;
    if (!firstYear || !lastYear) return {};
    return { start_date: iso(firstYear, match[1], match[2]), end_date: iso(lastYear, match[4] || match[1], match[5]) };
  }
  function campName(value) {
    const found = clean(value).match(/(Ceramics Camp|Dollhouse Camp)/i);
    return found ? found[1].replace(/\b\w/g, function(c) { return c.toUpperCase(); }) : '';
  }
  function weekKey(value) {
    const found = clean(value).match(/Week\s*\d+/i);
    return found ? found[0].replace(/\s+/g, ' ').toLowerCase() : clean(value).toLowerCase();
  }
  function activity(name) {
    if (!activityByName.has(name)) {
      const item = { values: {name: name}, evidence: {name: ''}, sessions: [] };
      activityByName.set(name, item);
      business.activities.push(item);
    }
    return activityByName.get(name);
  }
  function sessionFor(item, label) {
    const key = weekKey(label);
    let session = item.sessions.find(function(candidate) { return weekKey(candidate.values.name) === key; });
    if (!session) {
      session = { values: {name: label}, evidence: {name: ''} };
      item.sessions.push(session);
    }
    return session;
  }
  function addField(record, key, value, page) {
    if (value !== undefined && value !== '') {
      record.values[key] = value;
      record.evidence[key] = page.url;
    }
  }

  for (const page of pages || []) {
    const doc = page && page.document;
    if (!doc || !page.url) continue;
    const allText = text(doc.body || doc);
    const h1s = Array.from(doc.querySelectorAll ? doc.querySelectorAll('h1') : []);
    const firstHeading = text(h1s[0]);
    if (!business.values.name && firstHeading && !/^week\s*\d+/i.test(firstHeading) && !/summer camps/i.test(firstHeading)) {
      put(business, 'name', firstHeading, page);
    }
    if (!business.values.website && /\/$/.test(page.url)) put(business, 'website', page.url, page);

    const emailNode = doc.querySelector && doc.querySelector('[data-hook="business-email"]');
    if (emailNode && !business.values.contact_email) put(business, 'contact_email', text(emailNode), page);
    const addressNode = doc.querySelector && doc.querySelector('[data-hook="business-address"]');
    if (addressNode && !business.values.locations) put(business, 'locations', [{address: text(addressNode)}], page);

    const isDetail = /service-page/i.test(page.url) && doc.querySelector;
    if (isDetail) {
      const titleNode = doc.querySelector('[data-hook="title-and-tagline-title"]') || doc.querySelector('h1');
      const title = text(titleNode);
      const name = campName(title);
      if (name && /^week\s*\d+/i.test(title)) {
        const item = activity(name);
        if (!item.evidence.name) item.evidence.name = page.url;
        if (!item.values.detail_url) addField(item, 'detail_url', page.url, page);
        const session = sessionFor(item, title);
        addField(session, 'name', title, page);
        const description = text(doc.querySelector('[data-hook="description"]'));
        const yearMatch = description.match(/\b(20\d{2})\b/);
        const range = dates(description, yearMatch && yearMatch[1]);
        addField(session, 'start_date', range.start_date, page);
        addField(session, 'end_date', range.end_date, page);
        const timeMatch = description.match(/\b(\d{1,2}(?::\d{2})?\s*(?:am|pm))\s*-\s*(\d{1,2}(?::\d{2})?\s*(?:am|pm))\b/i);
        if (timeMatch) {
          addField(session, 'start_time', timeMatch[1].replace(/\s+/g, '').toUpperCase(), page);
          addField(session, 'end_time', timeMatch[2].replace(/\s+/g, '').toUpperCase(), page);
        }
        const age = description.match(/(?:recommended\s+)?ages?\s+(\d+)\s*-\s*(\d+)/i);
        if (age) {
          addField(item, 'age_min', Number(age[1]), page);
          addField(item, 'age_max', Number(age[2]), page);
        }
        const priceNode = doc.querySelector('[data-hook="details-price"]');
        const priceMatch = text(priceNode).match(/\$\s*(\d+(?:\.\d{1,2})?)/);
        if (priceMatch) addField(session, 'price', {amount_cents: Math.round(Number(priceMatch[1]) * 100), currency: 'USD'}, page);
        const locationNode = doc.querySelector('[data-hook="details-locations"]');
        if (locationNode) addField(session, 'location', {name: text(locationNode)}, page);
        const booked = text(doc.querySelector('[data-hook="no-book-button-message"]'));
        if (/fully booked/i.test(booked)) addField(session, 'registration_status', 'fully booked', page);
        const policy = text(doc.querySelector('[data-hook="cancellation-policy"]'));
        if (policy) addField(session, 'cancellation_policy', policy, page);
        if (policy && /refund/i.test(policy)) addField(session, 'refund_policy', policy, page);
      }
    }

    const pageYear = (allText.match(/\b(20\d{2})\s+SUMMER\s+CAMPS\b/i) || [])[1];
    const headings = Array.from(doc.querySelectorAll ? doc.querySelectorAll('h3') : []);
    for (const heading of headings) {
      const label = text(heading);
      const name = campName(label);
      if (!name || !/^week\s*\d+/i.test(label)) continue;
      const item = activity(name);
      if (!item.evidence.name) item.evidence.name = page.url;
      const session = sessionFor(item, label);
      addField(session, 'name', label, page);
      const block = heading.closest && heading.closest('section');
      const blockText = text(block);
      const range = dates(label, pageYear);
      const fallbackRange = range.start_date ? range : dates(blockText, pageYear);
      addField(session, 'start_date', fallbackRange.start_date, page);
      addField(session, 'end_date', fallbackRange.end_date, page);
      const age = blockText.match(/ages?\s+(\d+)\s*-\s*(\d+)/i);
      if (age) {
        addField(item, 'age_min', Number(age[1]), page);
        addField(item, 'age_max', Number(age[2]), page);
      }
      const timeMatch = blockText.match(/\b(\d{1,2}(?::\d{2})?\s*(?:am|pm))\s*-\s*(\d{1,2}(?::\d{2})?\s*(?:am|pm))\b/i);
      if (timeMatch) {
        addField(session, 'start_time', timeMatch[1].replace(/\s+/g, '').toUpperCase(), page);
        addField(session, 'end_time', timeMatch[2].replace(/\s+/g, '').toUpperCase(), page);
      }
      const priceMatch = blockText.match(/\$\s*(\d+(?:\.\d{1,2})?)\s*\/\s*week/i);
      if (priceMatch && !session.values.price) addField(session, 'price', {amount_cents: Math.round(Number(priceMatch[1]) * 100), currency: 'USD'}, page);
      const link = block && block.querySelector && block.querySelector('a[href*="service-page"]');
      if (link && link.getAttribute) {
        const href = link.getAttribute('href');
        if (href) {
          if (!item.values.detail_url) addField(item, 'detail_url', href, page);
          addField(session, 'registration_url', href, page);
        }
        const state = clean(link.getAttribute('aria-label'));
        if (state === 'Sold Out') addField(session, 'registration_status', 'sold out', page);
      }
    }
  }

  business.activities = business.activities.filter(function(item) {
    item.sessions = item.sessions.filter(function(session) { return session.values.name; });
    return item.values.name && item.sessions.length;
  });
  for (const item of business.activities) {
    if (!item.evidence.name) item.evidence.name = item.sessions[0].evidence.name;
  }
  return {business};
}