// src/utils/globalUtils.ts
// Consolidated global utilities to eliminate duplication and provide consistent interface

import { createToolSlug, findToolByIdentifier, isToolHosted } from './toolHelpers.js';
import { auditService } from './auditService.js';

// Utility functions for UI interactions
export const UIUtils = {
  scrollToElement(element: Element | null, options: ScrollIntoViewOptions = {}) {
    if (!element) return;
    
    setTimeout(() => {
      const headerHeight = document.querySelector('nav')?.offsetHeight || 80;
      const elementRect = element.getBoundingClientRect();
      const absoluteElementTop = elementRect.top + window.pageYOffset;
      const targetPosition = absoluteElementTop - headerHeight - 20;
      
      window.scrollTo({
        top: targetPosition,
        behavior: 'smooth',
        ...options
      });
    }, 100);
  },

  scrollToElementById(elementId: string, options: ScrollIntoViewOptions = {}) {
    const element = document.getElementById(elementId);
    if (element) {
      this.scrollToElement(element, options);
    }
  },

  scrollToElementBySelector(selector: string, options: ScrollIntoViewOptions = {}) {
    const element = document.querySelector(selector);
    if (element) {
      this.scrollToElement(element, options);
    }
  },

  prioritizeSearchResults(tools: any[], searchTerm: string) {
    if (!searchTerm || !searchTerm.trim()) {
      return tools;
    }
    
    const lowerSearchTerm = searchTerm.toLowerCase().trim();
    
    return tools.sort((a, b) => {
      const aTagsLower = (a.tags || []).map((tag: string) => tag.toLowerCase());
      const bTagsLower = (b.tags || []).map((tag: string) => tag.toLowerCase());
      
      const aExactTag = aTagsLower.includes(lowerSearchTerm);
      const bExactTag = bTagsLower.includes(lowerSearchTerm);
      
      if (aExactTag && !bExactTag) return -1;
      if (!aExactTag && bExactTag) return 1;
      
      return a.name.localeCompare(b.name);
    });
  }
};

// Theme management
export const ThemeManager = {
  THEME_KEY: 'dfir-theme',

  getSystemTheme(): 'dark' | 'light' {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  },

  getStoredTheme(): string {
    return localStorage.getItem(this.THEME_KEY) || 'auto';
  },

  applyTheme(theme: string) {
    const effectiveTheme = theme === 'auto' ? this.getSystemTheme() : theme;
    document.documentElement.setAttribute('data-theme', effectiveTheme);
  },

  updateThemeToggle(theme: string) {
    document.querySelectorAll('[data-theme-toggle]').forEach(button => {
      button.setAttribute('data-current-theme', theme);
    });
  },

  initTheme() {
    const storedTheme = this.getStoredTheme();
    this.applyTheme(storedTheme);
    this.updateThemeToggle(storedTheme);
  },

  toggleTheme() {
    const current = this.getStoredTheme();
    const themes = ['light', 'dark', 'auto'];
    const currentIndex = themes.indexOf(current);
    const nextIndex = (currentIndex + 1) % themes.length;
    const nextTheme = themes[nextIndex];
    
    localStorage.setItem(this.THEME_KEY, nextTheme);
    this.applyTheme(nextTheme);
    this.updateThemeToggle(nextTheme);
  }
};

// Authentication utilities
export const AuthManager = {
  async checkClientAuth(context: string = 'general') {
    try {
      const response = await fetch('/api/auth/status');
      const data = await response.json();
      
      switch (context) {
        case 'contributions':
          return {
            authenticated: data.contributionAuthenticated,
            authRequired: data.contributionAuthRequired,
            expires: data.expires
          };
        case 'ai':
          return {
            authenticated: data.aiAuthenticated,
            authRequired: data.aiAuthRequired,
            expires: data.expires
          };
        default:
          return {
            authenticated: data.authenticated,
            authRequired: data.contributionAuthRequired || data.aiAuthRequired,
            expires: data.expires
          };
      }
    } catch (error) {
      console.error('Auth check failed:', error);
      return {
        authenticated: false,
        authRequired: true
      };
    }
  },

  async requireClientAuth(callback?: () => void, returnUrl?: string, context: string = 'general') {
    const authStatus = await this.checkClientAuth(context);
    
    if (authStatus.authRequired && !authStatus.authenticated) {
      const targetUrl = returnUrl || window.location.href;
      window.location.href = `/api/auth/login?returnTo=${encodeURIComponent(targetUrl)}`;
      return false;
    } else {
      if (typeof callback === 'function') {
        callback();
      }
      return true;
    }
  },

  async showIfAuthenticated(selector: string, context: string = 'general') {
    const authStatus = await this.checkClientAuth(context);
    const element = document.querySelector(selector);
    
    if (element) {
      (element as HTMLElement).style.display = (!authStatus.authRequired || authStatus.authenticated) 
        ? 'inline-flex' 
        : 'none';
    }
  },

  setupAuthButtons(selector: string = '[data-contribute-button]') {
    document.addEventListener('click', async (e) => {
      if (!e.target) return;
      
      const target = e.target as HTMLElement;
      const button = target.closest(selector) as HTMLAnchorElement;
      if (!button) return;
      
      e.preventDefault();
      
      await this.requireClientAuth(() => {
        window.location.href = button.href;
      }, button.href, 'contributions');
    });
  }
};

// Sharing utilities
export const SharingUtils = {
  async copyUrlToClipboard(url: string, button: HTMLElement) {
    try {
      await navigator.clipboard.writeText(url);
      
      const originalHTML = button.innerHTML;
      button.innerHTML = `
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right: 0.375rem;">
          <polyline points="20,6 9,17 4,12"/>
        </svg>
        Kopiert!
      `;
      button.style.color = 'var(--color-accent)';
      
      setTimeout(() => {
        button.innerHTML = originalHTML;
        button.style.color = '';
      }, 2000);
    } catch (err) {
      const textArea = document.createElement('textarea');
      textArea.value = url;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      
      const originalHTML = button.innerHTML;
      button.innerHTML = 'Kopiert!';
      setTimeout(() => {
        button.innerHTML = originalHTML;
      }, 2000);
    }
  },

  async shareArticle(button: HTMLElement, url: string, title: string) {
    const fullUrl = window.location.origin + url;
    await this.copyUrlToClipboard(fullUrl, button);
  },

  async shareCurrentArticle(button: HTMLElement) {
    await this.copyUrlToClipboard(window.location.href, button);
  }
};

// Audit utilities for window exposure
export const AuditUtils = {
  formatDuration(ms: number): string {
    if (ms < 1000) return '< 1s';
    if (ms < 60000) return `${Math.ceil(ms / 1000)}s`;
    const minutes = Math.floor(ms / 60000);
    const seconds = Math.ceil((ms % 60000) / 1000);
    return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
  },

  getConfidenceColor(confidence: number): string {
    if (confidence >= 80) return 'var(--color-accent)';
    if (confidence >= 60) return 'var(--color-warning)';
    return 'var(--color-error)';
  },

  escapeHtml(text: string): string {
    if (typeof text !== 'string') return String(text);
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  },

  sanitizeText(text: string): string {
    if (typeof text !== 'string') return '';
    
    return text
      .replace(/^#{1,6}\s+/gm, '')
      .replace(/^\s*[-*+]\s+/gm, '')
      .replace(/^\s*\d+\.\s+/gm, '')
      .replace(/\*\*(.+?)\*\*/g, '$1')
      .replace(/\*(.+?)\*/g, '$1')
      .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
      .replace(/```[\s\S]*?```/g, '[CODE BLOCK]')
      .replace(/`([^`]+)`/g, '$1')
      .replace(/<[^>]+>/g, '')
      .replace(/\n\s*\n\s*\n/g, '\n\n')
      .trim();
  }
};

// Tool utilities (re-export from toolHelpers)
export const ToolUtils = {
  createToolSlug,
  findToolByIdentifier,
  isToolHosted
};

// Centralized initialization function
export function initializeGlobalUtils() {
  // Expose theme utilities
  window.themeUtils = ThemeManager;
  
  // Expose UI utilities
  window.scrollToElement = UIUtils.scrollToElement.bind(UIUtils);
  window.scrollToElementById = UIUtils.scrollToElementById.bind(UIUtils);
  window.scrollToElementBySelector = UIUtils.scrollToElementBySelector.bind(UIUtils);
  window.prioritizeSearchResults = UIUtils.prioritizeSearchResults.bind(UIUtils);
  
  // Expose auth utilities
  window.checkClientAuth = AuthManager.checkClientAuth.bind(AuthManager);
  window.requireClientAuth = AuthManager.requireClientAuth.bind(AuthManager);
  window.showIfAuthenticated = AuthManager.showIfAuthenticated.bind(AuthManager);
  window.setupAuthButtons = AuthManager.setupAuthButtons.bind(AuthManager);
  
  // Expose sharing utilities
  window.shareArticle = SharingUtils.shareArticle.bind(SharingUtils);
  window.shareCurrentArticle = SharingUtils.shareCurrentArticle.bind(SharingUtils);
  
  // Expose tool utilities
  window.createToolSlug = ToolUtils.createToolSlug;
  window.findToolByIdentifier = ToolUtils.findToolByIdentifier;
  window.isToolHosted = ToolUtils.isToolHosted;
  
  // Expose audit utilities
  window.AuditUtils = AuditUtils;
  window.auditService = auditService;
}

// Listen for system theme changes
export function setupThemeChangeListener() {
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
    if (ThemeManager.getStoredTheme() === 'auto') {
      ThemeManager.applyTheme('auto');
    }
  });
}