const helpdeskAgentJsVars = window['generatify_helpdesk_agent_js_vars'] || {};

function getContrastTextColor(backgroundColor) {
  const temp = document.createElement('div');
  temp.style.backgroundColor = backgroundColor;
  temp.style.display = 'none';
  document.body.appendChild(temp);

  const computedColor = window.getComputedStyle(temp).backgroundColor;
  document.body.removeChild(temp);

  const [r, g, b] = computedColor.match(/\d+/g).map(Number);
  const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;

  return luminance > 0.5 ? '#000000' : '#ffffff';
}

class GeneratifyHelpdeskAgent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.styles = new Set();
    this.state = 'closed';
    this.position = helpdeskAgentJsVars.aiHelpdeskAgentSettings.position || 'bottom-right';
    this.primaryColor = helpdeskAgentJsVars.aiHelpdeskAgentSettings.primaryColor || '#000000';
    this.backgroundColor = getContrastTextColor(this.primaryColor);
    this.textColor = getContrastTextColor(this.backgroundColor);
    this.cover = helpdeskAgentJsVars.aiHelpdeskAgentSettings.cover || '';
    this.icon = helpdeskAgentJsVars.aiHelpdeskAgentSettings.icon || '';
    this.homeTitle = helpdeskAgentJsVars.aiHelpdeskAgentSettings.homeTitle || '';
    this.homeTagline = helpdeskAgentJsVars.aiHelpdeskAgentSettings.homeTagline || '';
    this.homeButtonText = helpdeskAgentJsVars.aiHelpdeskAgentSettings.homeButtonText || 'Send us a message';

    this.homePopularTopics = [];
    

    this.messageMode = 'contact';
    

    this.helpArticles = helpdeskAgentJsVars.aiHelpdeskAgentSettings.helpArticles || [];
  }

  async connectedCallback() {
    this.render();
    this.handleStateChange(this.state);
    this.handleToggle();
    this.handleTabs();
    this.handleContactForm();
    
  }

  static show() {
    let GeneratifyHelpdeskAgent = document.querySelector('generatify-helpdesk-agent');

    if (!GeneratifyHelpdeskAgent) {
      GeneratifyHelpdeskAgent = document.createElement('generatify-helpdesk-agent');
      document.body.appendChild(GeneratifyHelpdeskAgent);
    }

    return GeneratifyHelpdeskAgent;
  }

  injectStyles(css) {
    this.styles.add(css);
  }

  handleStateChange(state) {
    const helpdeskAgentContainer = this.shadowRoot.querySelector('.helpdesk-agent');

    switch (state) {
      case 'opened':
        helpdeskAgentContainer.setAttribute('data-open', '');
        break;
      case 'closed':
        helpdeskAgentContainer.removeAttribute('data-open');
        break;
      default:
    }
  }

  handleToggle() {
    const button = this.shadowRoot.querySelector('.helpdesk-agent-button');
    const dropdown = this.shadowRoot.querySelector('.helpdesk-agent-dropdown');

    const set = (s) => {
      if (this.state !== s) {
        this.state = s;
        this.handleStateChange(s);
      }
    };

    button.addEventListener('click', () => set(this.state === 'closed' ? 'opened' : 'closed'));

    let mouseDownInside = false;

    document.addEventListener('mousedown', (e) => {
      const path = e.composedPath?.() || [];
      mouseDownInside = path.includes(this) || path.includes(button) || path.includes(dropdown);
    });

    document.addEventListener('click', (e) => {
      const path = e.composedPath?.() || [];
      const clickInside = path.includes(this) || path.includes(button) || path.includes(dropdown);
      const hitClose = path.some((n) => n && n.nodeType === 1 && n.hasAttribute && n.hasAttribute('data-close'));

      if (this.state === 'opened' && ((!mouseDownInside && !clickInside) || hitClose)) set('closed');
    });
  }

  handleTabs() {
    const toggles = this.shadowRoot.querySelectorAll('button[data-tab]');
    const panels = this.shadowRoot.querySelectorAll('.helpdesk-agent-tab');

    const clearActive = () => {
      toggles.forEach((toggle) => toggle.removeAttribute('data-active'));
      panels.forEach((panel) => panel.removeAttribute('data-active'));
    };

    const activate = (toggle) => {
      if (!toggle) return;
      const key = toggle.getAttribute('data-tab');
      if (!key) return;
      const panel = Array.from(panels).find((p) => p.getAttribute('data-tab') === key);
      if (!panel) return;
      clearActive();

      // Add data-active to all toggles that match the key
      toggles.forEach((t) => {
        if (t.getAttribute('data-tab') === key) {
          t.setAttribute('data-active', 'true');
        }
      });

      panel.setAttribute('data-active', 'true');
    };

    // Find initial active toggle
    let initial = Array.from(toggles).find((toggle) => toggle.hasAttribute('data-active'));
    if (!initial) {
      const activePanel = Array.from(panels).find((p) => p.hasAttribute('data-active'));
      if (activePanel) {
        const key = activePanel.getAttribute('data-tab');
        initial = Array.from(toggles).find((toggle) => toggle.getAttribute('data-tab') === key);
      }
    }
    if (!initial && toggles.length > 0) {
      initial = toggles[0];
    }

    if (initial) {
      activate(initial);
    }

    toggles.forEach((toggle) => {
      toggle.addEventListener('click', function (e) {
        e.preventDefault();
        activate(this);
      });
    });
  }

  handleContactForm() {
    const form = this.shadowRoot.querySelector('.helpdesk-agent-tab-message_content_form');
    if (!form) return;

    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const formData = new FormData(form);
      const name = formData.get('personName');
      const email = formData.get('personEmail');
      const message = formData.get('personMessage');
      const page = window.location.origin + window.location.pathname;

      if (!name || !email || !message) return;

      form.setAttribute('data-state', 'submitting');

      try {
        const response = await fetch(helpdeskAgentJsVars.restUrl + 'generatify/v1/helpdesk-agent/contact', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': helpdeskAgentJsVars.restNonce,
          },
          body: JSON.stringify({
            name,
            email,
            message,
            page,
          }),
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        if (data.status === 'success') {
          form.reset();
          form.setAttribute('data-state', 'success');
        } else {
          form.setAttribute('data-state', 'fail');
          console.error('Error submitting contact form:', data.message);
        }
      } catch (error) {
        form.setAttribute('data-state', 'fail');
        console.error('Error submitting contact form:', error);
      }
    });
  }

  

  /*! Render Functions */

  renderHomeTab() {
    this.injectStyles(`
      .helpdesk-agent-tab-home {
        position: relative;
        display: flex;
        flex-direction: column;
        height: 100%;
      }

      .helpdesk-agent-tab-home_close {
        position: absolute;
        display: flex;
        justify-content: center; 
        align-items: center; 
        border-radius: 9999px;
        color: ${this.textColor}7a;
        z-index: 10;
        top: 10px;
        right: 10px;
        width: 32px;
        height: 32px;
        border: none;
        outline: none;
        cursor: pointer;
        background-color: transparent;
      }

      .helpdesk-agent-tab-home_close:hover {
        background-color: ${this.backgroundColor};
      }

      .helpdesk-agent-tab-home_close svg {
        flex-shrink: 0;
        width: 16px;
        height: 16px;
      }

      .helpdesk-agent-tab-home_cover {
        width: 100%;
        height: 120px;
        object-fit: cover;
        background-color: ${this.primaryColor}1a;
      }

      .helpdesk-agent-tab-home_icon {
        position: relative; 
        display: flex;
        justify-content: center; 
        align-items: center;
        border-radius: 9999px;
        overflow: hidden;
        object-fit: cover;
        width: 56px;
        height: 56px;
        font-weight: 600;
        font-size: 24px;
        line-height: 1;
        text-align: center;
        background-color: ${this.backgroundColor};
        color: ${this.textColor};
        text-transform: uppercase;
        margin-top: -30px;
        margin-left: 15px;
      }

      .helpdesk-agent-tab-home_content {
        display: flex;
        flex-direction: column;
        gap: 16px;
        padding: 20px;
        overflow-y: auto;
        flex: 1;
      }

      .helpdesk-agent-tab-home_title {
        font-weight: 600;
        font-size: 20px;
        line-height: 28px;
        color: ${this.textColor};
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
      }

      .helpdesk-agent-tab-home_tagline {
        font-size: 14px;
        line-height: 20px;
        color: ${this.textColor}e0;
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
      }

      .helpdesk-agent-tab-home_button {
        display: inline-flex; 
        padding: 10px 12px;
        column-gap: 6px; 
        justify-content: center; 
        align-items: center; 
        border-radius: 8px; 
        border: 1px solid transparent; 
        outline: none;
        cursor: pointer;
        width: 100%; 
        font-size: 14px;
        line-height: 20px; 
        font-weight: 500;
        color: ${this.backgroundColor}; 
        background-color: ${this.primaryColor}; 
        -webkit-transition: all 0.1s ease-out;
        -o-transition: all 0.1s ease-out;
        transition: all 0.1s ease-out;
      }

      .helpdesk-agent-tab-home_button:hover {
        opacity: 0.95;
      }

      .helpdesk-agent-tab-home_popular-topics_title {
        margin-bottom: 8px;
        font-size: 12px;
        line-height: 16px;
        color: ${this.textColor}bd;
      }

      .helpdesk-agent-tab-home_popular-topics_list {
        list-style: none;
        margin: 0;
        padding: 0;
      }

      .helpdesk-agent-tab-home_popular-topics_list > :not(:last-child){
        margin-block-start: -1px;
        margin-block-end: -1px;
      }

      .helpdesk-agent-tab-home_popular-topic_item {
        overflow: hidden;
        border: 1px solid ${this.textColor}1f;
      }

      .helpdesk-agent-tab-home_popular-topic_item:first-child {
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
      }

      .helpdesk-agent-tab-home_popular-topic_item:last-child {
        border-bottom-left-radius: 8px;
        border-bottom-right-radius: 8px;
      }

      .helpdesk-agent-tab-home_popular-topic_link {
        display: flex; 
        padding: 12px 16px;
        column-gap: 12px; 
        background-color: ${this.backgroundColor};
        text-decoration: none;
        outline: none;
        cursor: pointer;
        -webkit-transition: all 0.1s ease-out;
        -o-transition: all 0.1s ease-out;
        transition: all 0.1s ease-out;
      }

      .helpdesk-agent-tab-home_popular-topic_link:hover {
        background-color: ${this.textColor}0a; 
      }

      .helpdesk-agent-tab-home_popular-topic_title {
        font-size: 14px;
        line-height: 20px;
        font-weight: 500;
        color: ${this.textColor}e0;
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
      }

      .helpdesk-agent-tab-home_popular-topic_description {
        font-size: 12px;
        line-height: 16px;
        color: ${this.textColor}bd;
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
      }

      .helpdesk-agent-tab-home_popular-topic_icon {
        align-self: center;
        margin-inline-start: auto;
      }

      .helpdesk-agent-tab-home_popular-topic_icon svg {
        width: 14px;
        height: 14px;
        flex-shrink: 0;
        color: ${this.primaryColor};
      }
    `);

    return `
      <div class="helpdesk-agent-tab-home">
        <button class="helpdesk-agent-tab-home_close" aria-label="${wp.i18n.__('Close Helpdesk', 'generatify')}" data-close>
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>
        </button>
        <div class="helpdesk-agent-tab-home_header">
          ${this.cover ? `<img class="helpdesk-agent-tab-home_cover" src="${this.cover}" alt="image" />` : '<div class="helpdesk-agent-tab-home_cover"></div>'}
          ${this.icon ? `<img class="helpdesk-agent-tab-home_icon" src="${this.icon}" alt="image" />` : `<div class="helpdesk-agent-tab-home_icon">${window.location.hostname.charAt(0)}</div>`}
        </div>
        <div class="helpdesk-agent-tab-home_content">
          <div class="helpdesk-agent-tab-home_texts">
            ${this.homeTitle ? `<div class="helpdesk-agent-tab-home_title">${this.homeTitle}</div>` : ''}
            ${this.homeTagline ? `<div class="helpdesk-agent-tab-home_tagline">${this.homeTagline}</div>` : ''}
          </div>
          ${this.homeButtonText ? `<button type="button" class="helpdesk-agent-tab-home_button" data-tab="message">${this.homeButtonText}</button>` : ''}
          ${
            this.homePopularTopics.length && this.homePopularTopics.some((topic) => topic.title && topic.description && topic.url)
              ? `
            <div class="helpdesk-agent-tab-home_popular-topics">
              <div class="helpdesk-agent-tab-home_popular-topics_title">
                ${wp.i18n.__('Popular Topics', 'generatify')}
              </div>
              <ul class="helpdesk-agent-tab-home_popular-topics_list">
                ${this.homePopularTopics
                  .map(
                    (topic) => `
                  <li class="helpdesk-agent-tab-home_popular-topic_item">
                    <a class="helpdesk-agent-tab-home_popular-topic_link" href="${topic.url}" target="_blank">
                      <div>
                        <div class="helpdesk-agent-tab-home_popular-topic_title">
                          ${topic.title}
                        </div>
                        <div class="helpdesk-agent-tab-home_popular-topic_description">
                          ${topic.description}
                        </div>
                      </div>
                      <div class="helpdesk-agent-tab-home_popular-topic_icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                          <path d="M5 12h14"></path>
                          <path d="m12 5 7 7-7 7"></path>
                        </svg>
                      </div>
                    </a>
                  </li>
                `
                  )
                  .join('')}
              </ul>
            </div>
          `
              : ''
          }
        </div>
      </div>
    `;
  }

  renderMessageTab() {
    

    this.injectStyles(`
      .helpdesk-agent-tab-message {
        position: relative;
        display: flex;
        flex-direction: column;
        height: 100%;
      }

      .helpdesk-agent-tab-message_close {
        position: absolute;
        display: flex;
        justify-content: center; 
        align-items: center; 
        border-radius: 9999px;
        color: ${this.textColor}7a;
        z-index: 10;
        top: 10px;
        right: 10px;
        width: 32px;
        height: 32px;
        border: none;
        outline: none;
        cursor: pointer;
        background-color: transparent;
      }

      .helpdesk-agent-tab-message_close:hover {
        background-color: ${this.backgroundColor};
      }

      .helpdesk-agent-tab-message_close svg {
        flex-shrink: 0;
        width: 16px;
        height: 16px;
      }

      .helpdesk-agent-tab-message_cover {
        width: 100%;
        height: 120px;
        object-fit: cover;
        background-color: ${this.primaryColor}1a;
      }

      .helpdesk-agent-tab-message_icon {
        position: relative; 
        display: flex;
        justify-content: center; 
        align-items: center;
        border-radius: 9999px;
        overflow: hidden;
        object-fit: cover;
        width: 56px;
        height: 56px;
        font-weight: 600;
        font-size: 24px;
        line-height: 1;
        text-align: center;
        background-color: ${this.backgroundColor};
        color: ${this.textColor};
        text-transform: uppercase;
        margin-top: -30px;
        margin-left: 15px;
      }

      .helpdesk-agent-tab-message_content {
        flex: 1;
        padding: 20px;
        overflow-y: auto;
      }

      .helpdesk-agent-tab-message_content_form {
        display: flex;
        flex-direction: column;
        gap: 18px;
        padding: 0;
        width: 100%;
      }

      .helpdesk-agent-tab-message_content_form-group {
        display: flex;
        flex-direction: column;
        gap: 4px;
        width: 100%;
      }

      .helpdesk-agent-tab-message_content_form-label {
        display: inline-flex;
        align-items: center;
        font-size: 14px;
        line-height: 20px;
        font-weight: 500;
        color: ${this.textColor}e0;
      }

      .helpdesk-agent-tab-message_content_form-field,
      .helpdesk-agent-tab-message_content_form-textarea {
        display: block;
        width: auto;
        padding: 8px 12px;
        font-size: 14px;
        line-height: 20px;
        color: ${this.textColor}e0;
        background-color: ${this.backgroundColor};
        border: 1px solid ${this.textColor}1f;
        border-radius: 8px;
        outline: none;
        box-sizing: border-box;
        flex: 1;
      }

      .helpdesk-agent-tab-message_content_form-field:focus,
      .helpdesk-agent-tab-message_content_form-textarea:focus {
        border-color: ${this.primaryColor};
        outline: 2px solid transparent;
        box-shadow: 0 0 0 1px ${this.primaryColor};
      }

      .helpdesk-agent-tab-message_content_form-field::placeholder,
      .helpdesk-agent-tab-message_content_form-textarea::placeholder {
        color: ${this.textColor}7a;
      }

      .helpdesk-agent-tab-message_content_form-textarea {
        field-sizing: content;
        overflow: hidden;
        resize: none;
        min-height: 70px;
      }

      .helpdesk-agent-tab-message_content_form-button {
        display: inline-flex; 
        padding: 10px 12px;
        column-gap: 6px; 
        justify-content: center; 
        align-items: center; 
        border-radius: 8px; 
        border: 1px solid transparent; 
        outline: none;
        cursor: pointer;
        width: 100%; 
        font-size: 14px;
        line-height: 20px; 
        font-weight: 500;
        color: ${this.backgroundColor}; 
        background-color: ${this.primaryColor}; 
        -webkit-transition: all 0.1s ease-out;
        -o-transition: all 0.1s ease-out;
        transition: all 0.1s ease-out;
      }

      .helpdesk-agent-tab-message_content_form-button:hover {
        opacity: 0.95;
      }

      .helpdesk-agent-tab-message_content_form-button_spinner {
        display: none;
        width: 14px;
        height: 14px;
        border: 3px solid ${this.backgroundColor};
        border-top-color: transparent;
        border-radius: 9999px;
        animation: spin 1s linear infinite;
      }

      .helpdesk-agent-tab-message_content_form[data-state="submitting"] .helpdesk-agent-tab-message_content_form-button {
        pointer-events: none;
        opacity: 0.5;
      }

      .helpdesk-agent-tab-message_content_form[data-state="submitting"] .helpdesk-agent-tab-message_content_form-button_text {
        display: none;
      }

      .helpdesk-agent-tab-message_content_form[data-state="submitting"] .helpdesk-agent-tab-message_content_form-button_spinner {
        display: inline-block;
      }

      .helpdesk-agent-tab-message_content_form-results {
        display: none;
        position: absolute;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        inset: 0;
        background-color: ${this.backgroundColor};
      }

      .helpdesk-agent-tab-message_content_form[data-state="success"] .helpdesk-agent-tab-message_content_form-results,
      .helpdesk-agent-tab-message_content_form[data-state="fail"] .helpdesk-agent-tab-message_content_form-results {
        display: flex;
      }

      .helpdesk-agent-tab-message_content_form-result {
        display: none;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
        padding: 20px;
      }

      .helpdesk-agent-tab-message_content_form[data-state="success"] .helpdesk-agent-tab-message_content_form-result.-success,
      .helpdesk-agent-tab-message_content_form[data-state="fail"] .helpdesk-agent-tab-message_content_form-result.-fail {
        display: flex;
      }

      .helpdesk-agent-tab-message_content_form-result-icon {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        width: 48px;
        height: 48px;
        border-radius: 9999px;
        background-color: #b9f8cf;
        color: #008236;
      }

      .helpdesk-agent-tab-message_content_form[data-state="fail"] .helpdesk-agent-tab-message_content_form-result-icon {
        background-color: #ffc9c9;
        color: #9f0712;
      }

      .helpdesk-agent-tab-message_content_form-result-icon svg {
        flex-shrink: 0;
        width: 24px;
        height: 24px;
      }

      .helpdesk-agent-tab-message_content_form-result-title {
        margin-top: 14px;
        font-weight: 600;
        font-size: 20px;
        line-height: 28px;
        color: ${this.textColor}e0;
      }

      .helpdesk-agent-tab-message_content_form-result-description {
        font-size: 14px;
        line-height: 20px;
        color: ${this.textColor}7a;
      }

      .helpdesk-agent-tab-message_content_form-result-button {
        display: inline-flex;
        margin-top: 24px;
        padding: 8px 16px;
        column-gap: 6px;
        justify-content: center;
        align-items: center;
        border-radius: 8px;
        border: 1px solid transparent;
        outline: none;
        cursor: pointer;
        font-size: 14px;
        line-height: 20px;
        font-weight: 500;
        color: ${this.backgroundColor};
        background-color: ${this.primaryColor};
        -webkit-transition: all 0.1s ease-out;
        -o-transition: all 0.1s ease-out;
        transition: all 0.1s ease-out;
      }

      .helpdesk-agent-tab-message_content_form-result-button:hover {
        opacity: 0.95;
      }

      @keyframes spin {
        to {
          transform: rotate(360deg);
        }
      }
    `);

    return `
      <div class="helpdesk-agent-tab-message">
        <button class="helpdesk-agent-tab-message_close" aria-label="${wp.i18n.__('Close Helpdesk', 'generatify')}" data-close>
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>
        </button>
        <div class="helpdesk-agent-tab-message_header">
          ${this.cover ? `<img class="helpdesk-agent-tab-message_cover" src="${this.cover}" alt="image" />` : '<div class="helpdesk-agent-tab-message_cover"></div>'}
          ${this.icon ? `<img class="helpdesk-agent-tab-message_icon" src="${this.icon}" alt="image" />` : `<div class="helpdesk-agent-tab-message_icon">${window.location.hostname.charAt(0)}</div>`}
        </div>
        <div class="helpdesk-agent-tab-message_content">
          <form class="helpdesk-agent-tab-message_content_form">
            <div class="helpdesk-agent-tab-message_content_form-group">
              <label for="personName" class="helpdesk-agent-tab-message_content_form-label">${wp.i18n.__('Name', 'generatify')}</label>
              <input id="personName" name="personName" type="text" class="helpdesk-agent-tab-message_content_form-field" placeholder="${wp.i18n.__('Enter Name', 'generatify')}" maxlength="100" required />
            </div>
            <div class="helpdesk-agent-tab-message_content_form-group">
              <label for="personEmail" class="helpdesk-agent-tab-message_content_form-label">${wp.i18n.__('Email', 'generatify')}</label>
              <input id="personEmail" name="personEmail" type="email" class="helpdesk-agent-tab-message_content_form-field" placeholder="${wp.i18n.__('Enter Email', 'generatify')}" maxlength="100" required />
            </div>
            <div class="helpdesk-agent-tab-message_content_form-group">
              <label for="personMessage" class="helpdesk-agent-tab-message_content_form-label">${wp.i18n.__('Message', 'generatify')}</label>
              <textarea id="personMessage" name="personMessage" class="helpdesk-agent-tab-message_content_form-textarea" placeholder="${wp.i18n.__('Enter Message', 'generatify')}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" maxlength="3000" required></textarea>
            </div>
            <button type="submit" class="helpdesk-agent-tab-message_content_form-button">
              <div class="helpdesk-agent-tab-message_content_form-button_text">${wp.i18n.__('Send us a message', 'generatify')}</div>
              <div class="helpdesk-agent-tab-message_content_form-button_spinner" role="status" aria-label="loading"></div>
            </button>
            <div class="helpdesk-agent-tab-message_content_form-results">
              <div class="helpdesk-agent-tab-message_content_form-result -success" role="alert" aria-live="assertive">
                <span class="helpdesk-agent-tab-message_content_form-result-icon">
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"></path></svg>
                </span>
                <div class="helpdesk-agent-tab-message_content_form-result-title">
                  ${wp.i18n.__("We're on it!", 'generatify')}
                </div>
                <div class="helpdesk-agent-tab-message_content_form-result-description">
                  ${wp.i18n.__('You will receive a response via email.', 'generatify')}
                </div>
                <button type="button" class="helpdesk-agent-tab-message_content_form-result-button" onclick="this.closest('form').removeAttribute('data-state');">
                  ${wp.i18n.__('Send another message', 'generatify')}
                </button>
              </div>
              <div class="helpdesk-agent-tab-message_content_form-result -fail" role="alert" aria-live="assertive">
                <span class="helpdesk-agent-tab-message_content_form-result-icon">
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
                </span>
                <div class="helpdesk-agent-tab-message_content_form-result-title">
                  ${wp.i18n.__('Failed to send', 'generatify')}
                </div>
                <div class="helpdesk-agent-tab-message_content_form-result-description">
                  ${wp.i18n.__('There was an error sending your message.', 'generatify')}
                </div>
                <button type="button" class="helpdesk-agent-tab-message_content_form-result-button" onclick="this.closest('form').removeAttribute('data-state');">
                  ${wp.i18n.__('Try sending again', 'generatify')}
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    `;
  }

  renderHelpTab() {
    this.injectStyles(`
      .helpdesk-agent-tab-help {
        position: relative;
        display: flex;
        flex-direction: column;
        height: 100%;
      }

      .helpdesk-agent-tab-help_header {
        position: sticky;
        top: 0;
        z-index: 10;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
        column-gap: 8px;
        background-color: ${this.backgroundColor};
        border-bottom: 1px solid ${this.textColor}1f;
      }

      .helpdesk-agent-tab-help_header_icon {
        position: relative; 
        display: flex;
        justify-content: center; 
        align-items: center;
        border-radius: 9999px;
        overflow: hidden;
        object-fit: cover;
        width: 28px;
        height: 28px;
        font-weight: 600;
        font-size: 12px;
        line-height: 1;
        text-align: center;
        background-color: ${this.textColor};
        color: ${this.backgroundColor};
        text-transform: uppercase;
      }

      .helpdesk-agent-tab-help_header_title {
        display: block;
        font-weight: 600;
        font-size: 14px;
        line-height: 16px;
        color: ${this.textColor}e0;
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
      }

      .helpdesk-agent-tab-help_header_close {
        display: flex;
        justify-content: center; 
        align-items: center; 
        border-radius: 9999px;
        color: ${this.textColor}7a;
        flex-shrink: 0;
        width: 32px;
        height: 32px;
        border: none;
        outline: none;
        cursor: pointer;
        background-color: transparent;
      }

      .helpdesk-agent-tab-help_header_close:hover {
        background-color: ${this.textColor}0a;
      }

      .helpdesk-agent-tab-help_header_close svg {
        flex-shrink: 0;
        width: 16px;
        height: 16px;
      }

      .helpdesk-agent-tab-help_content {
        flex: 1;
        overflow-y: auto; 
      }
      
      .helpdesk-agent-tab-help_articles_list {
        list-style: none;
        margin: 0;
        padding: 0;
      }

      .helpdesk-agent-tab-help_article_item {
        overflow: hidden;
        border-bottom: 1px solid ${this.textColor}1f;
      }

      .helpdesk-agent-tab-help_article_link {
        display: flex; 
        padding: 14px 16px;
        column-gap: 14px;
        background-color: ${this.backgroundColor};
        text-decoration: none;
        outline: none;
        cursor: pointer;
        -webkit-transition: all 0.1s ease-out;
        -o-transition: all 0.1s ease-out;
        transition: all 0.1s ease-out;
      }

      .helpdesk-agent-tab-help_article_link:hover {
        background-color: ${this.textColor}0a; 
      }

      .helpdesk-agent-tab-help_article_title {
        font-size: 14px;
        line-height: 20px;
        font-weight: 500;
        color: ${this.textColor}e0;
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
      }

      .helpdesk-agent-tab-help_article_description {
        font-size: 12px;
        line-height: 16px;
        color: ${this.textColor}bd;
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
      }

      .helpdesk-agent-tab-help_article_icon {
        align-self: center;
        margin-inline-start: auto;
      }

      .helpdesk-agent-tab-help_article_icon svg {
        width: 14px;
        height: 14px;
        flex-shrink: 0;
        color: ${this.textColor};
      }

      .helpdesk-agent-tab-help_no-articles {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-align: center;
        height: calc(100% - 49px);
        padding: 20px;
      }

      .helpdesk-agent-tab-help_no-articles_icon {
        width: 192px;
        margin: 0 auto;
      }

      .helpdesk-agent-tab-help_no-articles_texts {
        margin: 16px auto 0 auto;
        max-width: 240px;
      }

      .helpdesk-agent-tab-help_no-articles_title {
        color: ${this.textColor}e0;
        font-size: 16px;
        line-height: 24px;
        font-weight: 600;
      }

      .helpdesk-agent-tab-help_no-articles_description {
        color: ${this.textColor}bd;
        font-size: 14px;
        line-height: 20px;
      }
    `);

    return `
      <div class="helpdesk-agent-tab-help">
        <div class="helpdesk-agent-tab-help_header">
          ${this.icon ? `<img class="helpdesk-agent-tab-help_header_icon" src="${this.icon}" alt="image" />` : `<div class="helpdesk-agent-tab-help_header_icon">${window.location.hostname.charAt(0)}</div>`}
          <span class="helpdesk-agent-tab-help_header_title">
            ${wp.i18n.__('Help Articles', 'generatify')}
          </span>
          <button type="button" class="helpdesk-agent-tab-help_header_close" aria-label="${wp.i18n.__('Close', 'generatify')}" data-close>
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M18 6 6 18"></path>
              <path d="m6 6 12 12"></path>
            </svg>
          </button>
        </div>
        <div class="helpdesk-agent-tab-help_content">
          ${(() => {
            const validArticles = (this.helpArticles || []).filter((article) => article && article.title && article.description && article.url);
            return validArticles.length
              ? `
            <ul class="helpdesk-agent-tab-help_articles_list">
              ${validArticles
                .map(
                  (article) => `
                <li class="helpdesk-agent-tab-help_article_item">
                  <a class="helpdesk-agent-tab-help_article_link" href="${article.url}" target="_blank">
                    <div>
                      <div class="helpdesk-agent-tab-help_article_title">
                        ${article.title}
                      </div>
                      <div class="helpdesk-agent-tab-help_article_description">
                        ${article.description}
                      </div>
                    </div>
                    <div class="helpdesk-agent-tab-help_article_icon">
                      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="m9 18 6-6-6-6"/>
                      </svg>
                    </div>
                  </a>
                </li>
              `
                )
                .join('')}
            </ul>
          `
              : `
            <div class="helpdesk-agent-tab-help_no-articles">
              <svg class="helpdesk-agent-tab-help_no-articles_icon" viewBox="0 0 178 75" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect x="19.5" y="28.5" width="139" height="39" rx="7.5" fill="currentColor" style="fill: ${this.backgroundColor};"></rect>
                <rect x="19.5" y="28.5" width="139" height="39" rx="7.5" stroke="currentColor" style="stroke: ${this.textColor}0a;"></rect>
                <rect x="27" y="36" width="24" height="24" rx="12" fill="currentColor" style="fill: ${this.textColor}0a;"></rect>
                <rect x="59" y="39" width="60" height="6" rx="3" fill="currentColor" style="fill: ${this.textColor}0a;"></rect>
                <rect x="59" y="51" width="92" height="6" rx="3" fill="currentColor" style="fill: ${this.textColor}0a;"></rect>
                <g filter="url(#filter1)">
                  <rect x="12" y="6" width="154" height="40" rx="8" style="fill: ${this.backgroundColor};" shape-rendering="crispEdges"></rect>
                  <rect x="12.5" y="6.5" width="153" height="39" rx="7.5" stroke="currentColor" style="stroke: ${this.textColor}0a;" shape-rendering="crispEdges"></rect>
                  <rect x="20" y="14" width="24" height="24" rx="12" fill="currentColor" style="fill: ${this.textColor}30;"></rect>
                  <rect x="52" y="17" width="60" height="6" rx="3" fill="currentColor" style="fill: ${this.textColor}30;"></rect>
                  <rect x="52" y="29" width="106" height="6" rx="3" fill="currentColor" style="fill: ${this.textColor}30;"></rect>
                </g>
                <defs>
                  <filter id="filter1" x="0" y="0" width="178" height="64" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
                    <feFlood flood-opacity="0" result="BackgroundImageFix"></feFlood>
                    <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"></feColorMatrix>
                    <feOffset dy="6"></feOffset>
                    <feGaussianBlur stdDeviation="6"></feGaussianBlur>
                    <feComposite in2="hardAlpha" operator="out"></feComposite>
                    <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.03 0"></feColorMatrix>
                    <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_1187_14810"></feBlend>
                    <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_1187_14810" result="shape"></feBlend>
                  </filter>
                </defs>
              </svg>
              <div class="helpdesk-agent-tab-help_no-articles_texts">
                <div class="helpdesk-agent-tab-help_no-articles_title">
                  ${wp.i18n.__('No help articles', 'generatify')}
                </div>
                <div class="helpdesk-agent-tab-help_no-articles_description">
                  ${wp.i18n.__('Currently no help articles available', 'generatify')}
                </div>
              </div>
            </div>
          `;
          })()}
        </div>
      </div>
    `;
  }

  renderTabs() {
    this.injectStyles(`
      .helpdesk-agent-tab {
        display: none;
        position: relative;
        width: 100%;
        height: calc(100% - 86px);
        -webkit-transition: all 0.1s ease-out;
        -o-transition: all 0.1s ease-out;
        transition: all 0.1s ease-out;
        animation: 0.1s ease 0s 1 normal none running fadeIn;
      }

      .helpdesk-agent:has(.helpdesk-agent-tab[data-tab="message"][data-active]) .helpdesk-agent-tab {
        height: 100%;
      }

      .helpdesk-agent-tab[data-active] {
        display: block;
      }

      .helpdesk-agent-tab-nav {
        position: sticky;
        bottom: 0;
        display: flex;
        padding: 16px 20px;
        border-bottom-right-radius: 16px;
        border-bottom-left-radius: 16px; 
        border-top: 1px solid ${this.textColor}1f; 
        background-color: ${this.backgroundColor}; 
      }

      .helpdesk-agent-tab-nav-button {
        display: inline-flex;
        flex-direction: column;
        gap: 1px;
        justify-content: center;
        align-items: center;
        width: 100%;
        font-size: 14px;
        line-height: 20px;
        text-align: center;
        color: ${this.textColor}e0;
        border-radius: 8px;
        outline: none;
        border: none;
        padding: 0;
        margin: 0;
        cursor: pointer;
        background-color: transparent;
        -webkit-transition: all 0.1s ease-out;
        -o-transition: all 0.1s ease-out;
        transition: all 0.1s ease-out;
      }

      .helpdesk-agent-tab-nav-button:hover {
        color: ${this.primaryColor};
      }

      .helpdesk-agent-tab-nav-button[data-active] {
        color: ${this.primaryColor};
        font-weight: 500;
      }

      .helpdesk-agent-tab-nav-button span {
        display: flex;
        justify-content: center; 
        align-items: center;
        padding: 8px 16px;
        border-radius: 9999px;
      }

      .helpdesk-agent-tab-nav-button[data-active] span {
        background-color: ${this.primaryColor}1a;
      }

      .helpdesk-agent-tab-nav-button svg {
        flex-shrink: 0;
        width: 16px;
        height: 16px;
      }
    `);

    return `
      <div class="helpdesk-agent-tab" role="tabpanel" aria-labelledby="home-tab" tabindex="0" data-tab="home" data-active>
        ${this.renderHomeTab()}
      </div>
      <div class="helpdesk-agent-tab" role="tabpanel" aria-labelledby="message-tab" tabindex="0" data-tab="message">
        ${this.renderMessageTab()}
      </div>
      <div class="helpdesk-agent-tab" role="tabpanel" aria-labelledby="help-tab" tabindex="0" data-tab="help">
        ${this.renderHelpTab()}
      </div>
      <nav class="helpdesk-agent-tab-nav" aria-label="Tabs" role="tablist" aria-orientation="horizontal">
        <button type="button" class="helpdesk-agent-tab-nav-button" aria-controls="home-tab" role="tab" data-tab="home" data-active>
          <span>
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
              <polyline points="9 22 9 12 15 12 15 22"></polyline>
            </svg>
          </span>
          ${wp.i18n.__('Home', 'generatify')}
        </button>
        <button type="button" class="helpdesk-agent-tab-nav-button" aria-controls="message-tab" role="tab" data-tab="message">
          <span>
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M14 9a2 2 0 0 1-2 2H6l-4 4V4c0-1.1.9-2 2-2h8a2 2 0 0 1 2 2z"></path>
              <path d="M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"></path>
            </svg>
          </span>
          ${wp.i18n.__('Message', 'generatify')}
        </button>
        <button type="button" class="helpdesk-agent-tab-nav-button" aria-controls="help-tab" role="tab" data-tab="help">
          <span>
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="12" cy="12" r="10"></circle>
              <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>
              <path d="M12 17h.01"></path>
            </svg>
          </span>
          ${wp.i18n.__('Help', 'generatify')}
        </button>
      </nav>
    `;
  }

  render() {
    const positionStyles = {
      'bottom-right': document.querySelector('progressify-navigation-tab-bar') ? 'bottom: 70px; right: 20px;' : 'bottom: 20px; right: 20px;',
      'bottom-left': document.querySelector('progressify-navigation-tab-bar') ? 'bottom: 70px; left: 20px;' : 'bottom: 20px; left: 20px;',
      'top-right': 'top: 20px; right: 20px;',
      'top-left': 'top: 20px; left: 20px;',
    }[this.position];

    const dropdownPositionStyles = {
      'bottom-right': document.querySelector('progressify-navigation-tab-bar') ? 'bottom: 130px; right: 20px;' : 'bottom: 80px; right: 20px;',
      'bottom-left': document.querySelector('progressify-navigation-tab-bar') ? 'bottom: 130px; left: 20px;' : 'bottom: 80px; left: 20px;',
      'top-right': 'top: 80px; right: 20px;',
      'top-left': 'top: 80px; left: 20px;',
    }[this.position];

    this.injectStyles(`
      .helpdesk-agent {
        position: fixed;
        ${positionStyles}
        z-index: 99999;
      }

      .helpdesk-agent * {
        font-family: inherit !important;
      }

      .helpdesk-agent *::-webkit-scrollbar {
        width: 8px;
      }

      .helpdesk-agent *::-webkit-scrollbar-thumb {
        border-radius: 9999px;
        background-color: ${this.textColor}7a;
      }

      .helpdesk-agent *::-webkit-scrollbar-track {
        background-color: ${this.textColor}0a;
      }

      .helpdesk-agent-dropdown {
        display: none;
        position: fixed;
        flex-direction: column;
        ${dropdownPositionStyles}
        width: 384px;
        max-width: 89%;
        height: 100%;
        max-height: min(612px, 100% - 100px);
        overflow: auto;
        z-index: 10;
        border-radius: 1.5rem; 
        background-color: ${this.backgroundColor}; 
        box-shadow: rgba(9, 14, 21, 0.16) 0px 5px 40px 0px; 
        -webkit-transition: all 0.1s ease-out;
        -o-transition: all 0.1s ease-out;
        transition: all 0.1s ease-out;
        animation: 0.1s ease 0s 1 normal none running fadeIn;
      }
      
      .helpdesk-agent[data-open] .helpdesk-agent-dropdown {
        display: flex;
      }

      .helpdesk-agent-button {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-align: center;
            -ms-flex-align: center;
                align-items: center;
        -webkit-box-pack: center;
            -ms-flex-pack: center;
                justify-content: center;
        -webkit-transition: all 0.1s ease-out;
        -o-transition: all 0.1s ease-out;
        transition: all 0.1s ease-out;
        width: 50px;
        height: 50px;
        background: ${this.primaryColor};
        border: none;
        border-radius: 50%;
        cursor: pointer;
        -webkit-box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      }

      .helpdesk-agent-button:hover {
        opacity: 0.95;
      }
  
      .helpdesk-agent-button_icon {
        width: 1.25rem;
        height: 1.25rem;
        color: ${this.backgroundColor};
      }

      .helpdesk-agent[data-open] .helpdesk-agent-button_icon.-closed,
      .helpdesk-agent .helpdesk-agent-button_icon.-open {
        display: none;
      }

      .helpdesk-agent .helpdesk-agent-button_icon.-closed,
      .helpdesk-agent[data-open] .helpdesk-agent-button_icon.-open {
        display: inline-block;
      }

      @media (max-width: 500px) { 
        .helpdesk-agent-dropdown {
          inset: 0;
          width: 100%;
          max-width: 100%;
          height: 100%;
          max-height: 100%;
          border-radius: 0;
        }
      }

      @-webkit-keyframes fadeIn {
        0% {
          opacity: 0;
        }
        40% {
          opacity: 0.4;
        }
        60% {
          opacity: 0.6;
        }
        100% {
          opacity: 1;
        }
      }

      @keyframes fadeIn {
        0% {
          opacity: 0;
        }
        40% {
          opacity: 0.4;
        }
        60% {
          opacity: 0.6;
        }
        100% {
          opacity: 1;
        }
      }
    `);

    const tabs = this.renderTabs();
    const combinedStyles = Array.from(this.styles).join('\n');

    this.shadowRoot.innerHTML = `
      <style>${combinedStyles}</style>
      <div class="helpdesk-agent">
        <div class="helpdesk-agent-dropdown" role="menu" aria-orientation="vertical" tabindex="-1">
          ${tabs}
        </div>
        <div class="helpdesk-agent-button" role="button" tabindex="0" aria-pressed="false" aria-label="${wp.i18n.__('Toggle Helpdesk', 'generatify')}">
          <svg class="helpdesk-agent-button_icon -closed" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"/></svg>
          <svg class="helpdesk-agent-button_icon -open" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
        </div>
      </div>
    `;
  }
}

function initHelpdeskAgent() {
  if (!customElements.get('generatify-helpdesk-agent')) {
    customElements.define('generatify-helpdesk-agent', GeneratifyHelpdeskAgent);
  }

  GeneratifyHelpdeskAgent.show();
}

document.addEventListener('DOMContentLoaded', function () {
  initHelpdeskAgent();
});
