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

export const prerender = true;

export async function getStaticPaths() {
  const knowledgebaseEntries = await getCollection('knowledgebase');
  
  console.log('Building static paths for:', knowledgebaseEntries.map(e => e.slug));
  
  return knowledgebaseEntries.map((entry) => {
    return {
      params: { slug: entry.slug },
      props: { entry },
    };
  });
}

const { entry }: { entry: any } = Astro.props;

const isGatedContent = entry.data.gated_content === true;
const gatedContentAuthRequired = isGatedContentAuthRequired();
const requiresAuth = isGatedContent && gatedContentAuthRequired;

console.log(`[GATED CONTENT] Article: ${entry.data.title}, Gated: ${isGatedContent}, Auth Required: ${requiresAuth}`);

const { Content } = await entry.render();

const data = await getToolsData();

const primaryTool = entry.data.tool_name 
  ? data.tools.find((t: any) => t.name === entry.data.tool_name)
  : null;

const relatedTools = entry.data.related_tools 
  ? entry.data.related_tools.map((toolName: string) => 
      data.tools.find((t: any) => t.name === toolName)
    ).filter(Boolean)
  : [];

const displayTool = primaryTool || relatedTools[0];

if (!displayTool && !entry.data.tool_name && relatedTools.length === 0) {
  console.log(`Standalone knowledgebase article: ${entry.slug}`);
}

const isMethod = displayTool?.type === 'method';
const isConcept = displayTool?.type === 'concept';
const isStandalone = !displayTool;
const hasValidProjectUrl = displayTool && displayTool.projectUrl !== undefined && 
                          displayTool.projectUrl !== null && 
                          displayTool.projectUrl !== "" && 
                          displayTool.projectUrl.trim() !== "";

const currentUrl = Astro.url.href;
---

<BaseLayout title={entry.data.title} description={entry.data.description}>
  {requiresAuth && (
    <script define:vars={{ requiresAuth, articleTitle: entry.data.title }}>
      document.addEventListener('DOMContentLoaded', async () => {
        if (!requiresAuth) return;
        
        console.log('[GATED CONTENT] Checking client-side auth for: ' + articleTitle);
        
        const urlParams = new URLSearchParams(window.location.search);
        const authSuccess = urlParams.get('auth') === 'success';
        
        const contentArea = document.querySelector('.article-content');
        const sidebar = document.querySelector('.article-sidebar');
        
        if (contentArea) {
          contentArea.style.display = 'none';
        }
        
        if (authSuccess) {
          console.log('[GATED CONTENT] Auth success detected, waiting for session...');
          await new Promise(resolve => setTimeout(resolve, 1000));
          
          const cleanUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
          window.history.replaceState({}, document.title, cleanUrl);
        }
        
        try {
          const response = await fetch('/api/auth/status');
          const authStatus = await response.json();
          
          const isAuthenticated = authStatus.gatedContentAuthenticated || false;
          const authRequired = authStatus.gatedContentAuthRequired || false;
          
          console.log('[GATED CONTENT] Auth status - Required: ' + authRequired + ', Authenticated: ' + isAuthenticated);
          
          if (authRequired && !isAuthenticated) {
            console.log('[GATED CONTENT] Access denied - showing auth required message: ' + articleTitle);
            
            if (contentArea) {
              const loginUrl = '/api/auth/login?returnTo=' + encodeURIComponent(window.location.href);
                contentArea.innerHTML = [
                  '<div class="gated-content-block">',
                    '<div class="gated-icon">🔒</div>',
                    '<h3 class="gated-title">Authentifizierung erforderlich</h3>',
                    '<p class="gated-description">Dieser Artikel enthält geschützte Inhalte und ist nur für authentifizierte Benutzer zugänglich.</p>',
                    '<div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap; margin-bottom: 1.5rem;">',
                      '<a href="' + loginUrl + '" class="btn btn-primary" style="min-width: 140px; text-align: center;">',
                        '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right: 0.5rem;">',
                          '<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>',
                          '<polyline points="10 17 15 12 10 7"/>',
                          '<line x1="15" y1="12" x2="3" y2="12"/>',
                        '</svg>',
                        'Anmelden',
                      '</a>',
                      '<a href="/knowledgebase" class="btn btn-secondary" style="min-width: 140px; text-align: center;">Zurück zur Übersicht</a>',
                    '</div>',
                    '<div class="gated-help">',
                      '<small>Nach der Anmeldung werden Sie automatisch zu diesem Artikel zurückgeleitet.</small>',
                    '</div>',
                  '</div>'
                ].join('');
              contentArea.style.display = 'block';
            }
          } else {
            console.log('[GATED CONTENT] Access granted for: ' + articleTitle);
            if (contentArea) {
              contentArea.style.display = 'block';
            }
            setTimeout(() => {
              if (typeof generateTOCContent === 'function') {
                generateTOCContent();
              }
            }, 100);
          }
        } catch (error) {
          console.error('[GATED CONTENT] Auth check failed:', error);
          if (requiresAuth && contentArea) {
            const loginUrl = '/api/auth/login?returnTo=' + encodeURIComponent(window.location.href);
            contentArea.innerHTML = [
              '<div class="gated-content-block">',
                '<div class="gated-icon error">⚠️</div>',
                '<h3 class="gated-title">Authentifizierungsfehler</h3>',
                '<p class="gated-description">Es gab ein Problem bei der Überprüfung Ihrer Berechtigung. Bitte versuchen Sie es erneut.</p>',
                '<div class="gated-actions">',
                  '<a href="' + loginUrl + '" class="btn btn-primary">Anmelden</a>',
                  '<button onclick="location.reload()" class="btn btn-secondary">Seite neu laden</button>',
                '</div>',
              '</div>'
            ].join('');
            contentArea.style.display = 'block';
          }
        }
      });
    </script>
  )}

  <div class="article-layout">
    <!-- Article Header -->
    <header class="article-header">
      <div class="article-header-content">
        <div class="article-meta">
          <nav class="breadcrumb">
            <a href="/knowledgebase" class="breadcrumb-link">Knowledgebase</a>
            <span class="breadcrumb-separator">→</span>
            <span class="breadcrumb-current">{entry.data.title}</span>
          </nav>
          
          <div class="article-tags">
            {entry.data.categories?.map((cat: string) => (
              <span class="article-tag article-tag-category">{cat}</span>
            ))}
            {entry.data.tags?.map((tag: string) => (
              <span class="article-tag">{tag}</span>
            ))}
          </div>
        </div>
        
        <div class="article-title-section">
          <h1 class="article-title">
            {displayTool?.icon && <span class="article-icon">{displayTool.icon}</span>}
            {entry.data.title}
            {isGatedContent && (
              <span class="gated-indicator" title="Geschützter Inhalt - Authentifizierung erforderlich">
                🔒
              </span>
            )}
          </h1>
          <p class="article-description">{entry.data.description}</p>
          
          {isGatedContent && gatedContentAuthRequired && (
            <div class="gated-content-notice">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right: 0.5rem;">
                <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>Dieser Artikel enthält geschützte Inhalte</span>
            </div>
          )}
        </div>
        
        <div class="article-metadata-grid">
          <div class="metadata-item">
            <span class="metadata-label">Typ</span>
            <div class="metadata-badges">
              {isStandalone ? (
                <span class="badge badge-accent">Artikel</span>
              ) : (
                <>
                  {isConcept && <span class="badge badge-concept">Konzept</span>}
                  {isMethod && <span class="badge badge-method">Methode</span>}
                  {!isMethod && !isConcept && <span class="badge badge-primary">Software</span>}
                  {hasValidProjectUrl && <span class="badge badge-primary">CC24-Server</span>}
                </>
              )}
              <span class="badge badge-error">📖</span>
              {isGatedContent && <span class="badge badge-warning">🔒</span>}
            </div>
          </div>
          
          {entry.data.difficulty && (
            <div class="metadata-item">
              <span class="metadata-label">Schwierigkeit</span>
              <span class="metadata-value">{entry.data.difficulty}</span>
            </div>
          )}
          
          <div class="metadata-item">
            <span class="metadata-label">Aktualisiert</span>
            <span class="metadata-value">{entry.data.last_updated.toLocaleDateString('de-DE')}</span>
          </div>
          
          <div class="metadata-item">
            <span class="metadata-label">Autor</span>
            <span class="metadata-value">{entry.data.author}</span>
          </div>
          
          <div class="metadata-item">
            <span class="metadata-label">Lesezeit</span>
            <span class="metadata-value" id="reading-time">~5 min</span>
          </div>
        </div>
        
        <div class="article-actions">
          <button 
            id="share-article-btn"
            class="btn btn-secondary"
            onclick="window.shareCurrentArticle(this)"
            title="Artikel teilen"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <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>
          
          <a href="/knowledgebase" class="btn btn-secondary">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="15,18 9,12 15,6"></polyline>
            </svg>
            Zurück
          </a>
        </div>
      </div>
    </header>

    <!-- Main Content Area -->
    <div class="article-content-wrapper">
      <!-- Sidebar Navigation (will be populated by JS) -->
      <aside class="article-sidebar">
        <!-- TOC will be inserted here by JavaScript -->
      </aside>
      
      <!-- Article Content -->
      <main class="article-main">
        <article class="article-content" style={requiresAuth ? "display: none;" : ""}>
          <div class="markdown-content">
            <Content />
          </div>
        </article>
        
        <!-- Article Footer -->
        <footer class="article-footer">
          <div class="article-footer-actions">
            <h3>Links</h3>
            <div class="footer-actions-grid">
              {isStandalone ? (
                <a href="/knowledgebase" class="btn btn-primary">
                  <svg width="16" height="16" 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"/>
                    <polyline points="14 2 14 8 20 8"/>
                  </svg>
                  Weitere Artikel
                </a>
              ) : (
                <>
                  {isConcept ? (
                    <a href={displayTool.url} target="_blank" rel="noopener noreferrer" class="btn btn-concept">
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <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>
                      Mehr erfahren
                    </a>
                  ) : isMethod ? (
                    <a href={displayTool.projectUrl || displayTool.url} target="_blank" rel="noopener noreferrer" class="btn btn-method">
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <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>
                      Zur Methode
                    </a>
                  ) : (
                    <>
                      <a href={displayTool.url} target="_blank" rel="noopener noreferrer" class="btn btn-secondary">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                          <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>
                        Homepage
                      </a>
                      {hasValidProjectUrl && (
                        <a href={displayTool.projectUrl} target="_blank" rel="noopener noreferrer" class="btn btn-primary">
                          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="10"/>
                            <path d="M12 16l4-4-4-4"/>
                            <path d="M8 12h8"/>
                          </svg>
                          Zugreifen
                        </a>
                      )}
                    </>
                  )}
                </>
              )}
              
              <a href="/" class="btn btn-secondary">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
                  <polyline points="9,22 9,12 15,12 15,22"/>
                </svg>
                Zur Hauptseite
              </a>
            </div>
          </div>
          
          {relatedTools.length > 0 && (
            <div class="related-tools">
              <h3>Verwandte Tools</h3>
              <div class="related-tools-grid">
                {relatedTools.map((tool: any) => (
                  <a href={tool.projectUrl || tool.url} target="_blank" rel="noopener noreferrer" class="related-tool-card">
                    {tool.icon && <span class="tool-icon">{tool.icon}</span>}
                    <span class="tool-name">{tool.name}</span>
                  </a>
                ))}
              </div>
            </div>
          )}
        </footer>
      </main>
    </div>
  </div>

<script define:vars={{ requiresAuth }}>
  /** @template {Element} T
   *  @param {string} sel
   *  @param {Document|Element} [root=document]
   *  @returns {T|null} */
  const qs = (sel, root = document) => root.querySelector(sel);

  /** @template {Element} T
   *  @param {string} sel
   *  @param {Document|Element} [root=document]
   *  @returns {T[]} */
  const qsa = (sel, root = document) => Array.from(root.querySelectorAll(sel));

  function calculateReadingTime() {
    /** @type {HTMLElement|null} */
    const content = qs('.markdown-content');
    if (!content) return;

    const text = (content.textContent || content.innerText || '').trim();
    if (!text) return;

    const wordsPerMinute = 200;
    const words = text.split(/\s+/).length;
    const readingTime = Math.ceil(words / wordsPerMinute);

    const readingTimeElement = document.getElementById('reading-time');
    if (readingTimeElement) {
      readingTimeElement.textContent = `~${readingTime} min`;
    }
  }

  function generateSidebarTOC() {
    if (requiresAuth) {
      return;
    }
    
    generateTOCContent();
  }

  function generateTOCContent() {
    /** @type {HTMLElement|null} */
    const article = qs('.markdown-content');
    /** @type {HTMLElement|null} */
    const sidebar = qs('.article-sidebar');
    /** @type {HTMLElement|null} */
    const main = qs('.article-main');

    if (!article || !sidebar || !main) return;

    /** @type {HTMLHeadingElement[]} */
    const headings = qsa('h1, h2, h3, h4, h5, h6', article);

    if (headings.length < 2) {
      sidebar.style.display = 'none';
      main.style.maxWidth = '100%';
      return;
    }

    headings.forEach((h, i) => {
      if (!h.id) h.id = `heading-${i}`;
    });

    const tocHTML = `
      <div class="sidebar-toc">
        <h3 class="toc-title">Inhaltsverzeichnis</h3>
        <nav class="toc-navigation">
          ${headings.map((h) => {
            const level = parseInt(h.tagName.slice(1), 10);
            const text = (h.textContent || '').trim();
            const id = h.id;
            return `
              <a href="#${id}" class="toc-item toc-level-${level}" data-heading="${id}">
                ${text}
              </a>
            `;
          }).join('')}
        </nav>
      </div>
    `;

    sidebar.innerHTML = tocHTML;

    /** @type {HTMLAnchorElement[]} */
    const tocItems = qsa('.toc-item', sidebar);

    tocItems.forEach((item) => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        const href = item.getAttribute('href');
        if (!href || !href.startsWith('#')) return;

        const target = document.getElementById(href.slice(1));
        if (target) {
          target.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });
          tocItems.forEach((i) => i.classList.remove('active'));
          item.classList.add('active');
        }
      });
    });

    const updateActiveSection = () => {
      const scrollY = window.scrollY + 100;
      let currentId = null;

      for (let i = 0; i < headings.length; i++) {
        const h = headings[i];
        const rect = h.getBoundingClientRect();
        const absTop = rect.top + window.pageYOffset;
        if (absTop <= scrollY) currentId = h.id;
      }

      if (currentId) {
        tocItems.forEach((i) => i.classList.remove('active'));
        /** @type {HTMLAnchorElement|null} */
        const active = qs(`.toc-item[data-heading="${currentId}"]`, sidebar);
        if (active) active.classList.add('active');
      }
    };

    let ticking = false;
    window.addEventListener('scroll', () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        updateActiveSection();
        ticking = false;
      });
    });

    updateActiveSection();
  }

  function enhanceCodeCopy() {
    /** @type {HTMLPreElement[]} */
    const pres = qsa('.markdown-content pre');

    pres.forEach((pre) => {
      if (pre.dataset.copyEnhanced === 'true') return;
      pre.dataset.copyEnhanced = 'true';
      pre.style.position ||= 'relative';

      let btn =
        pre.querySelector('.copy-btn') ||  
        pre.querySelector('.btn-copy, .copy-button, .code-copy, .copy-code, button[aria-label*="copy" i]');

      if (btn && !btn.classList.contains('copy-btn')) {
        btn.classList.add('copy-btn');
      }

      if (!btn) {
        btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'copy-btn';
        btn.setAttribute('aria-label', 'Code kopieren');
        btn.innerHTML = `
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
               aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/>
               <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
          <span>Copy</span>
        `;
        pre.appendChild(btn);
      }

      const possibleOldButtons = pre.querySelectorAll(
        '.btn-copy, .copy-button, .code-copy, .copy-code, button[aria-label*="copy" i]'
      );
      possibleOldButtons.forEach((b) => {
        if (b !== btn) b.style.display = 'none';
      });

      if (!pre.querySelector('.copied-pill')) {
        const pill = document.createElement('div');
        pill.className = 'copied-pill';
        pill.textContent = '✓ Kopiert';
        pre.appendChild(pill);
      }

      if (!pre.querySelector('.sr-live')) {
        const live = document.createElement('div');
        live.className = 'sr-live';
        live.setAttribute('aria-live', 'polite');
        Object.assign(live.style, {
          position: 'absolute', width: '1px', height: '1px', padding: '0', margin: '-1px',
          overflow: 'hidden', clip: 'rect(0,0,0,0)', border: '0'
        });
        pre.appendChild(live);
      }

      btn.addEventListener('click', async () => {
        const code = pre.querySelector('code');
        const text = code ? code.innerText : pre.innerText;
        const live = pre.querySelector('.sr-live');

        const copyText = async (t) => {
          try {
            await navigator.clipboard.writeText(t);
            return true;
          } catch {
            const ta = document.createElement('textarea');
            ta.value = t;
            ta.style.position = 'fixed';
            ta.style.top = '-1000px';
            document.body.appendChild(ta);
            ta.select();
            const ok = document.execCommand('copy');
            document.body.removeChild(ta);
            return ok;
          }
        };

        const ok = await copyText(text);
        pre.dataset.copied = ok ? 'true' : 'false';
        if (live) live.textContent = ok ? 'Code in die Zwischenablage kopiert' : 'Kopieren fehlgeschlagen';

        window.setTimeout(() => { pre.dataset.copied = 'false'; }, 1200);
      });
    });
  }

  window.generateTOCContent = generateTOCContent;

  document.addEventListener('DOMContentLoaded', () => {
    calculateReadingTime();
    generateSidebarTOC();
    enhanceCodeCopy();
  });
</script>

<style>
  .gated-indicator {
    font-size: 0.875rem;
    opacity: 0.8;
    margin-left: 0.5rem;
  }
  
  .gated-content-notice {
    display: flex;
    align-items: center;
    padding: 0.75rem 1rem;
    background-color: var(--color-warning-bg, rgba(255, 193, 7, 0.1));
    border: 1px solid var(--color-warning, #ffc107);
    border-radius: 0.375rem;
    color: var(--color-warning-text, #856404);
    font-size: 0.875rem;
    margin-top: 1rem;
  }

  .gated-content-block {
    text-align: center;
    padding: 4rem 2rem;
    max-width: 600px;
    margin: 0 auto;
  }

  .gated-icon {
    font-size: 4rem;
    margin-bottom: 1.5rem;
    opacity: 0.8;
  }

  .gated-icon.error {
    color: var(--color-error, #dc3545);
  }

  .gated-title {
    font-size: 1.5rem;
    font-weight: 600;
    color: var(--color-text);
    margin-bottom: 1rem;
  }

  .gated-description {
    font-size: 1rem;
    color: var(--color-text-secondary);
    line-height: 1.6;
    margin-bottom: 2rem;
  }

  .gated-actions {
    display: flex;
    gap: 1rem;
    justify-content: center;
    flex-wrap: wrap;
  }

  .gated-actions .btn {
    margin: 0 0.5rem;
  }

  .gated-help {
    color: var(--color-text-secondary);
    font-size: 0.875rem;
  }

  .gated-help small {
    opacity: 0.8;
  }

  /* Responsive adjustments */
  @media (max-width: 640px) {
    .gated-content-block {
      padding: 3rem 1rem;
    }
    
    .gated-actions {
      flex-direction: column;
      align-items: center;
    }
    
    .gated-actions .btn {
      width: 100%;
      max-width: 280px;
    }
  }
</style>
</BaseLayout>