(function (global) {
  const schoolSearchApi = global.CollegePlaybookAISchoolSearch;
  const previewApi = global.CollegePlaybookAIProfilePreview;
  const validationApi = global.CollegePlaybookAIValidationResults;
  const actionsApi = global.CollegePlaybookAIGenerationActions;

  function resolveApiUrl(pathname) {
    const configuredBase = typeof global.COLLEGE_PLAYBOOK_API_BASE === 'string'
      ? global.COLLEGE_PLAYBOOK_API_BASE.trim()
      : '';

    if (configuredBase) {
      return `${configuredBase.replace(/\/$/, '')}${pathname}`;
    }

    if (global.location && global.location.port === '4173') {
      // Use the same hostname the page was loaded from so LAN access works.
      return `http://${global.location.hostname}:3001${pathname}`;
    }

    return pathname;
  }

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

  function createProgressView(label) {
    const wrap = document.createElement('div');
    wrap.className = 'ai-generation-status';
    const spinner = document.createElement('div');
    spinner.className = 'ai-spinner';
    spinner.setAttribute('aria-hidden', 'true');
    wrap.appendChild(spinner);
    wrap.appendChild(createTextElement('p', label || 'Working…', 'ai-generation-status-label'));
    return wrap;
  }

  function createSuccessView(schoolName) {
    const wrap = document.createElement('div');
    wrap.className = 'ai-generation-status';
    const icon = createTextElement('div', '✓', 'ai-generation-success-icon');
    icon.setAttribute('aria-hidden', 'true');
    wrap.appendChild(icon);
    wrap.appendChild(createTextElement('p', `${schoolName || 'School'} added successfully.`, 'ai-generation-status-label'));
    return wrap;
  }

  function createAddSchoolModal(options) {
    const state = {
      query: '',
      searchStatus: 'idle',
      searchResults: [],
      selectedSchool: null,
      isDuplicate: false,
      generatedProfile: null,
      validation: null,
      qaReport: null,
      status: 'idle',
      progressLabel: '',
      errorMessage: '',
      recentSearches: [],
      popularSchools: [],
      controller: null,
      preventClose: false
    };

    const overlay = document.createElement('div');
    overlay.className = 'ai-modal-overlay';
    overlay.hidden = true;
    overlay.setAttribute('role', 'presentation');

    const modal = document.createElement('section');
    modal.className = 'ai-modal add-school-modal';
    modal.setAttribute('role', 'dialog');
    modal.setAttribute('aria-modal', 'true');
    modal.setAttribute('aria-label', 'Add School');
    overlay.appendChild(modal);

    const header = document.createElement('header');
    header.className = 'ai-modal-header';
    const heading = createTextElement('h2', 'Add a School');
    header.appendChild(heading);

    const closeButton = document.createElement('button');
    closeButton.type = 'button';
    closeButton.className = 'ai-modal-close';
    closeButton.setAttribute('aria-label', 'Close add school modal');
    closeButton.textContent = '×';
    closeButton.addEventListener('click', close);
    closeButton.onclick = close;
    header.appendChild(closeButton);
    modal.appendChild(header);

    const body = document.createElement('div');
    body.className = 'ai-modal-body';
    modal.appendChild(body);

    const searchContainer = document.createElement('div');
    searchContainer.className = 'ai-add-school-search-section';
    body.appendChild(searchContainer);

    const generatedContentContainer = document.createElement('div');
    generatedContentContainer.className = 'ai-add-school-generated-content';
    body.appendChild(generatedContentContainer);

    const footer = document.createElement('footer');
    footer.className = 'ai-modal-footer';
    modal.appendChild(footer);

    const statusLine = createTextElement('p', 'Ready to add a school.', 'ai-modal-status-line');
    footer.appendChild(statusLine);

    const searchPanel = schoolSearchApi && typeof schoolSearchApi.createSchoolSearchPanel === 'function'
      ? schoolSearchApi.createSchoolSearchPanel({
        query: state.query,
        searchStatus: state.searchStatus,
        results: state.searchResults,
        selectedSchoolId: state.selectedSchool ? state.selectedSchool.id : '',
        selectedSchool: state.selectedSchool,
        recentSearches: state.recentSearches,
        popularSchools: state.popularSchools,
        libraryIds: new Set(Array.isArray(options.existingSchoolIds) ? options.existingSchoolIds : []),
        onQueryChange: handleQueryChange,
        onRunSearch: runSearch,
        onSelectSchool: selectSchool
      })
      : null;

    if (searchPanel && searchPanel.element) {
      searchContainer.appendChild(searchPanel.element);
    }

    const actionsContainer = document.createElement('div');
    actionsContainer.className = 'ai-modal-actions';
    footer.appendChild(actionsContainer);

    const cancelButton = createTextElement('button', 'Cancel', 'ai-action-button ai-action-ghost');
    cancelButton.type = 'button';
    cancelButton.addEventListener('click', () => close());

    const generateButton = createTextElement('button', 'Generate Profile', 'ai-action-button ai-action-primary');
    generateButton.type = 'button';
    generateButton.disabled = true;
    generateButton.addEventListener('click', () => {
      if (!state.selectedSchool || state.isDuplicate) {
        return;
      }
      generateProfile();
    });

    actionsContainer.appendChild(cancelButton);
    actionsContainer.appendChild(generateButton);

    let searchTimeout = null;

    function updateStatus(message) {
      statusLine.textContent = message;
    }

    function render() {
      generatedContentContainer.innerHTML = '';
      const isWorking = state.status === 'generating' || state.status === 'saving';
      const isQaFailure = state.status === 'error' && Boolean(state.generatedProfile);

      if (isWorking) {
        updateStatus(state.progressLabel || 'Working…');
        generatedContentContainer.appendChild(createProgressView(state.progressLabel));
      } else if (state.status === 'success') {
        updateStatus('Added successfully.');
        generatedContentContainer.appendChild(createSuccessView(state.selectedSchool ? state.selectedSchool.name : ''));
      } else if (isQaFailure) {
        updateStatus(state.errorMessage || 'This profile did not pass quality checks.');
        const previewSection = previewApi.createProfilePreview(state.generatedProfile);
        const validationSection = validationApi.createValidationResults(state.validation);
        const qualitySection = validationApi.createQualityReportPanel(state.qaReport);
        generatedContentContainer.appendChild(previewSection);
        generatedContentContainer.appendChild(validationSection);
        generatedContentContainer.appendChild(qualitySection);
      } else if (state.errorMessage) {
        updateStatus(state.errorMessage);
      } else {
        updateStatus('Ready to add a school.');
      }

      if (searchPanel && typeof searchPanel.update === 'function') {
        const selection = typeof searchPanel.captureInputSelection === 'function'
          ? searchPanel.captureInputSelection()
          : null;

        searchPanel.update({
          query: state.query,
          searchStatus: state.searchStatus,
          results: state.searchResults,
          selectedSchoolId: state.selectedSchool ? state.selectedSchool.id : '',
          selectedSchool: state.selectedSchool,
          recentSearches: state.recentSearches,
          popularSchools: state.popularSchools
        });

        if (typeof searchPanel.restoreInputSelection === 'function') {
          searchPanel.restoreInputSelection(selection);
        }
      }

      generateButton.disabled = !state.selectedSchool || isWorking;
      generateButton.textContent = state.selectedSchool && state.isDuplicate ? 'Open Existing Profile' : 'Generate Profile';
      if (state.selectedSchool && state.isDuplicate) {
        generateButton.onclick = () => {
          if (typeof options.onOpenExisting === 'function' && state.selectedSchool) {
            options.onOpenExisting(state.selectedSchool.id);
            close();
          }
        };
      } else {
        generateButton.onclick = () => generateProfile();
      }

      actionsContainer.innerHTML = '';
      if (isWorking) {
        const workingButton = createTextElement('button', 'Working…', 'ai-action-button ai-action-primary');
        workingButton.type = 'button';
        workingButton.disabled = true;
        actionsContainer.appendChild(workingButton);
      } else if (state.status === 'success') {
        const closeSuccess = createTextElement('button', 'Close', 'ai-action-button ai-action-primary');
        closeSuccess.type = 'button';
        closeSuccess.addEventListener('click', () => close());
        actionsContainer.appendChild(closeSuccess);
      } else if (isQaFailure) {
        const regenerateButton = createTextElement('button', 'Regenerate', 'ai-action-button ai-action-secondary');
        regenerateButton.type = 'button';
        regenerateButton.addEventListener('click', generateProfile);
        const discardButton = createTextElement('button', 'Discard', 'ai-action-button ai-action-ghost');
        discardButton.type = 'button';
        discardButton.addEventListener('click', resetModal);
        actionsContainer.appendChild(discardButton);
        actionsContainer.appendChild(regenerateButton);
      } else {
        actionsContainer.appendChild(cancelButton);
        actionsContainer.appendChild(generateButton);
      }
    }

    function setState(nextState) {
      Object.assign(state, nextState);
      render();
    }

    function handleQueryChange(query) {
      setState({
        query,
        searchStatus: query.trim().length >= 2 ? 'searching' : 'idle',
        selectedSchool: null,
        isDuplicate: false,
        status: 'idle'
      });
      if (searchTimeout) {
        clearTimeout(searchTimeout);
      }

      if (query.trim().length < 2) {
        setState({ searchResults: [], errorMessage: '' });
        return;
      }

      searchTimeout = setTimeout(() => {
        runSearch(query);
      }, 300);
    }

    async function runSearch(query) {
      if (!query || query.trim().length < 2) {
        setState({ searchResults: [], searchStatus: 'idle' });
        return;
      }

      setState({ searchStatus: 'searching', errorMessage: '' });

      try {
        const response = await fetch(resolveApiUrl(`/api/universities/search?q=${encodeURIComponent(query.trim())}`), {
          method: 'GET'
        });
        const payload = await response.json();
        if (!response.ok || !Array.isArray(payload)) {
          throw new Error((payload && payload.error) ? payload.error : 'Search failed.');
        }

        const existingIds = new Set(Array.isArray(options.existingSchoolIds) ? options.existingSchoolIds : []);
        const results = payload.map(school => ({
          ...school,
          exists: existingIds.has(school.id)
        }));

        const recentSearches = [query.trim(), ...state.recentSearches.filter(item => item !== query.trim())].slice(0, 5);
        setState({ searchResults: results, searchStatus: 'idle', recentSearches, errorMessage: '' });
      } catch (error) {
        setState({ searchStatus: 'error', errorMessage: 'Unable to search universities.' });
      }
    }

    function selectSchool(school) {
      const exists = Array.isArray(options.existingSchoolIds) && options.existingSchoolIds.includes(school.id);
      setState({ selectedSchool: school, isDuplicate: exists, status: 'selected', errorMessage: '' });
    }

    async function generateProfile() {
      if (!state.selectedSchool) {
        return;
      }

      const schoolName = state.selectedSchool.name;
      setState({
        status: 'generating',
        progressLabel: `Generating ${schoolName}…`,
        errorMessage: '',
        generatedProfile: null,
        validation: null,
        qaReport: null
      });
      const controller = new AbortController();
      state.controller = controller;
      state.preventClose = true;

      try {
        const response = await fetch(resolveApiUrl('/api/schools/generate'), {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ schoolName, studentContext: { major: 'Business', interest: 'Finance', athlete: true, sport: 'Soccer' } }),
          signal: controller.signal
        });
        const payload = await response.json();

        if (response.status === 409 && payload.status === 'exists') {
          if (typeof options.onOpenExisting === 'function' && payload.schoolId) {
            options.onOpenExisting(payload.schoolId);
            close();
            return;
          }
          throw new Error(payload.message || 'A profile for this school already exists.');
        }

        if (!response.ok || payload.status !== 'complete') {
          throw new Error(payload?.message || 'Generation failed. Please try again.');
        }

        const generatedProfile = payload.profile;
        setState({ progressLabel: 'Checking quality…', generatedProfile });

        const validation = validationApi.validateGeneratedProfile(generatedProfile);
        let qaReport = null;
        if (validation.valid) {
          const qaResponse = await fetch(resolveApiUrl('/api/schools/quality-report'), {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ profile: generatedProfile }),
            signal: controller.signal
          });
          const qaPayload = await qaResponse.json();
          if (qaResponse.ok && qaPayload?.success) {
            qaReport = qaPayload.qaReport;
          }
        }

        const passesQuality = validation.valid && qaReport && !qaReport.rejectSave;

        if (!passesQuality) {
          setState({
            status: 'error',
            validation,
            qaReport,
            errorMessage: 'This profile did not pass quality checks. Regenerate or discard it.',
            preventClose: false
          });
          return;
        }

        setState({ progressLabel: 'Saving…', validation, qaReport });

        const saveResponse = await fetch(resolveApiUrl('/api/schools/save'), {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ profile: generatedProfile, saveMode: 'check' }),
          signal: controller.signal
        });
        const savePayload = await saveResponse.json();

        if (saveResponse.status === 409 || savePayload?.duplicate) {
          if (typeof options.onOpenExisting === 'function' && savePayload?.schoolId) {
            options.onOpenExisting(savePayload.schoolId);
            close();
            return;
          }
          throw new Error(savePayload?.message || 'A profile for this school already exists.');
        }

        if (!saveResponse.ok || savePayload?.success !== true) {
          throw new Error(savePayload?.message || savePayload?.error || 'Unable to save profile.');
        }

        setState({ status: 'success', errorMessage: '', preventClose: false });

        if (typeof options.onSaved === 'function') {
          await options.onSaved(savePayload);
        }

        setTimeout(() => {
          if (state.status === 'success') {
            close();
          }
        }, 1400);
      } catch (error) {
        setState({
          status: 'error',
          errorMessage: error.name === 'AbortError' ? 'Generation timed out. Please try again.' : (error.message || 'Unable to generate profile. Please try again.'),
          preventClose: false
        });
      } finally {
        state.controller = null;
      }
    }

    function resetModal() {
      setState({ generatedProfile: null, validation: null, qaReport: null, status: 'idle', progressLabel: '', errorMessage: '' });
    }

    function open() {
      document.querySelectorAll('.ai-modal-overlay').forEach(el => {
        if (el !== overlay) {
          el.remove();
        }
      });

      overlay.hidden = false;
      overlay.style.display = 'flex';
      document.body.classList.add('ai-modal-open');
      if (searchPanel && typeof searchPanel.focusInput === 'function') {
        searchPanel.focusInput();
      }
      render();
    }

    function close() {
      if (state.preventClose) {
        const shouldClose = window.confirm('A process is still running. Close anyway?');
        if (!shouldClose) {
          return;
        }
      }
      if (state.controller) {
        state.controller.abort();
        state.controller = null;
      }
      overlay.hidden = true;
      overlay.style.display = 'none';
      document.body.classList.remove('ai-modal-open');
      setState({ query: '', searchStatus: 'idle', searchResults: [], selectedSchool: null, isDuplicate: false, generatedProfile: null, validation: null, qaReport: null, status: 'idle', progressLabel: '', errorMessage: '', preventClose: false });
    }

    overlay.addEventListener('click', event => {
      if (event.target === overlay) {
        close();
      }
    });

    document.addEventListener('keydown', event => {
      if (event.key === 'Escape' && !overlay.hidden) {
        close();
      }
    });

    render();

    return {
      element: overlay,
      open,
      close,
      setExistingSchoolIds(ids) {
        if (Array.isArray(ids)) {
          options.existingSchoolIds = ids;
        }
      }
    };
  }

  global.CollegePlaybookAddSchoolModal = {
    createAddSchoolModal
  };
})(window);
