class JiraSettings {
  constructor() {
    this.form = document.getElementById('settings-form');
    this.notification = document.getElementById('notification');
    this.domainInput = document.getElementById('jira-domain');
    this.emailInput = document.getElementById('jira-email');
    this.tokenInput = document.getElementById('jira-token');

    this.loadSettings();
    this.attachEventListeners();
  }

  attachEventListeners() {
    this.form.addEventListener('submit', (e) => this.handleSubmit(e));
  }

  async loadSettings() {
    const settings = await chrome.storage.local.get(['jiraDomain', 'jiraEmail', 'jiraToken']);
    if (settings.jiraDomain) {
      this.domainInput.value = settings.jiraDomain;
    }
    if (settings.jiraEmail) {
      this.emailInput.value = settings.jiraEmail;
    }
    if (settings.jiraToken) {
      this.tokenInput.value = settings.jiraToken;
    }
  }

  async handleSubmit(event) {
    event.preventDefault();
    
    const domain = this.domainInput.value.trim();
    const email = this.emailInput.value.trim();
    const token = this.tokenInput.value.trim();

    try {
      // Validate the credentials
      const isValid = await this.validateJiraCredentials(domain, email, token);
      
      if (isValid) {
        // Save settings
        await chrome.storage.local.set({
          jiraDomain: domain,
          jiraEmail: email,
          jiraToken: token
        });

        this.showNotification('Settings saved successfully!', 'success');
      } else {
        this.showNotification('Invalid Jira credentials. Please check and try again.', 'error');
      }
    } catch (error) {
      console.error('Error saving settings:', error);
      this.showNotification('Error saving settings. Please try again.', 'error');
    }
  }

  async validateJiraCredentials(domain, email, token) {
    try {
      const response = await fetch(`https://${domain}/rest/api/3/myself`, {
        headers: {
          'Authorization': `Basic ${btoa(`${email}:${token}`)}`,
          'Accept': 'application/json'
        }
      });

      return response.ok;
    } catch (error) {
      console.error('Error validating Jira credentials:', error);
      return false;
    }
  }

  showNotification(message, type) {
    this.notification.textContent = message;
    this.notification.className = `notification ${type}`;
    this.notification.style.display = 'block';

    setTimeout(() => {
      this.notification.style.display = 'none';
    }, 5000);
  }
}

// Initialize settings
new JiraSettings();