(function (global) {
  function createTextElement(tag, text, className) {
    const element = document.createElement(tag);
    if (className) {
      element.className = className;
    }
    element.textContent = String(text || '');
    return element;
  }

  function createSearchResults(options) {
    const props = {
      results: [],
      selectedSchoolId: '',
      onSelectSchool: null,
      searchStatus: 'idle',
      noResultsText: 'No schools found.',
      ...options
    };

    const container = document.createElement('div');
    container.className = 'ai-school-results';

    function createSchoolRow(school) {
      const row = document.createElement('button');
      row.type = 'button';
      row.className = `ai-school-result-row${props.selectedSchoolId === school.id ? ' selected' : ''}`;
      row.addEventListener('click', () => {
        if (typeof props.onSelectSchool === 'function') {
          props.onSelectSchool(school);
        }
      });

      const primary = document.createElement('div');
      primary.className = 'ai-school-result-primary';
      primary.appendChild(createTextElement('strong', school.name, 'ai-school-result-title'));
      row.appendChild(primary);

      const secondary = document.createElement('div');
      secondary.className = 'ai-school-result-secondary';
      const locationParts = [];
      if (school.city) {
        locationParts.push(school.city);
      }
      if (school.state) {
        locationParts.push(school.state);
      }
      if (!school.city && !school.state && school.country) {
        locationParts.push(school.country);
      }
      const location = locationParts.length > 0 ? locationParts.join(', ') : 'Unknown location';
      secondary.textContent = `${location}${school.schoolType ? ` • ${school.schoolType}` : ''}`;
      row.appendChild(secondary);

      const badge = document.createElement('span');
      badge.className = `ai-school-result-badge ${school.exists ? 'added' : 'available'}`;
      badge.textContent = school.exists ? 'Already Added' : 'Available';
      row.appendChild(badge);

      return row;
    }

    function render() {
      container.innerHTML = '';

      if (props.searchStatus === 'searching') {
        container.appendChild(createTextElement('p', 'Searching schools...', 'ai-school-search-loading'));
        return;
      }

      if (!Array.isArray(props.results) || props.results.length === 0) {
        container.appendChild(createTextElement('p', props.noResultsText, 'ai-school-search-empty'));
        return;
      }

      props.results.forEach(school => {
        container.appendChild(createSchoolRow(school));
      });
    }

    render();

    return {
      element: container,
      update(nextProps) {
        Object.assign(props, nextProps);
        render();
      }
    };
  }

  global.CollegePlaybookAISearchResults = {
    createSearchResults
  };
})(window);
