/**
 * Recipient Selection Modal
 *
 * Modal UI for selecting recipients and watermarking options when protecting documents.
 * Supports both manual entry and Filevine contact selection.
 */

export class RecipientModal {
  constructor() {
    this.modal = null;
    this.onConfirm = null;
    this.contacts = [];
    this.selectedDocument = null;
  }

  /**
   * Show the modal for a specific document
   *
   * @param {Object} documentInfo - Document metadata
   * @param {string} documentInfo.docId - Document ID
   * @param {string} documentInfo.filename - Document filename
   * @param {string} documentInfo.projectId - Project ID
   * @param {Function} onConfirm - Callback(recipientData, watermarkOptions)
   */
  async show(documentInfo, onConfirm) {
    this.selectedDocument = documentInfo;
    this.onConfirm = onConfirm;

    // Load project contacts
    await this.loadProjectContacts(documentInfo.projectId);

    // Create and inject modal
    this.createModal();
    document.body.appendChild(this.modal);

    // Focus first input
    setTimeout(() => {
      const firstInput = this.modal.querySelector('input[name="recipientName"]');
      if (firstInput) firstInput.focus();
    }, 100);
  }

  /**
   * Load contacts from Filevine project
   */
  async loadProjectContacts(projectId) {
    try {
      const response = await chrome.runtime.sendMessage({
        type: 'GET_PROJECT_CONTACTS',
        projectId: parseInt(projectId)
      });

      if (response?.contacts) {
        this.contacts = response.contacts;
        console.log('[Recipient Modal] Loaded', this.contacts.length, 'contacts');
      }
    } catch (error) {
      console.warn('[Recipient Modal] Failed to load contacts:', error);
      this.contacts = [];
    }
  }

  /**
   * Create modal DOM structure
   */
  createModal() {
    this.modal = document.createElement('div');
    this.modal.className = 'fv-echomark-modal-overlay';

    this.modal.innerHTML = `
      <div class="fv-echomark-modal">
        <div class="fv-echomark-modal-header">
          <h2>Protect Document with Forensic Watermark</h2>
          <button class="fv-echomark-close" aria-label="Close">&times;</button>
        </div>

        <div class="fv-echomark-modal-body">
          <!-- Document Info -->
          <div class="fv-echomark-doc-info">
            <svg class="fv-echomark-doc-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
              <polyline points="14 2 14 8 20 8"></polyline>
            </svg>
            <div>
              <div class="fv-echomark-doc-filename">${this.selectedDocument.filename}</div>
              <div class="fv-echomark-doc-note">A unique watermark will be embedded for leak tracking</div>
            </div>
          </div>

          <!-- Recipient Selection -->
          <div class="fv-echomark-section">
            <h3>Select Recipient</h3>

            <!-- Tab Switcher -->
            <div class="fv-echomark-tabs">
              <button class="fv-echomark-tab active" data-tab="manual">
                Manual Entry
              </button>
              <button class="fv-echomark-tab" data-tab="contacts">
                Project Contacts (${this.contacts.length})
              </button>
            </div>

            <!-- Manual Entry Tab -->
            <div class="fv-echomark-tab-content active" data-tab-content="manual">
              <div class="fv-echomark-form-group">
                <label for="recipientName">Recipient Name <span class="required">*</span></label>
                <input
                  type="text"
                  id="recipientName"
                  name="recipientName"
                  placeholder="John Doe"
                  required
                />
              </div>

              <div class="fv-echomark-form-group">
                <label for="recipientEmail">Recipient Email <span class="required">*</span></label>
                <input
                  type="email"
                  id="recipientEmail"
                  name="recipientEmail"
                  placeholder="john.doe@example.com"
                  required
                />
                <small>Used as unique watermark identifier</small>
              </div>
            </div>

            <!-- Contacts Tab -->
            <div class="fv-echomark-tab-content" data-tab-content="contacts">
              <div class="fv-echomark-contact-search">
                <input
                  type="text"
                  id="contactSearch"
                  placeholder="Search contacts..."
                />
              </div>

              <div class="fv-echomark-contact-list">
                ${this.renderContactList()}
              </div>
            </div>
          </div>

          <!-- Watermarking Options -->
          <div class="fv-echomark-section">
            <h3>Watermarking Options</h3>

            <div class="fv-echomark-option-group">
              <label class="fv-echomark-checkbox">
                <input type="checkbox" name="imageWatermarking" checked />
                <span>Image Watermarking</span>
                <small>Invisible watermarks in images/graphics</small>
              </label>

              <label class="fv-echomark-checkbox">
                <input type="checkbox" name="textWatermarking" checked />
                <span>Text Watermarking</span>
                <small>Subtle variations in text positioning</small>
              </label>

              <label class="fv-echomark-checkbox">
                <input type="checkbox" name="visibleWatermarking" />
                <span>Visible Watermark (Optional)</span>
                <small>Add visible text overlay</small>
              </label>

              <div class="fv-echomark-visible-options" style="display: none;">
                <input
                  type="text"
                  name="visibleText"
                  placeholder="Personalized for {{recipient}}"
                  value="Personalized for {{recipient}}"
                />
              </div>
            </div>

            <div class="fv-echomark-form-group">
              <label for="watermarkStrength">Watermark Strength</label>
              <select id="watermarkStrength" name="watermarkStrength">
                <option value="auto" selected>Auto (Recommended)</option>
                <option value="subtle">Subtle (Lower distortion)</option>
                <option value="balanced">Balanced</option>
                <option value="strong">Strong (Higher robustness)</option>
              </select>
              <small>Higher strength = more resistant to alterations</small>
            </div>
          </div>

          <!-- Error Display -->
          <div class="fv-echomark-error" style="display: none;"></div>
        </div>

        <div class="fv-echomark-modal-footer">
          <button class="fv-echomark-btn fv-echomark-btn-secondary" data-action="cancel">
            Cancel
          </button>
          <button class="fv-echomark-btn fv-echomark-btn-primary" data-action="confirm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
              <path d="M9 12l2 2 4-4"></path>
            </svg>
            Protect Document
          </button>
        </div>
      </div>
    `;

    this.attachStyles();
    this.attachEventListeners();
  }

  /**
   * Render contact list HTML
   */
  renderContactList() {
    if (this.contacts.length === 0) {
      return `
        <div class="fv-echomark-empty-state">
          <p>No contacts found for this project</p>
          <small>Use Manual Entry to specify a recipient</small>
        </div>
      `;
    }

    return this.contacts.map(contact => `
      <div class="fv-echomark-contact-item" data-contact-id="${contact.id}">
        <div class="fv-echomark-contact-avatar">
          ${this.getInitials(contact.name)}
        </div>
        <div class="fv-echomark-contact-info">
          <div class="fv-echomark-contact-name">${contact.name}</div>
          <div class="fv-echomark-contact-email">${contact.email || 'No email'}</div>
        </div>
        <div class="fv-echomark-contact-role">${contact.role || ''}</div>
      </div>
    `).join('');
  }

  /**
   * Get initials from name
   */
  getInitials(name) {
    return name
      .split(' ')
      .map(part => part[0])
      .join('')
      .toUpperCase()
      .slice(0, 2);
  }

  /**
   * Attach event listeners
   */
  attachEventListeners() {
    // Close button
    this.modal.querySelector('.fv-echomark-close').addEventListener('click', () => {
      this.hide();
    });

    // Click outside to close
    this.modal.addEventListener('click', (e) => {
      if (e.target === this.modal) {
        this.hide();
      }
    });

    // Tab switching
    this.modal.querySelectorAll('.fv-echomark-tab').forEach(tab => {
      tab.addEventListener('click', () => {
        this.switchTab(tab.dataset.tab);
      });
    });

    // Contact selection
    this.modal.querySelectorAll('.fv-echomark-contact-item').forEach(item => {
      item.addEventListener('click', () => {
        this.selectContact(item);
      });
    });

    // Contact search
    const searchInput = this.modal.querySelector('#contactSearch');
    if (searchInput) {
      searchInput.addEventListener('input', (e) => {
        this.filterContacts(e.target.value);
      });
    }

    // Visible watermark toggle
    this.modal.querySelector('input[name="visibleWatermarking"]').addEventListener('change', (e) => {
      const options = this.modal.querySelector('.fv-echomark-visible-options');
      options.style.display = e.target.checked ? 'block' : 'none';
    });

    // Cancel button
    this.modal.querySelector('[data-action="cancel"]').addEventListener('click', () => {
      this.hide();
    });

    // Confirm button
    this.modal.querySelector('[data-action="confirm"]').addEventListener('click', () => {
      this.handleConfirm();
    });

    // Enter key in inputs
    this.modal.querySelectorAll('input[type="text"], input[type="email"]').forEach(input => {
      input.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
          this.handleConfirm();
        }
      });
    });

    // Escape key to close
    document.addEventListener('keydown', this.handleEscape = (e) => {
      if (e.key === 'Escape' && this.modal) {
        this.hide();
      }
    });
  }

  /**
   * Switch between tabs
   */
  switchTab(tabName) {
    // Update tab buttons
    this.modal.querySelectorAll('.fv-echomark-tab').forEach(tab => {
      tab.classList.toggle('active', tab.dataset.tab === tabName);
    });

    // Update tab content
    this.modal.querySelectorAll('.fv-echomark-tab-content').forEach(content => {
      content.classList.toggle('active', content.dataset.tabContent === tabName);
    });
  }

  /**
   * Select a contact from the list
   */
  selectContact(contactElement) {
    // Remove previous selection
    this.modal.querySelectorAll('.fv-echomark-contact-item').forEach(item => {
      item.classList.remove('selected');
    });

    // Mark as selected
    contactElement.classList.add('selected');

    // Fill in manual entry fields with contact data
    const contactId = contactElement.dataset.contactId;
    const contact = this.contacts.find(c => c.id == contactId);

    if (contact) {
      this.modal.querySelector('input[name="recipientName"]').value = contact.name;
      this.modal.querySelector('input[name="recipientEmail"]').value = contact.email || '';
    }
  }

  /**
   * Filter contacts by search query
   */
  filterContacts(query) {
    const lowerQuery = query.toLowerCase();
    this.modal.querySelectorAll('.fv-echomark-contact-item').forEach(item => {
      const name = item.querySelector('.fv-echomark-contact-name').textContent.toLowerCase();
      const email = item.querySelector('.fv-echomark-contact-email').textContent.toLowerCase();
      const matches = name.includes(lowerQuery) || email.includes(lowerQuery);
      item.style.display = matches ? 'flex' : 'none';
    });
  }

  /**
   * Handle confirm button click
   */
  async handleConfirm() {
    try {
      // Validate inputs
      const recipientName = this.modal.querySelector('input[name="recipientName"]').value.trim();
      const recipientEmail = this.modal.querySelector('input[name="recipientEmail"]').value.trim();

      if (!recipientName || !recipientEmail) {
        this.showError('Please enter recipient name and email');
        return;
      }

      // Email validation
      if (!this.isValidEmail(recipientEmail)) {
        this.showError('Please enter a valid email address');
        return;
      }

      // Collect watermark options
      const options = {
        imageWatermarking: this.modal.querySelector('input[name="imageWatermarking"]').checked,
        textWatermarking: this.modal.querySelector('input[name="textWatermarking"]').checked,
        visibleWatermarking: this.modal.querySelector('input[name="visibleWatermarking"]').checked,
        visibleWatermarkText: this.modal.querySelector('input[name="visibleText"]').value,
        watermarkStrength: this.modal.querySelector('select[name="watermarkStrength"]').value
      };

      // At least one watermarking method must be enabled
      if (!options.imageWatermarking && !options.textWatermarking) {
        this.showError('Please enable at least one watermarking method');
        return;
      }

      // Show loading state
      const confirmBtn = this.modal.querySelector('[data-action="confirm"]');
      const originalText = confirmBtn.innerHTML;
      confirmBtn.disabled = true;
      confirmBtn.innerHTML = `
        <svg class="fv-echomark-spinner" viewBox="0 0 24 24">
          <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" opacity="0.25"/>
          <path d="M12 2a10 10 0 0 1 10 10" stroke="currentColor" stroke-width="2" fill="none"/>
        </svg>
        Processing...
      `;

      // Call confirm callback
      if (this.onConfirm) {
        await this.onConfirm(
          {
            recipientId: recipientEmail,
            recipientName: recipientName
          },
          options
        );
      }

      // Hide modal on success
      this.hide();

    } catch (error) {
      console.error('[Recipient Modal] Confirm error:', error);
      this.showError(error.message || 'Failed to process document');

      // Reset button
      const confirmBtn = this.modal.querySelector('[data-action="confirm"]');
      confirmBtn.disabled = false;
      confirmBtn.innerHTML = `
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
          <path d="M9 12l2 2 4-4"></path>
        </svg>
        Protect Document
      `;
    }
  }

  /**
   * Validate email format
   */
  isValidEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  }

  /**
   * Show error message
   */
  showError(message) {
    const errorDiv = this.modal.querySelector('.fv-echomark-error');
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';

    // Auto-hide after 5 seconds
    setTimeout(() => {
      errorDiv.style.display = 'none';
    }, 5000);
  }

  /**
   * Hide the modal
   */
  hide() {
    if (this.modal && this.modal.parentNode) {
      this.modal.parentNode.removeChild(this.modal);
    }
    this.modal = null;

    // Remove escape key listener
    if (this.handleEscape) {
      document.removeEventListener('keydown', this.handleEscape);
    }
  }

  /**
   * Inject styles for the modal
   */
  attachStyles() {
    if (document.getElementById('fv-echomark-modal-styles')) {
      return; // Already injected
    }

    const style = document.createElement('style');
    style.id = 'fv-echomark-modal-styles';
    style.textContent = `
      .fv-echomark-modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(4px);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10000;
        animation: fv-echomark-fade-in 0.2s ease-out;
      }

      @keyframes fv-echomark-fade-in {
        from { opacity: 0; }
        to { opacity: 1; }
      }

      .fv-echomark-modal {
        background: white;
        border-radius: 8px;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        width: 90%;
        max-width: 600px;
        max-height: 90vh;
        display: flex;
        flex-direction: column;
        animation: fv-echomark-slide-up 0.3s ease-out;
      }

      @keyframes fv-echomark-slide-up {
        from { transform: translateY(20px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
      }

      .fv-echomark-modal-header {
        padding: 20px 24px;
        border-bottom: 1px solid #e2e8f0;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .fv-echomark-modal-header h2 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #1a202c;
      }

      .fv-echomark-close {
        background: none;
        border: none;
        font-size: 28px;
        color: #718096;
        cursor: pointer;
        padding: 0;
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        transition: background 0.2s;
      }

      .fv-echomark-close:hover {
        background: #f7fafc;
        color: #2d3748;
      }

      .fv-echomark-modal-body {
        padding: 24px;
        overflow-y: auto;
        flex: 1;
      }

      .fv-echomark-doc-info {
        display: flex;
        gap: 12px;
        padding: 16px;
        background: #f7fafc;
        border-radius: 6px;
        margin-bottom: 24px;
        border: 1px solid #e2e8f0;
      }

      .fv-echomark-doc-icon {
        width: 40px;
        height: 40px;
        color: #800020;
        flex-shrink: 0;
      }

      .fv-echomark-doc-filename {
        font-weight: 600;
        color: #1a202c;
        margin-bottom: 4px;
      }

      .fv-echomark-doc-note {
        font-size: 13px;
        color: #718096;
      }

      .fv-echomark-section {
        margin-bottom: 24px;
      }

      .fv-echomark-section h3 {
        font-size: 14px;
        font-weight: 600;
        color: #2d3748;
        margin: 0 0 12px 0;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      }

      .fv-echomark-tabs {
        display: flex;
        gap: 8px;
        margin-bottom: 16px;
        border-bottom: 2px solid #e2e8f0;
      }

      .fv-echomark-tab {
        background: none;
        border: none;
        padding: 10px 16px;
        font-size: 14px;
        font-weight: 500;
        color: #718096;
        cursor: pointer;
        border-bottom: 2px solid transparent;
        margin-bottom: -2px;
        transition: all 0.2s;
      }

      .fv-echomark-tab:hover {
        color: #2d3748;
      }

      .fv-echomark-tab.active {
        color: #800020;
        border-bottom-color: #800020;
      }

      .fv-echomark-tab-content {
        display: none;
      }

      .fv-echomark-tab-content.active {
        display: block;
      }

      .fv-echomark-form-group {
        margin-bottom: 16px;
      }

      .fv-echomark-form-group label {
        display: block;
        font-size: 13px;
        font-weight: 600;
        color: #2d3748;
        margin-bottom: 6px;
      }

      .fv-echomark-form-group .required {
        color: #e53e3e;
      }

      .fv-echomark-form-group input[type="text"],
      .fv-echomark-form-group input[type="email"],
      .fv-echomark-form-group select {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #cbd5e0;
        border-radius: 4px;
        font-size: 14px;
        transition: border-color 0.2s;
      }

      .fv-echomark-form-group input:focus,
      .fv-echomark-form-group select:focus {
        outline: none;
        border-color: #800020;
        box-shadow: 0 0 0 3px rgba(128, 0, 32, 0.1);
      }

      .fv-echomark-form-group small {
        display: block;
        font-size: 12px;
        color: #718096;
        margin-top: 4px;
      }

      .fv-echomark-contact-search {
        margin-bottom: 12px;
      }

      .fv-echomark-contact-search input {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #cbd5e0;
        border-radius: 4px;
        font-size: 14px;
      }

      .fv-echomark-contact-list {
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #e2e8f0;
        border-radius: 4px;
      }

      .fv-echomark-contact-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        cursor: pointer;
        border-bottom: 1px solid #e2e8f0;
        transition: background 0.2s;
      }

      .fv-echomark-contact-item:last-child {
        border-bottom: none;
      }

      .fv-echomark-contact-item:hover {
        background: #f7fafc;
      }

      .fv-echomark-contact-item.selected {
        background: #edf2f7;
        border-left: 3px solid #800020;
      }

      .fv-echomark-contact-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: linear-gradient(135deg, #800020 0%, #a0002a 100%);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        font-size: 14px;
        flex-shrink: 0;
      }

      .fv-echomark-contact-info {
        flex: 1;
      }

      .fv-echomark-contact-name {
        font-weight: 600;
        color: #1a202c;
        font-size: 14px;
      }

      .fv-echomark-contact-email {
        font-size: 12px;
        color: #718096;
      }

      .fv-echomark-contact-role {
        font-size: 12px;
        color: #a0aec0;
        font-style: italic;
      }

      .fv-echomark-empty-state {
        padding: 40px 20px;
        text-align: center;
        color: #718096;
      }

      .fv-echomark-empty-state p {
        margin: 0 0 8px 0;
        font-weight: 500;
      }

      .fv-echomark-empty-state small {
        font-size: 13px;
      }

      .fv-echomark-option-group {
        display: flex;
        flex-direction: column;
        gap: 12px;
      }

      .fv-echomark-checkbox {
        display: flex;
        align-items: flex-start;
        gap: 10px;
        cursor: pointer;
        padding: 12px;
        border: 1px solid #e2e8f0;
        border-radius: 4px;
        transition: background 0.2s;
      }

      .fv-echomark-checkbox:hover {
        background: #f7fafc;
      }

      .fv-echomark-checkbox input[type="checkbox"] {
        margin-top: 2px;
        cursor: pointer;
      }

      .fv-echomark-checkbox span {
        flex: 1;
        font-weight: 500;
        color: #2d3748;
        font-size: 14px;
      }

      .fv-echomark-checkbox small {
        display: block;
        font-size: 12px;
        color: #718096;
        margin-top: 2px;
      }

      .fv-echomark-visible-options {
        margin-left: 32px;
        margin-top: -4px;
      }

      .fv-echomark-visible-options input {
        width: 100%;
        padding: 6px 10px;
        border: 1px solid #cbd5e0;
        border-radius: 3px;
        font-size: 13px;
      }

      .fv-echomark-error {
        padding: 12px;
        background: #fff5f5;
        border: 1px solid #fc8181;
        border-radius: 4px;
        color: #c53030;
        font-size: 13px;
        margin-top: 16px;
      }

      .fv-echomark-modal-footer {
        padding: 16px 24px;
        border-top: 1px solid #e2e8f0;
        display: flex;
        gap: 12px;
        justify-content: flex-end;
      }

      .fv-echomark-btn {
        padding: 8px 20px;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        border: none;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .fv-echomark-btn svg {
        width: 16px;
        height: 16px;
      }

      .fv-echomark-btn-secondary {
        background: white;
        color: #4a5568;
        border: 1px solid #cbd5e0;
      }

      .fv-echomark-btn-secondary:hover {
        background: #f7fafc;
      }

      .fv-echomark-btn-primary {
        background: linear-gradient(135deg, #800020 0%, #a0002a 100%);
        color: white;
      }

      .fv-echomark-btn-primary:hover {
        background: linear-gradient(135deg, #600018 0%, #800020 100%);
      }

      .fv-echomark-btn-primary:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }

      .fv-echomark-spinner {
        animation: fv-echomark-spin 1s linear infinite;
      }

      @keyframes fv-echomark-spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
      }
    `;

    document.head.appendChild(style);
  }
}
