---
//src/pages/knowledgebase.astro
import BaseLayout from '../layouts/BaseLayout.astro';
import { getCollection } from 'astro:content';
import { getToolsData } from '../utils/dataService.js';
import ContributionButton from '../components/ContributionButton.astro';
import { isGatedContentAuthRequired } from '../utils/auth.js';

const data = await getToolsData();
const allKnowledgebaseEntries = await getCollection('knowledgebase', (entry) => {
  return entry.data.published !== false;
});

const gatedContentAuthEnabled = isGatedContentAuthRequired();

const knowledgebaseEntries = allKnowledgebaseEntries.map((entry) => {
  const associatedTool = entry.data.tool_name 
    ? data.tools.find((tool: any) => tool.name === entry.data.tool_name)
    : null;
  
  return {
    slug: entry.slug,
    title: entry.data.title,
    description: entry.data.description,
    author: entry.data.author,
    last_updated: entry.data.last_updated,
    difficulty: entry.data.difficulty,
    categories: entry.data.categories || [],
    tags: entry.data.tags || [],
    gated_content: entry.data.gated_content || false, 
    tool_name: entry.data.tool_name,
    related_tools: entry.data.related_tools || [],
    associatedTool,
    
    name: entry.data.title,
    type: associatedTool?.type || 'article',
    icon: associatedTool?.icon || '📖',
    platforms: associatedTool?.platforms || [],
    skillLevel: entry.data.difficulty || associatedTool?.skillLevel || 'intermediate',
    phases: associatedTool?.phases || [],
    license: associatedTool?.license
  };
});

knowledgebaseEntries.sort((a: any, b: any) => a.title.localeCompare(b.title));

const gatedCount = knowledgebaseEntries.filter(entry => entry.gated_content).length;
const publicCount = knowledgebaseEntries.length - gatedCount;
---

<BaseLayout title="Knowledgebase" description="Extended documentation and insights for DFIR tools">
  <section class="section-padding">
    <div class="text-center mb-8 p-8 bg-secondary rounded-lg border">
      <h1 class="mb-4 text-2xl text-primary">Knowledgebase</h1>
      <p class="text-lg text-secondary mb-4">
        Erweiterte Dokumentation und Erkenntnisse
      </p>
      <p class="text-base text-secondary mb-6">
        Praktische Erfahrungen, Konfigurationshinweise und Lektionen aus der Praxis
      </p>
      
      {gatedContentAuthEnabled && gatedCount > 0 && (
        <div class="gated-content-info mb-4 p-3 rounded" style="background-color: var(--color-bg-secondary); border: 1px solid var(--color-border);">
          <div class="flex items-center justify-center gap-2 text-sm text-secondary">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
              <circle cx="12" cy="16" r="1"/>
              <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
            </svg>
            <span>
              {gatedCount} geschützte Artikel • {publicCount} öffentliche Artikel
            </span>
          </div>
          <p class="text-xs text-secondary mt-1">
            🔒 Geschützte Artikel erfordern Authentifizierung
          </p>
        </div>
      )}
      
      <div class="flex gap-4 justify-center flex-wrap">
        <ContributionButton type="write" variant="primary" text="Artikel schreiben" style="padding: 0.75rem 1.5rem;" />
        <button onclick="window.scrollToElementById('kb-entries')" class="btn btn-secondary" style="padding: 0.75rem 1.5rem;">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right: 0.5rem;">
            <circle cx="11" cy="11" r="8"/>
            <line x1="21" y1="21" x2="16.65" y2="16.65"/>
          </svg>
          Artikel durchsuchen
        </button>
      </div>
    </div>

    <div class="mb-6">
      <input 
        type="text" 
        id="kb-search" 
        placeholder="Knowledgebase durchsuchen..."
        class="w-full max-w-lg mx-auto block"
      />
    </div>

    <div class="text-center mb-6">
      <p class="text-secondary text-sm">
        <span id="visible-count">{knowledgebaseEntries.length}</span> von {knowledgebaseEntries.length} Einträgen
      </p>
    </div>

    <div class="max-w-6xl mx-auto">
      {knowledgebaseEntries.length === 0 ? (
        <div class="card text-center p-8">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-secondary)" stroke-width="1.5" style="margin: 0 auto 1rem;">
            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
            <polyline points="14 2 14 8 20 8"/>
            <line x1="16" y1="13" x2="8" y2="13"/>
            <line x1="16" y1="17" x2="8" y2="17"/>
            <polyline points="10 9 9 9 8 9"/>
          </svg>
          <h3 class="text-secondary mb-2">Noch keine Knowledgebase-Einträge</h3>
          <p class="text-secondary">
            Knowledgebase-Einträge werden automatisch angezeigt, sobald Artikel veröffentlicht werden.
          </p>
        </div>
      ) : (
        <div id="kb-entries" class="grid gap-4">
          {knowledgebaseEntries.map((entry: any, index: number) => {
            const hasAssociatedTool = !!entry.associatedTool;
            const hasValidProjectUrl = hasAssociatedTool && 
                                      entry.associatedTool.projectUrl !== undefined && 
                                      entry.associatedTool.projectUrl !== null && 
                                      entry.associatedTool.projectUrl !== "" && 
                                      entry.associatedTool.projectUrl.trim() !== "";
            
            const isMethod = hasAssociatedTool && entry.associatedTool.type === 'method';
            const isConcept = hasAssociatedTool && entry.associatedTool.type === 'concept';
            const isStandalone = !hasAssociatedTool;
            const isGated = entry.gated_content === true;
            
            const articleUrl = `/knowledgebase/${entry.slug}`;
            
            return (
              <article 
                class="kb-entry card cursor-pointer" 
                id={`kb-${entry.slug}`} 
                data-tool-name={entry.title.toLowerCase()}
                data-article-type={isStandalone ? 'standalone' : 'tool-associated'}
                data-gated={isGated}
                onclick={`window.location.href='${articleUrl}'`}
              >
                <!-- Card Header -->
                <div class="flex-between mb-3">
                  <div class="flex items-start gap-3 flex-1 min-w-0">
                    <span class="text-2xl flex-shrink-0">{entry.icon}</span>
                    <div class="min-w-0 flex-1">
                      <h3 class="text-lg font-semibold text-primary mb-1 leading-tight">
                        {entry.title}
                        {isGated && gatedContentAuthEnabled && (
                          <span class="gated-indicator ml-2" title="Geschützter Inhalt - Authentifizierung erforderlich">
                            🔒
                          </span>
                        )}
                      </h3>
                      <div class="flex gap-2 flex-wrap mb-2">
                        {isStandalone && <span class="badge" style="background-color: var(--color-accent); color: white;">Artikel</span>}
                        {isConcept && <span class="badge" style="background-color: var(--color-concept); color: white;">Konzept</span>}
                        {isMethod && <span class="badge" style="background-color: var(--color-method); color: white;">Methode</span>}
                        {hasAssociatedTool && !isMethod && !isConcept && <span class="badge badge-primary">Software</span>}
                        {hasValidProjectUrl && <span class="badge badge-primary">CC24-Server</span>}
                        {hasAssociatedTool && entry.associatedTool.license !== 'Proprietary' && !isMethod && !isConcept && <span class="badge badge-success">Open Source</span>}
                        <span class="badge badge-error">📖</span>
                        {isGated && gatedContentAuthEnabled && <span class="badge badge-warning">🔒</span>}
                      </div>
                    </div>
                  </div>
                  
                  <div class="flex gap-2 flex-shrink-0" onclick="event.stopPropagation();">
                    <a href={articleUrl} 
                       class="btn btn-primary btn-sm"
                       title={isGated && isGatedContentAuthRequired() ? "Geschützter Inhalt - Anmeldung erforderlich" : "Artikel öffnen"}>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right: 0.375rem;">
                        <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
                        <polyline points="15 3 21 3 21 9"/>
                        <line x1="10" y1="14" x2="21" y2="3"/>
                      </svg>
                      {isGated && gatedContentAuthEnabled ? 'Anmelden' : 'Öffnen'}
                    </a>
                    <button 
                      class="btn btn-secondary btn-sm"
                      onclick="window.shareArticle(this, '${articleUrl}', '${entry.title}')"
                      title="Artikel teilen"
                      style="font-size: 0.8125rem; padding: 0.5rem 0.75rem;"
                    >
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right: 0.375rem;">
                        <circle cx="18" cy="5" r="3"/>
                        <circle cx="6" cy="12" r="3"/>
                        <circle cx="18" cy="19" r="3"/>
                        <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/>
                        <line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
                      </svg>
                      Teilen
                    </button>
                  </div>
                </div>

                <!-- Description -->
                <p class="text-secondary mb-4 leading-relaxed">
                  {entry.description}
                  {isGated && gatedContentAuthEnabled && (
                    <span class="gated-content-hint ml-2 text-xs">
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display: inline; margin-right: 0.25rem;">
                        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                        <circle cx="12" cy="16" r="1"/>
                        <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                      </svg>
                      Authentifizierung erforderlich
                    </span>
                  )}
                </p>

                <!-- Metadata Footer -->
                <div class="border-t pt-3 mt-auto">
                  <div class="flex items-center justify-between text-xs text-secondary flex-wrap gap-2">
                    <div class="flex items-center gap-4 flex-wrap">
                      {entry.difficulty && (
                        <span class="flex items-center gap-1">
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="10"/>
                            <path d="M12 6v6l4 2"/>
                          </svg>
                          {entry.difficulty}
                        </span>
                      )}
                      
                      {hasAssociatedTool && entry.platforms && entry.platforms.length > 0 && !isMethod && !isConcept && (
                        <span class="flex items-center gap-1">
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
                          </svg>
                          {entry.platforms.slice(0, 2).join(', ')}{entry.platforms.length > 2 ? '...' : ''}
                        </span>
                      )}
                      
                      {entry.categories && entry.categories.length > 0 && (
                        <span class="flex items-center gap-1">
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10"/>
                          </svg>
                          {entry.categories.slice(0, 2).join(', ')}{entry.categories.length > 2 ? '...' : ''}
                        </span>
                      )}
                    </div>
                    
                    <div class="flex items-center gap-3">
                      <span>{entry.author}</span>
                      <span>•</span>
                      <span>{entry.last_updated.toLocaleDateString('de-DE')}</span>
                    </div>
                  </div>
                  
                  {entry.tags && entry.tags.length > 0 && (
                    <div class="flex flex-wrap gap-1 mt-2">
                      {entry.tags.slice(0, 8).map((tag: string) => (
                        <span class="tag text-xs">{tag}</span>
                      ))}
                    </div>
                  )}
                </div>
              </article>
            );
          })}
        </div>
      )}
    </div>

    <div id="no-kb-results" class="card text-center p-8 hidden">
      <h3 class="text-secondary mb-2">Keine Ergebnisse gefunden</h3>
      <p class="text-secondary">Versuchen Sie es mit anderen Suchbegriffen.</p>
    </div>
  </section>
  
  <div id="fab-container" class="fixed bottom-8 right-8 z-50 hidden">
    <ContributionButton 
      type="write" 
      variant="primary" 
      text="✍️" 
      style="border-radius: 50%; width: 56px; height: 56px; display: flex; align-items: center; justify-content: center; box-shadow: var(--shadow-lg); font-size: 1.5rem; padding: 0;"
      className="fab-button"
    />
  </div>
</BaseLayout>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('kb-search') as HTMLInputElement | null;
    const entries = document.querySelectorAll('.kb-entry') as NodeListOf<HTMLElement>;
    const visibleCount = document.getElementById('visible-count') as HTMLElement | null;
    const noResults = document.getElementById('no-kb-results') as HTMLElement | null;

    function updateVisibleCount(count: number) {
      if (visibleCount) {
        visibleCount.textContent = count.toString();
      }
    }

    function filterEntries(searchTerm: string) {
      let visibleEntries = 0;
      
      entries.forEach((entry) => {
        const toolName = entry.getAttribute('data-tool-name') || '';
        const entryText = entry.textContent?.toLowerCase() || '';
        const matches = entryText.includes(searchTerm.toLowerCase()) || 
                       toolName.includes(searchTerm.toLowerCase());
        
        if (matches) {
          entry.style.display = 'block';
          visibleEntries++;
        } else {
          entry.style.display = 'none';
        }
      });
      
      updateVisibleCount(visibleEntries);
      
      if (noResults) {
        noResults.style.display = visibleEntries === 0 && searchTerm.length > 0 ? 'block' : 'none';
      }
    }

    if (searchInput) {
      searchInput.addEventListener('input', (e) => {
        const target = e.target as HTMLInputElement;
        filterEntries(target.value);
      });
    }

    let lastScrollY = window.scrollY;
    const fabContainer = document.getElementById('fab-container');
    
    window.addEventListener('scroll', () => {
      if (fabContainer) {
        if (window.scrollY > 200 && window.scrollY < lastScrollY) {
          fabContainer.style.display = 'block';
        } else {
          fabContainer.style.display = 'none';
        }
        lastScrollY = window.scrollY;
      }
    });
  });
</script>

<style>
  .gated-indicator {
    font-size: 0.875rem;
    opacity: 0.8;
  }
  
  .gated-content-hint {
    color: var(--color-warning);
    font-weight: 500;
  }
  
  .kb-entry[data-gated="true"] {
    border-left: 3px solid var(--color-warning);
  }
  
  .gated-content-info {
    border-left: 4px solid var(--color-warning) !important;
  }
</style>
</BaseLayout>