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

  function createSchoolSearchPanel(options) {
    const props = {
      query: '',
      searchStatus: 'idle',
      results: [],
      recentSearches: [],
      popularSchools: [],
      selectedSchoolId: '',
      libraryIds: new Set(),
      searchHelp: 'Type at least 2 characters to start your search.',
      ...options
    };

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

    const searchWrapper = document.createElement('div');
    searchWrapper.className = 'ai-school-search-input-shell';

    const label = createTextElement('label', 'Search by school name, abbreviation, or location', 'ai-school-search-label');
    label.htmlFor = 'addSchoolSearchInput';
    searchWrapper.appendChild(label);

    const searchInput = document.createElement('input');
    searchInput.id = 'addSchoolSearchInput';
    searchInput.className = 'ai-school-search-input';
    searchInput.type = 'search';
    searchInput.placeholder = 'Enter school name or abbreviation (e.g. NYU, UVA, Maryland)';
    searchInput.value = props.query;
    searchInput.autocomplete = 'off';
    searchInput.addEventListener('input', event => {
      if (typeof props.onQueryChange === 'function') {
        props.onQueryChange(event.target.value || '');
      }
    });
    searchWrapper.appendChild(searchInput);

    const helper = createTextElement('p', props.searchHelp, 'ai-school-search-helper');
    searchWrapper.appendChild(helper);
    container.appendChild(searchWrapper);

    const quickPanels = document.createElement('div');
    quickPanels.className = 'ai-school-search-quick-panels';

    const recentSection = document.createElement('div');
    recentSection.className = 'ai-school-search-panel-block';
    recentSection.appendChild(createTextElement('h4', 'Recent Searches', 'ai-school-search-panel-title'));
    const recentList = document.createElement('div');
    recentList.className = 'ai-school-search-chip-group';
    recentSection.appendChild(recentList);
    quickPanels.appendChild(recentSection);

    const popularSection = document.createElement('div');
    popularSection.className = 'ai-school-search-panel-block';
    popularSection.appendChild(createTextElement('h4', 'Popular Schools', 'ai-school-search-panel-title'));
    const popularList = document.createElement('div');
    popularList.className = 'ai-school-search-chip-group';
    popularSection.appendChild(popularList);
    quickPanels.appendChild(popularSection);

    container.appendChild(quickPanels);

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

    const selectedDetails = document.createElement('div');
    selectedDetails.className = 'ai-school-selection-details';
    container.appendChild(selectedDetails);

    function createChip(label, onClick) {
      const chip = document.createElement('button');
      chip.type = 'button';
      chip.className = 'ai-school-chip';
      chip.textContent = label;
      chip.addEventListener('click', () => {
        if (typeof onClick === 'function') {
          onClick(label);
        }
      });
      return chip;
    }

    function createSchoolCard(school, selectedId) {
      const isActive = selectedId === school.id;
      const card = document.createElement('button');
      card.type = 'button';
      card.className = `ai-school-card${isActive ? ' selected' : ''} ${school.exists ? 'ai-school-card-instant' : 'ai-school-card-generate'}`;
      card.setAttribute('aria-pressed', String(isActive));

      const titleRow = document.createElement('div');
      titleRow.className = 'ai-school-card-title-row';
      const titleWrap = document.createElement('div');
      titleWrap.className = 'ai-school-card-title-wrap';
      const icon = createTextElement('span', school.exists ? '⚡' : '✨', 'ai-school-card-icon');
      icon.setAttribute('aria-hidden', 'true');
      titleWrap.appendChild(icon);
      titleWrap.appendChild(createTextElement('strong', school.name, 'ai-school-card-title'));
      titleRow.appendChild(titleWrap);
      const status = createTextElement('span', school.exists ? 'Instant' : 'Generate', `ai-school-card-pill ${school.exists ? 'ai-pill-added' : 'ai-pill-generate'}`);
      titleRow.appendChild(status);
      card.appendChild(titleRow);

      const meta = document.createElement('div');
      meta.className = 'ai-school-card-meta';
      meta.textContent = school.location || (school.country || 'Unknown location');
      card.appendChild(meta);

      const hint = createTextElement(
        'p',
        school.exists ? 'Already in your library' : 'Takes about 20-30s to generate',
        `ai-school-card-hint ${school.exists ? 'ai-school-card-hint-instant' : 'ai-school-card-hint-generate'}`
      );
      card.appendChild(hint);

      const details = document.createElement('div');
      details.className = 'ai-school-card-details';
      details.textContent = school.website || school.domain || '';
      card.appendChild(details);

      const footer = document.createElement('div');
      footer.className = 'ai-school-card-footer';
      footer.appendChild(createTextElement('span', `${school.tier ? `${school.tier} •` : ''} ${school.abbreviations ? school.abbreviations.join(', ') : ''}`, 'ai-school-card-subtitle'));
      card.appendChild(footer);

      card.addEventListener('click', () => {
        if (typeof props.onSelectSchool === 'function') {
          props.onSelectSchool(school);
        }
      });

      return card;
    }

    function render() {
      helper.textContent = props.searchHelp;

      const isFocused = document.activeElement === searchInput;
      const selectionStart = searchInput.selectionStart;
      const selectionEnd = searchInput.selectionEnd;

      if (searchInput.value !== props.query) {
        searchInput.value = props.query;
        if (isFocused) {
          searchInput.focus();
          try {
            searchInput.setSelectionRange(selectionStart, selectionEnd);
          } catch (_error) {
            // ignore invalid selection range
          }
        }
      }

      // Hide quick panels while search is active so layout doesn't shift
      const isSearchActive = props.searchStatus === 'searching' || props.results.length > 0 || props.query.trim().length >= 2;
      quickPanels.hidden = isSearchActive;

      recentList.innerHTML = '';
      if (Array.isArray(props.recentSearches) && props.recentSearches.length > 0) {
        props.recentSearches.forEach(search => {
          recentList.appendChild(createChip(search, query => {
            if (typeof props.onQueryChange === 'function') {
              props.onQueryChange(query);
            }
            if (typeof props.onRunSearch === 'function') {
              props.onRunSearch(query);
            }
          }));
        });
      } else {
        recentList.appendChild(createTextElement('p', 'No recent searches yet.', 'ai-school-search-empty'));
      }

      popularList.innerHTML = '';
      if (Array.isArray(props.popularSchools) && props.popularSchools.length > 0) {
        props.popularSchools.forEach(school => {
          popularList.appendChild(createChip(school.name, () => {
            if (typeof props.onSelectSchool === 'function') {
              props.onSelectSchool(school);
            }
          }));
        });
      } else {
        popularList.appendChild(createTextElement('p', 'No popular schools available.', 'ai-school-search-empty'));
      }

      resultsHost.innerHTML = '';
      if (props.searchStatus === 'searching') {
        const loading = createTextElement('p', 'Searching universities...', 'ai-school-search-loading');
        resultsHost.appendChild(loading);
      } else if (Array.isArray(props.results) && props.results.length > 0) {
        props.results.forEach(school => {
          resultsHost.appendChild(createSchoolCard(school, props.selectedSchoolId));
        });
      } else if (props.query.trim().length >= 2) {
        resultsHost.appendChild(createTextElement('p', 'No universities found.', 'ai-school-search-empty'));
      } else {
        resultsHost.appendChild(createTextElement('p', 'Type at least 2 characters to search.', 'ai-school-search-empty'));
      }

      selectedDetails.innerHTML = '';
    }

    render();

    return {
      element: container,
      focusInput() {
        searchInput.focus();
      },
      captureInputSelection() {
        return {
          focused: document.activeElement === searchInput,
          start: searchInput.selectionStart,
          end: searchInput.selectionEnd
        };
      },
      restoreInputSelection(selection) {
        if (selection && selection.focused) {
          searchInput.focus();
          if (typeof selection.start === 'number' && typeof selection.end === 'number') {
            try {
              searchInput.setSelectionRange(selection.start, selection.end);
            } catch (_error) {
              // ignore invalid selection range
            }
          }
        }
      },
      update(nextProps) {
        Object.assign(props, nextProps);
        render();
      }
    };
  }

  global.CollegePlaybookAISchoolSearch = {
    createSchoolSearchPanel
  };
})(window);
