/**
 * Simple toast notification utility using DOM.
 * Bypasses react-hot-toast issues in WordPress admin.
 */

type ToastType = 'success' | 'error' | 'info';

interface ToastOptions {
  duration?: number;
  description?: string;
}

const TOAST_CONTAINER_ID = 'sequensy-toast-container';

/**
 * Generate a unique ID at runtime.
 * Uses window property mutation which cannot be optimized at build time.
 */
function generateUniqueId(): string {
  // Use a counter stored on window - this mutation cannot be optimized away
  const win = window as unknown as { __sequensyToastCounter?: number };
  win.__sequensyToastCounter = (win.__sequensyToastCounter || 0) + 1;
  // Use new Date() constructor which creates a new object each time
  return `${new Date().getTime()}-${win.__sequensyToastCounter}`;
}

function getOrCreateContainer(): HTMLElement {
  let container = document.getElementById(TOAST_CONTAINER_ID);
  if (!container) {
    container = document.createElement('div');
    container.id = TOAST_CONTAINER_ID;
    container.style.cssText = `
      position: fixed;
      top: 48px;
      right: 16px;
      z-index: 100000;
      display: flex;
      flex-direction: column;
      gap: 8px;
      pointer-events: none;
    `;
    document.body.appendChild(container);
  }
  return container;
}

function createToast(message: string, type: ToastType, options: ToastOptions = {}): string {
  const { duration = 4000, description } = options;
  const container = getOrCreateContainer();
  const id = `toast-${generateUniqueId()}`;

  const toast = document.createElement('div');
  toast.id = id;
  toast.style.cssText = `
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 12px 16px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    font-family: system-ui, -apple-system, sans-serif;
    font-size: 14px;
    line-height: 1.4;
    pointer-events: auto;
    max-width: 360px;
    animation: slideIn 0.2s ease-out forwards;
  `;

  // Colors based on type
  const colors = {
    success: { bg: '#f0fdf4', border: '#86efac', text: '#166534', icon: '✓' },
    error: { bg: '#fef2f2', border: '#fecaca', text: '#991b1b', icon: '✕' },
    info: { bg: '#eff6ff', border: '#bfdbfe', text: '#1e40af', icon: 'ℹ' },
  };

  const color = colors[type];
  toast.style.backgroundColor = color.bg;
  toast.style.border = `1px solid ${color.border}`;
  toast.style.color = color.text;

  // Icon
  const icon = document.createElement('span');
  icon.textContent = color.icon;
  icon.style.cssText = `
    flex-shrink: 0;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    font-size: 12px;
    font-weight: bold;
  `;
  icon.style.backgroundColor =
    type === 'success' ? '#22c55e' : type === 'error' ? '#ef4444' : '#3b82f6';
  icon.style.color = 'white';

  // Content
  const content = document.createElement('div');
  content.style.cssText = 'flex: 1; min-width: 0;';

  const messageEl = document.createElement('div');
  messageEl.textContent = message;
  messageEl.style.fontWeight = '500';
  content.appendChild(messageEl);

  if (description) {
    const descEl = document.createElement('div');
    descEl.style.cssText = 'margin-top: 4px; opacity: 0.8; font-size: 13px; white-space: pre-line;';
    descEl.textContent = description;
    content.appendChild(descEl);
  }

  // Close button
  const closeBtn = document.createElement('button');
  closeBtn.textContent = '×';
  closeBtn.style.cssText = `
    flex-shrink: 0;
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
    padding: 0;
    line-height: 1;
    opacity: 0.5;
    color: inherit;
  `;
  closeBtn.onclick = () => dismissToast(id);

  toast.appendChild(icon);
  toast.appendChild(content);
  toast.appendChild(closeBtn);

  // Inject CSS keyframes if not already present
  if (!document.getElementById('sequensy-toast-styles')) {
    const style = document.createElement('style');
    style.id = 'sequensy-toast-styles';
    style.textContent = `
      @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
      }
      @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
      }
    `;
    document.head.appendChild(style);
  }

  container.appendChild(toast);

  // Auto dismiss
  if (duration > 0) {
    setTimeout(() => dismissToast(id), duration);
  }

  return id;
}

function dismissToast(id: string): void {
  const toast = document.getElementById(id);
  if (toast) {
    toast.style.animation = 'slideOut 0.2s ease-out forwards';
    setTimeout(() => toast.remove(), 200);
  }
}

export const toast = {
  success: (message: string, options?: ToastOptions) => createToast(message, 'success', options),
  error: (message: string, options?: ToastOptions) => createToast(message, 'error', options),
  info: (message: string, options?: ToastOptions) => createToast(message, 'info', options),
};
