---
// src/pages/contribute/tool.astro 
import BaseLayout from '../../layouts/BaseLayout.astro';
import { withAuth } from '../../utils/auth.js';
import { getToolsData } from '../../utils/dataService.js';

export const prerender = false;

const authResult = await withAuth(Astro, 'contributions');
if (authResult instanceof Response) {
  return authResult;
}

const { authenticated, userEmail, userId } = authResult;

const data = await getToolsData();
const domains = data.domains;
const phases = data.phases;
const domainAgnosticSoftware = data['domain-agnostic-software'] || [];
const existingTools = data.tools;

const editToolName = Astro.url.searchParams.get('edit');
const editTool = editToolName ? existingTools.find(tool => tool.name === editToolName) : null;
const isEdit = !!editTool;

const allTags = [...new Set(existingTools.flatMap(tool => tool.tags || []))].sort();
const allSoftwareAndMethods = existingTools
  .filter(tool => tool.type === 'software' || tool.type === 'method')
  .map(tool => tool.name)
  .sort();
const allConcepts = existingTools
  .filter(tool => tool.type === 'concept')
  .map(tool => tool.name)
  .sort();
---

<BaseLayout title={isEdit ? `Edit ${editTool?.name}` : 'Contribute Tool'}>
  <div class="container" style="max-width: 900px; margin: 0 auto; padding: 2rem 1rem;">
    
    <div class="header-center header-primary rounded-xl">
      <h1 style="margin-bottom: 1rem; font-size: 2rem;">{isEdit ? `Edit: ${editTool?.name}` : 'Tool / Methode / Konzept beitragen'}</h1>
      <p style="margin: 0.5rem 0; opacity: 0.9;">
        {isEdit 
          ? 'Passt die Informationen für dieses Tool/Methode/Konzept an. Dein Beitrag wird als Git-Issue veröffentlicht.'
          : 'Füge ein neues Tool, Methode oder Konzept in unsere Datenbank hinzu. Dein Beitrag wird als Git-Issue veröffentlicht.'
        }
      </p>
      {userEmail && <p style="margin: 0.5rem 0; opacity: 0.8;"><strong>Eingeloggt als:</strong> {userEmail}</p>}
    </div>

    <div id="validation-errors" class="card" style="display: none; background-color: var(--color-error); color: white; margin-bottom: 2rem;">
      <h3 style="margin: 0 0 1rem 0;">⚠️ Please fix the following issues:</h3>
      <ul id="error-list" style="margin: 0; padding-left: 1.5rem;"></ul>
    </div>

    <div class="card">
      <form id="contribution-form" novalidate style="padding: 2rem;">
        
        <div style="border: 1px solid var(--color-border); border-radius: 0.5rem; padding: 1.5rem; margin-bottom: 2rem;">
          <h3 style="margin: 0 0 1.5rem 0; color: var(--color-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem;">Grundlegende Infos</h3>
          
          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1.5rem;">
            <div>
              <label for="type" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Typ <span style="color: var(--color-error);">*</span></label>
              <select id="type" name="type" required>
                <option value="">Auswählen...</option>
                <option value="software" selected={editTool?.type === 'software'}>Software/Tool</option>
                <option value="method" selected={editTool?.type === 'method'}>Methode/Prozess</option>
                <option value="concept" selected={editTool?.type === 'concept'}>Konzept/Wissen</option>
              </select>
            </div>
            
            <div>
              <label for="skillLevel" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Skill Level <span style="color: var(--color-error);">*</span></label>
              <select id="skillLevel" name="skillLevel" required>
                <option value="">Auswählen...</option>
                <option value="novice" selected={editTool?.skillLevel === 'novice'}>Novice</option>
                <option value="beginner" selected={editTool?.skillLevel === 'beginner'}>Beginner</option>
                <option value="intermediate" selected={editTool?.skillLevel === 'intermediate'}>Intermediate</option>
                <option value="advanced" selected={editTool?.skillLevel === 'advanced'}>Advanced</option>
                <option value="expert" selected={editTool?.skillLevel === 'expert'}>Expert</option>
              </select>
            </div>
          </div>

          <div style="margin-bottom: 1.5rem;">
            <label for="name" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Name <span style="color: var(--color-error);">*</span></label>
            <input type="text" id="name" name="name" value={editTool?.name || ''} 
                   placeholder="Tool/Method/Concept name" maxlength="100" required />
          </div>

          <div style="margin-bottom: 1.5rem;">
            <label for="icon" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Icon (Emoji)</label>
            <input type="text" id="icon" name="icon" value={editTool?.icon || ''} 
                   placeholder="📦 (optional)" maxlength="10" />
          </div>

          <div style="margin-bottom: 1.5rem;">
            <label for="description" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Beschreibung <span style="color: var(--color-error);">*</span></label>
            <textarea id="description" name="description" rows="4" maxlength="1000" required
                      placeholder="Klare, kurze Beschreibung, was dein Tool/Methode/Konzept tut, was sein Zweck ist und was es einzigartig macht.">{editTool?.description || ''}</textarea>
            <div style="text-align: right; font-size: 0.75rem; color: var(--color-text-secondary); margin-top: 0.25rem;">
              <span id="description-count">0</span>/1000
            </div>
          </div>

          <div style="margin-bottom: 1.5rem;">
            <label for="url" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Primary URL <span style="color: var(--color-error);">*</span></label>
            <input type="url" id="url" name="url" value={editTool?.url || ''} 
                   placeholder="https://example.com" required />
            <small style="display: block; margin-top: 0.25rem; color: var(--color-text-secondary); font-size: 0.8125rem;">Homepage, Dokumentation, oder Primärquelle</small>
          </div>
        </div>

        <div style="border: 1px solid var(--color-border); border-radius: 0.5rem; padding: 1.5rem; margin-bottom: 2rem;">
          <h3 style="margin: 0 0 1.5rem 0; color: var(--color-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem;">Kategorien</h3>
          
          <div class="grid-2 gap-8">
            <div>
              <label style="display: block; margin-bottom: 0.75rem; font-weight: 600;">Forensische Domänen</label>
              <div style="display: grid; gap: 0.5rem;">
                {domains.map(domain => (
                  <label class="checkbox-wrapper">
                    <input type="checkbox" name="domains" value={domain.id} 
                           checked={editTool?.domains?.includes(domain.id)} />
                    <span>{domain.name}</span>
                  </label>
                ))}
              </div>
            </div>
            
            <div>
              <label style="display: block; margin-bottom: 0.75rem; font-weight: 600;">Phasen der Ermittlung</label>
              <div style="display: grid; gap: 0.5rem;">
                {phases.map(phase => (
                  <label class="checkbox-wrapper">
                    <input type="checkbox" name="phases" value={phase.id} 
                           checked={editTool?.phases?.includes(phase.id)} />
                    <span>{phase.name}</span>
                  </label>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div id="software-fields" style="border: 1px solid var(--color-border); border-radius: 0.5rem; padding: 1.5rem; margin-bottom: 2rem; display: none;">
          <h3 style="margin: 0 0 1.5rem 0; color: var(--color-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem;">Software Details</h3>
          
          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-bottom: 1.5rem;">
            <div>
              <label style="display: block; margin-bottom: 0.75rem; font-weight: 600;">Betrieb auf: <span id="platforms-required" style="color: var(--color-error);">*</span></label>
              <div style="display: grid; gap: 0.5rem;">
                {['Windows', 'macOS', 'Linux', 'Web', 'Mobile', 'Cross-platform'].map(platform => (
                  <label class="checkbox-wrapper">
                    <input type="checkbox" name="platforms" value={platform} 
                           checked={editTool?.platforms?.includes(platform)} />
                    <span>{platform}</span>
                  </label>
                ))}
              </div>
            </div>
            
            <div>
              <label for="license" style="display: block; margin-bottom: 0.75rem; font-weight: 600;">Lizenzmodell <span id="license-required" style="color: var(--color-error);">*</span></label>
              <input type="text" id="license" name="license" value={editTool?.license || ''} 
                     placeholder="MIT, Apache 2.0, GPL v3, Proprietary" list="license-options" />
              <datalist id="license-options">
                <option value="MIT" />
                <option value="Apache 2.0" />
                <option value="GPL v3" />
                <option value="BSD-3-Clause" />
                <option value="Proprietary" />
                <option value="Open Source" />
              </datalist>
            </div>
          </div>

          <div class="grid-2 gap-8">
            <div>
              <label for="accessType" style="display: block; margin-bottom: 0.75rem; font-weight: 600;">Zugriff über:</label>
              <select id="accessType" name="accessType">
                <option value="">Select access type...</option>
                <option value="download" selected={editTool?.accessType === 'download'}>Download</option>
                <option value="web" selected={editTool?.accessType === 'web'}>Web Application</option>
                <option value="api" selected={editTool?.accessType === 'api'}>API</option>
                <option value="cli" selected={editTool?.accessType === 'cli'}>Command Line</option>
                <option value="service" selected={editTool?.accessType === 'service'}>Service</option>
              </select>
            </div>
            
            <div>
              <label style="display: block; margin-bottom: 0.75rem; font-weight: 600;">Domänenübergreifende Kategorien</label>
              <div style="display: grid; gap: 0.5rem;">
                {domainAgnosticSoftware.map(cat => (
                  <label class="checkbox-wrapper">
                    <input type="checkbox" name="domainAgnostic" value={cat.id} 
                           checked={editTool?.['domain-agnostic-software']?.includes(cat.id)} />
                    <span>{cat.name}</span>
                  </label>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div id="relations-fields" style="border: 1px solid var(--color-border); border-radius: 0.5rem; padding: 1.5rem; margin-bottom: 2rem; display: none;">
          <h3 style="margin: 0 0 1.5rem 0; color: var(--color-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem;">Verwandte Tools & Konzepte</h3>
          
          <div style="display: grid; gap: 1.5rem;">
            <div id="related-concepts-section">
              <label for="related-concepts-input" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Verwandte Konzepte</label>
              <input type="text" id="related-concepts-input" placeholder="Beginne zu tippen, um Konzepte zu finden..." />
              <input type="hidden" id="related-concepts-hidden" name="relatedConcepts" value={editTool?.related_concepts?.join(', ') || ''} />
              <small style="display: block; margin-top: 0.25rem; color: var(--color-text-secondary); font-size: 0.8125rem;">
                Konzepte, die mit diesem Tool/Methode in Verbindung stehen
              </small>
            </div>
            
            <div id="related-software-section">
              <label for="related-software-input" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Verwandte Software & Methoden</label>
              <input type="text" id="related-software-input" placeholder="Beginne zu tippen, um Software/Methoden zu finden..." />
              <input type="hidden" id="related-software-hidden" name="relatedSoftware" value={editTool?.related_software?.join(', ') || ''} />
              <small style="display: block; margin-top: 0.25rem; color: var(--color-text-secondary); font-size: 0.8125rem;">
                Software oder Methoden, die oft zusammen mit diesem Tool verwendet werden
              </small>
            </div>
          </div>
        </div>

        <div style="border: 1px solid var(--color-border); border-radius: 0.5rem; padding: 1.5rem; margin-bottom: 2rem;">
          <h3 style="margin: 0 0 1.5rem 0; color: var(--color-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem;">Zusatzinfos</h3>
          
          <div style="margin-bottom: 1.5rem;">
            <label for="tags-input" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Tags</label>
            <input type="text" id="tags-input" placeholder="Beginne zu tippen, um Tags hinzuzufügen..." />
            <input type="hidden" id="tags-hidden" name="tags" value={editTool?.tags?.join(', ') || ''} />
            <small style="display: block; margin-top: 0.25rem; color: var(--color-text-secondary); font-size: 0.8125rem;">
              Passende Begriffe, nach denen ihr suchen würdet
            </small>
          </div>

          <div style="margin-bottom: 1.5rem;">
            <label class="checkbox-wrapper">
              <input type="checkbox" id="knowledgebase" name="knowledgebase" 
                     checked={editTool?.knowledgebase} />
              <span>Der Beitrag soll später einen Knowledgebase-Artikel haben</span>
            </label>
          </div>

          <div>
            <label for="reason" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Grund für den Beitrag (Optional)</label>
            <textarea id="reason" name="reason" rows="3" maxlength="500"
                      placeholder="Hier kannst du noch deine Motivation und sonstige Infos beschreiben."></textarea>
            <div style="text-align: right; font-size: 0.75rem; color: var(--color-text-secondary); margin-top: 0.25rem;">
              <span id="reason-count">0</span>/500
            </div>
          </div>
          <div style="margin-bottom: 1.5rem;">
            <label for="contact" style="display: block; margin-bottom: 0.5rem; font-weight: 600;">Kontakt (Optional)</label>
            <input type="text" id="contact" name="contact" 
                  placeholder="Discord: @username, Telegram: @username, oder andere Kontaktmöglichkeit" 
                  class="form-input" />
            <small style="display: block; margin-top: 0.25rem; color: var(--color-text-secondary); font-size: 0.8125rem;">
              Wird nur im Git-Issue angezeigt, falls Nachfragen entstehen
            </small>
          </div>
        </div>

        <div style="border: 1px solid var(--color-border); border-radius: 0.5rem; padding: 1.5rem; margin-bottom: 2rem;">
          <h3 style="margin: 0 0 1.5rem 0; color: var(--color-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem;">Preview</h3>
          <div style="border: 1px solid var(--color-border); border-radius: 0.375rem; overflow: hidden;">
            <pre id="yaml-preview" style="background: var(--color-bg-secondary); color: var(--color-text); padding: 1rem; margin: 0; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 0.8125rem; line-height: 1.4; overflow-x: auto; max-height: 300px;"># YAML preview will appear here</pre>
          </div>
        </div>

        <div style="display: flex; gap: 1rem; justify-content: flex-end; margin-top: 2rem; padding-top: 2rem; border-top: 1px solid var(--color-border);">
          <a href="/" class="btn btn-secondary">Cancel</a>
          <button type="submit" id="submit-btn" class="btn btn-primary">
            <span id="submit-text">{isEdit ? 'Update Tool' : 'Submit Contribution'}</span>
            <span id="submit-spinner" style="display: none; margin-left: 0.5rem;">⏳</span>
          </button>
        </div>
      </form>
    </div>

    <div id="success-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); z-index: 1000; align-items: center; justify-content: center;">
      <div class="card" style="max-width: 500px; width: 90%; margin: 2rem; text-align: center;">
        <div style="font-size: 3rem; margin-bottom: 1rem;">✅</div>
        <h3 style="margin-bottom: 1rem;">Contribution Submitted!</h3>
        <p id="success-message" style="margin-bottom: 1.5rem;">Your contribution has been submitted successfully.</p>
        <div style="display: flex; gap: 1rem; justify-content: center;">
          <a id="pr-link" href="#" target="_blank" class="btn btn-primary hidden">View Pull Request</a>
          <a href="/" class="btn btn-secondary">Back to Home</a>
        </div>
      </div>
    </div>
  </div>
</BaseLayout>

<script define:vars={{ isEdit, editTool, domains, phases, domainAgnosticSoftware, allTags, allSoftwareAndMethods, allConcepts }}>
class AutocompleteManager {
  constructor(inputElement, dataSource, options = {}) {
    this.input = inputElement;
    this.dataSource = dataSource;
    this.options = {
      minLength: 1,
      maxResults: 10,
      placeholder: 'Type to search...',
      allowMultiple: false,
      separator: ', ',
      filterFunction: this.defaultFilter.bind(this),
      renderFunction: this.defaultRender.bind(this),
      ...options
    };
    
    this.isOpen = false;
    this.selectedIndex = -1;
    this.filteredData = [];
    this.selectedItems = new Set();
    
    this.init();
  }
  
  init() {
    this.createDropdown();
    this.bindEvents();
    
    if (this.options.allowMultiple) {
      this.initMultipleMode();
    }
  }
  
  createDropdown() {
    this.dropdown = document.createElement('div');
    this.dropdown.className = 'autocomplete-dropdown';
    
    this.input.parentNode.style.position = 'relative';
    this.input.parentNode.insertBefore(this.dropdown, this.input.nextSibling);
  }
  
  bindEvents() {
    this.input.addEventListener('input', (e) => {
      this.handleInput(e.target.value);
    });
    
    this.input.addEventListener('keydown', (e) => {
      this.handleKeydown(e);
    });
    
    this.input.addEventListener('focus', () => {
      if (this.input.value.length >= this.options.minLength) {
        this.showDropdown();
      }
    });
    
    this.input.addEventListener('blur', (e) => {
      setTimeout(() => {
        if (!this.dropdown.contains(document.activeElement)) {
          this.hideDropdown();
        }
      }, 150);
    });
    
    document.addEventListener('click', (e) => {
      if (!this.input.contains(e.target) && !this.dropdown.contains(e.target)) {
        this.hideDropdown();
      }
    });
  }
  
  initMultipleMode() {
    this.selectedContainer = document.createElement('div');
    this.selectedContainer.className = 'autocomplete-selected';
    
    this.input.parentNode.insertBefore(this.selectedContainer, this.input);
    this.updateSelectedDisplay();
  }
  
  handleInput(value) {
    if (value.length >= this.options.minLength) {
      this.filteredData = this.options.filterFunction(value);
      this.selectedIndex = -1;
      this.renderDropdown();
      this.showDropdown();
    } else {
      this.hideDropdown();
    }
  }
  
  handleKeydown(e) {
    if (!this.isOpen) return;
    
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredData.length - 1);
        this.updateHighlight();
        break;
        
      case 'ArrowUp':
        e.preventDefault();
        this.selectedIndex = Math.max(this.selectedIndex - 1, -1);
        this.updateHighlight();
        break;
        
      case 'Enter':
        e.preventDefault();
        if (this.selectedIndex >= 0) {
          this.selectItem(this.filteredData[this.selectedIndex]);
        }
        break;
        
      case 'Escape':
        this.hideDropdown();
        break;
    }
  }
  
  defaultFilter(query) {
    const searchTerm = query.toLowerCase();
    return this.dataSource
      .filter(item => {
        const text = typeof item === 'string' ? item : item.name || item.label || item.toString();
        return text.toLowerCase().includes(searchTerm) && 
               (!this.options.allowMultiple || !this.selectedItems.has(text));
      })
      .slice(0, this.options.maxResults);
  }
  
  defaultRender(item) {
    const text = typeof item === 'string' ? item : item.name || item.label || item.toString();
    return `<div class="autocomplete-item">${this.escapeHtml(text)}</div>`;
  }
  
  renderDropdown() {
    if (this.filteredData.length === 0) {
      this.dropdown.innerHTML = '<div class="autocomplete-no-results">No results found</div>';
      return;
    }
    
    this.dropdown.innerHTML = this.filteredData
      .map((item, index) => {
        const content = this.options.renderFunction(item);
        return `<div class="autocomplete-option" data-index="${index}">${content}</div>`;
      })
      .join('');
    
    this.dropdown.querySelectorAll('.autocomplete-option').forEach((option, index) => {
      option.addEventListener('click', () => {
        this.selectItem(this.filteredData[index]);
      });
      
      option.addEventListener('mouseenter', () => {
        this.selectedIndex = index;
        this.updateHighlight();
      });
    });
  }
  
  updateHighlight() {
    this.dropdown.querySelectorAll('.autocomplete-option').forEach((option, index) => {
      option.style.backgroundColor = index === this.selectedIndex 
        ? 'var(--color-bg-secondary)' 
        : 'transparent';
    });
  }
  
  selectItem(item) {
    const text = typeof item === 'string' ? item : item.name || item.label || item.toString();
    
    if (this.options.allowMultiple) {
      this.selectedItems.add(text);
      this.updateSelectedDisplay();
      this.updateInputValue();
      this.input.value = '';
    } else {
      this.input.value = text;
      this.hideDropdown();
    }
    
    this.input.dispatchEvent(new CustomEvent('autocomplete:select', {
      detail: { item, text, selectedItems: Array.from(this.selectedItems) }
    }));
  }
  
  removeItem(text) {
    if (this.options.allowMultiple) {
      this.selectedItems.delete(text);
      this.updateSelectedDisplay();
      this.updateInputValue();
    }
  }
  
  updateSelectedDisplay() {
    if (!this.options.allowMultiple || !this.selectedContainer) return;
    
    this.selectedContainer.innerHTML = Array.from(this.selectedItems)
      .map(item => `
        <span class="autocomplete-tag">
          ${this.escapeHtml(item)}
          <button type="button" class="autocomplete-remove" data-item="${this.escapeHtml(item)}">×</button>
        </span>
      `)
      .join('');
    
    this.selectedContainer.querySelectorAll('.autocomplete-remove').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.preventDefault();
        this.removeItem(btn.getAttribute('data-item'));
      });
    });
  }
  
  updateInputValue() {
    if (this.options.allowMultiple && this.options.hiddenInput) {
      this.options.hiddenInput.value = Array.from(this.selectedItems).join(this.options.separator);
    }
  }
  
  showDropdown() {
    this.dropdown.style.display = 'block';
    this.isOpen = true;
  }
  
  hideDropdown() {
    this.dropdown.style.display = 'none';
    this.isOpen = false;
    this.selectedIndex = -1;
  }
  
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
  
  setDataSource(newDataSource) {
    this.dataSource = newDataSource;
  }
  
  getSelectedItems() {
    return Array.from(this.selectedItems);
  }
  
  setSelectedItems(items) {
    this.selectedItems = new Set(items);
    if (this.options.allowMultiple) {
      this.updateSelectedDisplay();
      this.updateInputValue();
    }
  }
  
  destroy() {
    if (this.dropdown && this.dropdown.parentNode) {
      this.dropdown.parentNode.removeChild(this.dropdown);
    }
    if (this.selectedContainer && this.selectedContainer.parentNode) {
      this.selectedContainer.parentNode.removeChild(this.selectedContainer);
    }
  }
}

console.log('[FORM] Script loaded, initializing...');

class ContributionForm {
  constructor() {
    this.isEdit = isEdit;
    this.editTool = editTool;
    this.elements = {};
    this.isSubmitting = false;
    this.autocompleteManagers = new Map();
    this.init();
  }

  init() {
    console.log('[FORM] Starting initialization...');
    
    this.elements = {
      form: document.getElementById('contribution-form'),
      submitBtn: document.getElementById('submit-btn'),
      submitText: document.getElementById('submit-text'),
      submitSpinner: document.getElementById('submit-spinner'),
      typeSelect: document.getElementById('type'),
      nameInput: document.getElementById('name'),
      descriptionTextarea: document.getElementById('description'),
      reasonTextarea: document.getElementById('reason'),
      skillLevelSelect: document.getElementById('skillLevel'),
      urlInput: document.getElementById('url'),
      yamlPreview: document.getElementById('yaml-preview'),
      successModal: document.getElementById('success-modal'),
      softwareFields: document.getElementById('software-fields'),
      relationsFields: document.getElementById('relations-fields'),
      descriptionCount: document.getElementById('description-count'),
      reasonCount: document.getElementById('reason-count'),
      validationErrors: document.getElementById('validation-errors'),
      errorList: document.getElementById('error-list'),
      platformsRequired: document.getElementById('platforms-required'),
      licenseRequired: document.getElementById('license-required'),
      licenseInput: document.getElementById('license'),
      tagsInput: document.getElementById('tags-input'),
      tagsHidden: document.getElementById('tags-hidden'),
      relatedConceptsInput: document.getElementById('related-concepts-input'),
      relatedConceptsHidden: document.getElementById('related-concepts-hidden'),
      relatedSoftwareInput: document.getElementById('related-software-input'),
      relatedSoftwareHidden: document.getElementById('related-software-hidden')
    };

    if (!this.elements.form || !this.elements.submitBtn) {
      console.error('[FORM] Critical elements missing!');
      return;
    }

    if (this.elements.form.hasAttribute('data-form-initialized')) {
      console.log('[FORM] Form already initialized, skipping...');
      return;
    }

    this.elements.form.setAttribute('data-form-initialized', 'true');

    console.log('[FORM] Setting up handlers...');
    this.setupEventListeners();
    this.setupAutocomplete();
    this.updateFieldVisibility();
    this.setupCharacterCounters();
    this.updateYAMLPreview();

    console.log('[FORM] Initialization complete!');
  }

  setupAutocomplete() {
    if (this.elements.tagsInput && this.elements.tagsHidden) {
      const tagsManager = new AutocompleteManager(this.elements.tagsInput, allTags, {
        allowMultiple: true,
        hiddenInput: this.elements.tagsHidden,
        placeholder: 'Beginne zu tippen, um Tags hinzuzufügen...'
      });
      
      if (this.editTool?.tags) {
        tagsManager.setSelectedItems(this.editTool.tags);
      }
      
      this.autocompleteManagers.set('tags', tagsManager);
    }

    if (this.elements.relatedConceptsInput && this.elements.relatedConceptsHidden) {
      const conceptsManager = new AutocompleteManager(this.elements.relatedConceptsInput, allConcepts, {
        allowMultiple: true,
        hiddenInput: this.elements.relatedConceptsHidden,
        placeholder: 'Beginne zu tippen, um Konzepte zu finden...'
      });
      
      if (this.editTool?.related_concepts) {
        conceptsManager.setSelectedItems(this.editTool.related_concepts);
      }
      
      this.autocompleteManagers.set('relatedConcepts', conceptsManager);
    }

    if (this.elements.relatedSoftwareInput && this.elements.relatedSoftwareHidden) {
      const softwareManager = new AutocompleteManager(this.elements.relatedSoftwareInput, allSoftwareAndMethods, {
        allowMultiple: true,
        hiddenInput: this.elements.relatedSoftwareHidden,
        placeholder: 'Beginne zu tippen, um Software/Methoden zu finden...'
      });
      
      if (this.editTool?.related_software) {
        softwareManager.setSelectedItems(this.editTool.related_software);
      }
      
      this.autocompleteManagers.set('relatedSoftware', softwareManager);
    }

    Object.values(this.autocompleteManagers).forEach(manager => {
      if (manager.input) {
        manager.input.addEventListener('autocomplete:select', () => {
          this.updateYAMLPreview();
        });
      }
    });
  }

  setupEventListeners() {
    this.elements.typeSelect.addEventListener('change', () => {
      this.updateFieldVisibility();
      this.updateYAMLPreview();
    });

    this.elements.form.addEventListener('input', () => {
      this.debounce(() => this.updateYAMLPreview(), 300);
    });

    this.elements.form.addEventListener('change', () => {
      this.updateYAMLPreview();
    });

    this.elements.form.addEventListener('submit', (e) => {
      e.preventDefault();
      e.stopPropagation();
      
      if (this.isSubmitting) {
        console.log('[FORM] Submission already in progress, ignoring...');
        return;
      }
      
      this.handleSubmit();
    });

    console.log('[FORM] Event listeners attached');
  }

  updateFieldVisibility() {
    const type = this.elements.typeSelect.value;
    
    this.elements.softwareFields.style.display = type === 'software' ? 'block' : 'none';
    
    this.elements.relationsFields.style.display = 'block';
    
    if (this.elements.platformsRequired) {
      this.elements.platformsRequired.style.display = type === 'software' ? 'inline' : 'none';
    }
    if (this.elements.licenseRequired) {
      this.elements.licenseRequired.style.display = type === 'software' ? 'inline' : 'none';
    }

    const conceptsSection = document.getElementById('related-concepts-section');
    const softwareSection = document.getElementById('related-software-section');
    if (conceptsSection) conceptsSection.style.display = 'block';
    if (softwareSection) softwareSection.style.display = 'block';

    console.log('[FORM] Updated visibility for type:', type || '(no type selected)');
  }

  setupCharacterCounters() {
    const counters = [
      { element: this.elements.descriptionTextarea, counter: this.elements.descriptionCount, max: 1000 },
      { element: this.elements.reasonTextarea, counter: this.elements.reasonCount, max: 500 }
    ];

    counters.forEach(({ element, counter, max }) => {
      if (element && counter) {
        const updateCounter = () => {
          const count = element.value.length;
          counter.textContent = count;
          counter.style.color = count > max * 0.9 ? 'var(--color-warning)' : 'var(--color-text-secondary)';
        };
        
        element.addEventListener('input', updateCounter);
        updateCounter();
      }
    });
  }

  updateYAMLPreview() {
    if (!this.elements.yamlPreview) return;

    try {
      const formData = new FormData(this.elements.form);
      
      const tool = {
        name: formData.get('name') || 'Tool Name',
        type: formData.get('type') || 'software',
        description: formData.get('description') || 'Tool description',
        domains: formData.getAll('domains'),
        phases: formData.getAll('phases'),
        skillLevel: formData.get('skillLevel') || 'intermediate',
        url: formData.get('url') || 'https://example.com'
      };

      if (formData.get('icon')) {
        tool.icon = formData.get('icon');
      }

      if (tool.type === 'software') {
        tool.platforms = formData.getAll('platforms');
        tool.license = formData.get('license') || 'Unknown';
        if (formData.get('accessType')) {
          tool.accessType = formData.get('accessType');
        }
        const domainAgnostic = formData.getAll('domainAgnostic');
        if (domainAgnostic.length > 0) {
          tool['domain-agnostic-software'] = domainAgnostic;
        }
      }

      if (formData.has('knowledgebase')) {
        tool.knowledgebase = true;
      }

      const tagsValue = this.elements.tagsHidden?.value || '';
      if (tagsValue) {
        tool.tags = tagsValue.split(',').map(t => t.trim()).filter(Boolean);
      }

      const relatedConceptsValue = this.elements.relatedConceptsHidden?.value || '';
      if (relatedConceptsValue) {
        tool.related_concepts = relatedConceptsValue.split(',').map(t => t.trim()).filter(Boolean);
      }

      const relatedSoftwareValue = this.elements.relatedSoftwareHidden?.value || '';
      if (relatedSoftwareValue) {
        tool.related_software = relatedSoftwareValue.split(',').map(t => t.trim()).filter(Boolean);
      }

      const yaml = this.generateYAML(tool);
      this.elements.yamlPreview.textContent = yaml;

    } catch (error) {
      console.error('[FORM] YAML preview error:', error);
      this.elements.yamlPreview.textContent = '# Error generating preview';
    }
  }

  generateYAML(tool) {
    const lines = [];
    
    lines.push(`name: "${tool.name}"`);
    if (tool.icon) lines.push(`icon: "${tool.icon}"`);
    lines.push(`type: ${tool.type}`);
    lines.push(`description: "${tool.description}"`);
    lines.push(`domains: [${tool.domains.map(d => `"${d}"`).join(', ')}]`);
    lines.push(`phases: [${tool.phases.map(p => `"${p}"`).join(', ')}]`);
    lines.push(`skillLevel: ${tool.skillLevel}`);
    lines.push(`url: "${tool.url}"`);
    
    if (tool.platforms && tool.platforms.length > 0) {
      lines.push(`platforms: [${tool.platforms.map(p => `"${p}"`).join(', ')}]`);
    }
    if (tool.license) lines.push(`license: "${tool.license}"`);
    if (tool.accessType) lines.push(`accessType: ${tool.accessType}`);
    if (tool['domain-agnostic-software']) {
      lines.push(`domain-agnostic-software: [${tool['domain-agnostic-software'].map(c => `"${c}"`).join(', ')}]`);
    }
    if (tool.knowledgebase) lines.push(`knowledgebase: true`);
    if (tool.tags && tool.tags.length > 0) {
      lines.push(`tags: [${tool.tags.map(t => `"${t}"`).join(', ')}]`);
    }
    if (tool.related_concepts && tool.related_concepts.length > 0) {
      lines.push(`related_concepts: [${tool.related_concepts.map(c => `"${c}"`).join(', ')}]`);
    }
    if (tool.related_software && tool.related_software.length > 0) {
      lines.push(`related_software: [${tool.related_software.map(s => `"${s}"`).join(', ')}]`);
    }

    return lines.join('\n');
  }

  validateForm() {
    const errors = [];
    const formData = new FormData(this.elements.form);

    const name = formData.get('name')?.trim();
    if (!name) {
      errors.push('Tool name is required');
    }

    const description = formData.get('description')?.trim();
    if (!description) {
      errors.push('Description is required');
    } else if (description.length < 10) {
      errors.push('Description must be at least 10 characters long');
    }

    const skillLevel = formData.get('skillLevel');
    if (!skillLevel) {
      errors.push('Skill level is required');
    }

    const type = formData.get('type');
    if (!type) {
      errors.push('Type is required');
    }

    const url = formData.get('url')?.trim();
    if (!url) {
      errors.push('Primary URL is required');
    } else {
      try {
        new URL(url);
      } catch {
        errors.push('Primary URL must be a valid URL');
      }
    }

    if (type === 'software') {
      const platforms = formData.getAll('platforms');
      if (platforms.length === 0) {
        errors.push('At least one platform is required for software');
      }

      const license = formData.get('license')?.trim();
      if (!license) {
        errors.push('License is required for software');
      }
    }

    return errors;
  }

  showValidationErrors(errors) {
    if (errors.length === 0) {
      this.elements.validationErrors.style.display = 'none';
      return;
    }

    this.elements.errorList.innerHTML = '';
    
    errors.forEach(error => {
      const li = document.createElement('li');
      li.textContent = error;
      this.elements.errorList.appendChild(li);
    });

    this.elements.validationErrors.style.display = 'block';
    
    this.elements.validationErrors.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }

  async handleSubmit() {
    console.log('[FORM] Submit handler called!');

    if (this.isSubmitting) {
      console.log('[FORM] Already submitting, aborting...');
      return;
    }

    this.isSubmitting = true;

    const validationErrors = this.validateForm();
    if (validationErrors.length > 0) {
      console.log('[FORM] Validation failed:', validationErrors);
      this.showValidationErrors(validationErrors);
      this.isSubmitting = false;
      return;
    }

    this.elements.validationErrors.style.display = 'none';

    this.elements.submitBtn.disabled = true;
    this.elements.submitText.textContent = this.isEdit ? 'Updating...' : 'Submitting...';
    this.elements.submitSpinner.style.display = 'inline';

    try {
      const formData = new FormData(this.elements.form);
      
      const submission = {
        action: this.isEdit ? 'edit' : 'add',
        tool: {
          name: formData.get('name'),
          type: formData.get('type'),
          description: formData.get('description'),
          domains: formData.getAll('domains'),
          phases: formData.getAll('phases'),
          skillLevel: formData.get('skillLevel'),
          url: formData.get('url'),
          tags: []
        },
        metadata: {
          reason: formData.get('reason') || '',
          contact: formData.get('contact') || ''
        }
      };

      const tagsValue = this.elements.tagsHidden?.value || '';
      if (tagsValue) {
        submission.tool.tags = tagsValue.split(',').map(t => t.trim()).filter(Boolean);
      }

      const relatedConceptsValue = this.elements.relatedConceptsHidden?.value || '';
      if (relatedConceptsValue) {
        submission.tool.related_concepts = relatedConceptsValue.split(',').map(t => t.trim()).filter(Boolean);
      }

      const relatedSoftwareValue = this.elements.relatedSoftwareHidden?.value || '';
      if (relatedSoftwareValue) {
        submission.tool.related_software = relatedSoftwareValue.split(',').map(t => t.trim()).filter(Boolean);
      }

      if (formData.get('icon')) submission.tool.icon = formData.get('icon');
      if (formData.has('knowledgebase')) submission.tool.knowledgebase = true;

      if (submission.tool.type === 'software') {
        submission.tool.platforms = formData.getAll('platforms');
        submission.tool.license = formData.get('license');
        if (formData.get('accessType')) {
          submission.tool.accessType = formData.get('accessType');
        }
        const domainAgnostic = formData.getAll('domainAgnostic');
        if (domainAgnostic.length > 0) {
          submission.tool['domain-agnostic-software'] = domainAgnostic;
        }
      }

      console.log('[FORM] Sending submission:', submission);

      const response = await fetch('/api/contribute/tool', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(submission)
      });

      console.log('[FORM] Response status:', response.status);
      const result = await response.json();
      console.log('[FORM] Response data:', result);

      if (result.success) {
        this.showSuccess(result);
      } else {
        throw new Error(result.error || 'Submission failed');
      }

    } catch (error) {
      console.error('[FORM] Submission error:', error);
      alert(`Submission failed: ${error.message}\n\nPlease try again or contact support if the problem persists.`);
    } finally {
      this.isSubmitting = false;
      this.elements.submitBtn.disabled = false;
      this.elements.submitText.textContent = this.isEdit ? 'Update Tool' : 'Submit Contribution';
      this.elements.submitSpinner.style.display = 'none';
    }
  }

  showSuccess(result) {
    const successMessage = document.getElementById('success-message');
    if (successMessage) {
      successMessage.textContent = `Your ${this.isEdit ? 'update' : 'contribution'} has been submitted as an issue and will be reviewed by maintainers.`;
    }

    if (result.issueUrl) {
      const prLink = document.getElementById('pr-link');
      if (prLink) {
        prLink.href = result.issueUrl;
        prLink.textContent = 'View Issue';
        prLink.style.display = 'inline-flex';
      }
    }

    this.elements.successModal.style.display = 'flex';
  }

  debounce(func, wait) {
    let timeout;
    return (...args) => {
      clearTimeout(timeout);
      timeout = setTimeout(() => func.apply(this, args), wait);
    };
  }

  destroy() {
    this.autocompleteManagers.forEach(manager => {
      manager.destroy();
    });
    this.autocompleteManagers.clear();
  }
}

function initializeForm() {
  const form = document.getElementById('contribution-form');
  if (!form) {
    console.error('[FORM] Form element not found!');
    return;
  }

  if (form.hasAttribute('data-form-initialized')) {
    console.log('[FORM] Form already initialized');
    return;
  }

  console.log('[FORM] Initializing form...');
  new ContributionForm();
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initializeForm);
} else {
  initializeForm();
}

console.log('[FORM] Script loaded successfully');
</script>
</BaseLayout>