// Security utilities
const security = {
  sanitizeHTML(str) {
    if (!str) return '';
    if (typeof str !== 'string') {
      str = String(str);
    }
    return str
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  },

  validateInput(input) {
    if (typeof input !== "string") return false;
    if (input.length > 1000) return false;

    // Check for dangerous patterns
    const dangerous = [
      /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
      /javascript:/gi,
      /data:/gi,
      /vbscript:/gi,
      /on\w+\s*=/gi,
      /(\b)(on\S+)(\s*)=/gi
    ];

    return !dangerous.some(pattern => pattern.test(input));
  },

  sanitizeURL(url) {
    try {
      const parsed = new URL(url); // Attempt to parse the URL
      // Ensure the protocol is HTTPS
      if (parsed.protocol === "https:") {
        return parsed.href; // Return the normalized URL
      } else {
        console.warn("URL is not HTTPS:", url);
        return parsed.href;
      }
    } catch (error) {
      console.error("Invalid URL provided:", url, error);
      return "";
    }
  },

  validateId(id) {
    return Number.isInteger(id) && id > 0 && id < Number.MAX_SAFE_INTEGER;
  },

  validateJSON(str) {
    try {
      JSON.parse(str);
      return true;
    } catch (e) {
      return false;
    }
  },
};

// Performance utilities
const performance = {
  debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  },

  throttle(func, limit) {
    let inThrottle;
    return function executedFunction(...args) {
      if (!inThrottle) {
        func(...args);
        inThrottle = true;
        setTimeout(() => (inThrottle = false), limit);
      }
    };
  },
};

// DOM utilities
const dom = {
  createElement(tag, attributes = {}, children = []) {
    const element = document.createElement(tag);

    Object.entries(attributes).forEach(([key, value]) => {
      if (key.startsWith("on") && typeof value === "function") {
        element.addEventListener(key.slice(2).toLowerCase(), value);
      } else if (key === "className") {
        element.className = value;
      } else if (key === "dataset") {
        Object.entries(value).forEach(([dataKey, dataValue]) => {
          element.dataset[dataKey] = dataValue;
        });
      } else if (key === "nonce") {
        element.setAttribute('nonce', value);
      } else {
        element.setAttribute(key, value);
      }
    });

    children.forEach((child) => {
      if (typeof child === "string") {
        element.appendChild(document.createTextNode(child));
      } else if (child instanceof Node) {
        element.appendChild(child);
      }
    });

    return element;
  },
};

// Toast notifications
const toast = {
  show(message, type = "info", duration = 3000) {
    const toastElement = document.getElementById("toast");
    const messageElement = document.getElementById("toastMessage");

    if (!toastElement || !messageElement) return;

    messageElement.textContent = message;
    toastElement.classList.remove("translate-x-full");

    setTimeout(() => {
      toastElement.classList.add("translate-x-full");
    }, duration);
  },
};

export { dom, performance, security, toast };
