document.addEventListener('DOMContentLoaded', () => {
  const onboardingFlow = document.getElementById('onboarding-flow');
  const confirmationFlow = document.getElementById('confirmation-flow');
  const onboardingIssuesContainer = document.getElementById('onboarding-issues-container');
  let onboardingIssueButtons;
  const saveOnboardingButton = document.getElementById('save-onboarding-issues');
  const confirmationIssuesList = document.getElementById('confirmation-issues-list');
  const confirmButton = document.getElementById('confirm-issues');
  const reselectButton = document.getElementById('reselect-issues');
  const statusParagraph = confirmationFlow.querySelector('.flow-header p:nth-of-type(1)');

  const ISSUES = [
    { value: "gun-control", text: "Gun Control" },
    { value: "gun-rights", text: "Gun Rights" },
    { value: "privacy", text: "Electronic Privacy" },
    { value: "immigration", text: "Immigration" },
    { value: "climate-change", text: "Climate Change" },
    { value: "healthcare", text: "Healthcare" },
    { value: "racial-justice", text: "Racial Justice" },
    { value: "lgbtq-rights", text: "LGBTQ+ Rights" },
    { value: "economic-inequality", text: "Economic Inequality" },
    { value: "reproductive-rights", text: "Reproductive Rights" },
    { value: "education-reform", text: "Education Reform" },
    { value: "criminal-justice", text: "Criminal Justice" },
    { value: "voting-rights", text: "Voting Rights" },
    { value: "campaign-finance", text: "Campaign Finance" },
    { value: "foreign-policy", text: "Foreign Policy" },
    { value: "national-security", text: "National Security" },
    { value: "free-speech", text: "Free Speech" },
    { value: "net-neutrality", text: "Net Neutrality" },
    { value: "labor-rights", text: "Labor Rights" },
    { value: "affordable-housing", text: "Affordable Housing" },
    { value: "environmental-protection", text: "Environmental Protection" },
    { value: "space-exploration", text: "Space Exploration" },
    { value: "drug-policy-reform", text: "Drug Policy Reform" },
    { value: "veterans-affairs", text: "Veterans' Affairs" },
    { value: "senior-citizen-rights", text: "Senior Citizen Rights" },
  ];

  const generateIssueButtons = () => {
    ISSUES.forEach(issue => {
      const button = document.createElement('button');
      button.className = 'issue-button';
      button.setAttribute('data-value', issue.value);
      button.setAttribute('aria-pressed', 'false');
      button.textContent = issue.text;
      onboardingIssuesContainer.appendChild(button);
    });
    onboardingIssueButtons = onboardingIssuesContainer.querySelectorAll('.issue-button');
  };

  generateIssueButtons();

  const getStorageApi = () => {
    if (typeof browser !== 'undefined' && browser.storage) {
      return browser.storage.local;
    }
    else if (typeof chrome !== 'undefined' && chrome.storage) {
      return chrome.storage.sync;
    }
    return null;
  };
  const storageApi = getStorageApi();

  const showFlow = (flow) => {
    onboardingFlow.style.display = 'none';
    confirmationFlow.style.display = 'none';
    flow.style.display = 'block';
  };

  const populateConfirmationList = (issues) => {
    confirmationIssuesList.innerHTML = '';
    if (issues && issues.length > 0) {
      issues.forEach(issueValue => {
        const issueObj = ISSUES.find(issue => issue.value === issueValue);
        const listItem = document.createElement('li');
        listItem.textContent = issueObj.text;
        confirmationIssuesList.appendChild(listItem);
      });
    } else {
      const listItem = document.createElement('li');
      listItem.textContent = 'No issues selected yet.';
      confirmationIssuesList.appendChild(listItem);
    }
  };

  const updateStatusDisplay = (isActive) => {
    if (statusParagraph) {
      statusParagraph.textContent = `Status: ${isActive ? 'Active' : 'Inactive'}`;
      statusParagraph.style.color = isActive ? '#10B981' : '#EF4444';
      statusParagraph.style.fontWeight = 'bold';
    }
    confirmButton.textContent = isActive ? 'Deactivate Praxis' : 'Activate Praxis';
    confirmButton.style.backgroundColor = isActive ? '#EF4444' : '#10B981';
  };

  onboardingIssuesContainer.addEventListener('click', (event) => {
    if (event.target.classList.contains('issue-button')) {
      const button = event.target;
      button.classList.toggle('selected');
      const isSelected = button.classList.contains('selected');
      button.setAttribute('aria-pressed', isSelected);
    }
  });

  saveOnboardingButton.addEventListener('click', () => {
    const selectedIssues = Array.from(onboardingIssuesContainer.querySelectorAll('.issue-button.selected'))
                                .map(button => button.dataset.value);

    if (storageApi) {
      storageApi.set({
        selected_issues: selectedIssues,
        onboarding_complete: true,
        praxis_active: true
      })
      .then(() => {
        populateConfirmationList(selectedIssues);
        updateStatusDisplay(true);
        showFlow(confirmationFlow);
      })
      .catch(error => {
        alert('Error saving data. Please try again. See console for details.');
      });
    } else {
      alert('Your browser does not support the necessary storage features.');
    }
  });

  confirmButton.addEventListener('click', () => {
    if (storageApi) {
      storageApi.get('praxis_active')
        .then(data => {
          const newStatus = typeof data.praxis_active === 'boolean' ? !data.praxis_active : false;
          storageApi.set({ praxis_active: newStatus })
            .then(() => {
              updateStatusDisplay(newStatus);
            })
            .catch(error => {});
        })
        .catch(error => {});
    }
  });

  reselectButton.addEventListener('click', () => {
    onboardingIssueButtons.forEach(button => {
      button.classList.remove('selected');
      button.setAttribute('aria-pressed', false);
    });

    if (storageApi) {
      storageApi.get('selected_issues')
        .then(data => {
          if (data && data.selected_issues) {
            data.selected_issues.forEach(savedIssue => {
              const button = onboardingIssuesContainer.querySelector(`.issue-button[data-value="${savedIssue}"]`);
              if (button) {
                button.classList.add('selected');
                button.setAttribute('aria-pressed', true);
              }
            });
          }
        })
        .catch(error => {});
    }

    showFlow(onboardingFlow);
  });

  if (storageApi) {
    storageApi.get(['selected_issues', 'onboarding_complete', 'praxis_active'])
      .then(data => {
        const isActive = typeof data.praxis_active === 'boolean' ? data.praxis_active : true;
        if (data.onboarding_complete) {
          populateConfirmationList(data.selected_issues || []);
          updateStatusDisplay(isActive);
          showFlow(confirmationFlow);
        } else {
          if (data.selected_issues) {
            data.selected_issues.forEach(savedIssue => {
              const button = onboardingIssuesContainer.querySelector(`.issue-button[data-value="${savedIssue}"]`);
              if (button) {
                button.classList.add('selected');
                button.setAttribute('aria-pressed', true);
              }
            });
          }
          showFlow(onboardingFlow);
        }
      })
      .catch(error => {
        updateStatusDisplay(true);
        showFlow(onboardingFlow);
      });
  } else {
    updateStatusDisplay(true);
    showFlow(onboardingFlow);
  }
});