(function (global) {
  const TABS = [
    { id: 'overview', label: 'Overview', sectionId: 'overview' },
    { id: 'admissions', label: 'Admissions', sectionId: 'admissions' },
    { id: 'academics', label: 'Academics', sectionId: 'academics' },
    { id: 'business', label: 'Business', sectionId: 'businessProgram' },
    { id: 'career', label: 'Career', sectionId: 'studentOutcomes' },
    { id: 'campus', label: 'Campus', sectionId: 'campusExperience' },
    { id: 'soccer', label: 'Soccer', sectionId: 'soccer' },
    { id: 'consultant', label: 'Consultant Analysis', sectionId: 'consultantAnalysis' }
  ];

  function findSection(profile, sectionId) {
    const sections = Array.isArray(profile && profile.sections) ? profile.sections : [];
    return sections.find(section => {
      const id = section && (section.id || section.anchor);
      return id === sectionId;
    }) || null;
  }

  function createFallbackPanel(profile, tab) {
    const panel = document.createElement('div');
    panel.className = 'ai-preview-panel';

    const note = document.createElement('p');
    note.className = 'ai-preview-fallback';
    note.textContent = `Structured section preview unavailable for ${tab.label}. Displaying raw data.`;
    panel.appendChild(note);

    const pre = document.createElement('pre');
    pre.className = 'ai-preview-raw';

    let raw = null;
    if (tab.id === 'overview') {
      raw = profile.overview;
    } else if (tab.id === 'admissions') {
      raw = profile.admissions;
    } else if (tab.id === 'academics') {
      raw = profile.academics;
    } else if (tab.id === 'career') {
      raw = profile.career;
    } else if (tab.id === 'campus') {
      raw = profile.campus;
    }

    if (!raw) {
      raw = findSection(profile, tab.sectionId) || {};
    }

    pre.textContent = JSON.stringify(raw, null, 2);
    panel.appendChild(pre);
    return panel;
  }

  function renderTabContent(profile, tab) {
    const canReuseSectionRenderer = typeof global.renderSection === 'function' && typeof global.normalizeProfileData === 'function';

    if (!canReuseSectionRenderer) {
      return createFallbackPanel(profile, tab);
    }

    let normalized;
    try {
      normalized = global.normalizeProfileData(profile);
    } catch (_error) {
      return createFallbackPanel(profile, tab);
    }

    const section = findSection(normalized, tab.sectionId);

    if (!section) {
      return createFallbackPanel(normalized, tab);
    }

    const sectionKey = section.id || section.anchor || tab.sectionId;
    let rendered;
    try {
      rendered = global.renderSection(sectionKey, section, normalized);
    } catch (_error) {
      return createFallbackPanel(normalized, tab);
    }

    if (!rendered) {
      return createFallbackPanel(normalized, tab);
    }

    rendered.classList.add('ai-preview-rendered-section');
    rendered.removeAttribute('id');
    rendered.querySelectorAll('[id]').forEach(node => node.removeAttribute('id'));

    const wrapper = document.createElement('div');
    wrapper.className = 'ai-preview-panel';
    wrapper.appendChild(rendered);
    return wrapper;
  }

  function createProfilePreview(profile) {
    const container = document.createElement('section');
    container.className = 'ai-profile-preview';

    const title = document.createElement('h3');
    title.className = 'ai-preview-title';
    title.textContent = 'Preview Generated Profile';
    container.appendChild(title);

    const tabBar = document.createElement('div');
    tabBar.className = 'ai-preview-tabs';
    container.appendChild(tabBar);

    const panelHost = document.createElement('div');
    panelHost.className = 'ai-preview-panel-host';
    container.appendChild(panelHost);

    const tabButtons = [];

    function selectTab(tabId) {
      tabButtons.forEach(button => {
        const isActive = button.dataset.tabId === tabId;
        button.classList.toggle('active', isActive);
        button.setAttribute('aria-selected', String(isActive));
      });

      const tab = TABS.find(item => item.id === tabId) || TABS[0];
      panelHost.innerHTML = '';
      panelHost.appendChild(renderTabContent(profile, tab));
    }

    TABS.forEach((tab, index) => {
      const button = document.createElement('button');
      button.type = 'button';
      button.className = 'ai-preview-tab';
      button.dataset.tabId = tab.id;
      button.textContent = tab.label;
      button.setAttribute('role', 'tab');
      button.setAttribute('aria-selected', String(index === 0));
      button.addEventListener('click', () => selectTab(tab.id));
      tabBar.appendChild(button);
      tabButtons.push(button);
    });

    selectTab(TABS[0].id);
    return container;
  }

  global.CollegePlaybookAIProfilePreview = {
    createProfilePreview
  };
})(window);
