import { ElementorElement, ElementorTemplate, GenerationResult } from '../types/elementor';

export interface ValidationResult {
  valid: boolean;
  errors: string[];
  warnings: string[];
}

const VALID_EL_TYPES = new Set(['container', 'section', 'column', 'widget']);

const VALID_WIDGET_TYPES = new Set([
  'heading', 'text-editor', 'button', 'image', 'icon', 'divider', 'spacer',
  'video', 'icon-list', 'counter', 'progress', 'testimonial', 'accordion',
  'tabs', 'social-icons', 'shortcode', 'html', 'menu-anchor', 'sidebar',
  'google_maps', 'nav-menu', 'form', 'posts', 'portfolio', 'slides',
  'price-table', 'price-list', 'countdown', 'share-buttons', 'login',
  'loop-grid', 'loop-carousel',
]);

function validateElement(el: ElementorElement, path: string, errors: string[], warnings: string[]): void {
  if (!el.id || typeof el.id !== 'string') {
    errors.push(`${path}: missing or invalid id`);
  }

  if (!VALID_EL_TYPES.has(el.elType)) {
    errors.push(`${path}: invalid elType "${el.elType}"`);
  }

  if (el.elType === 'widget') {
    if (!el.widgetType) {
      errors.push(`${path}: widget is missing widgetType`);
    } else if (!VALID_WIDGET_TYPES.has(el.widgetType)) {
      warnings.push(`${path}: unknown widgetType "${el.widgetType}" — may not render correctly`);
    }
    if (el.elements.length > 0) {
      warnings.push(`${path}: widget "${el.widgetType}" has nested elements — Elementor widgets cannot contain child elements`);
    }
  }

  if (el.elType === 'section') {
    const hasNonColumn = el.elements.some((child) => child.elType !== 'column');
    if (hasNonColumn) {
      errors.push(`${path}: section must only contain columns`);
    }
  }

  if (el.elType === 'column') {
    const hasSection = el.elements.some((child) => child.elType === 'section');
    if (hasSection) {
      warnings.push(`${path}: column contains a section — check for improper nesting`);
    }
  }

  if (!el.settings || typeof el.settings !== 'object') {
    errors.push(`${path}: missing settings object`);
  }

  if (!Array.isArray(el.elements)) {
    errors.push(`${path}: elements must be an array`);
  }

  el.elements?.forEach((child, i) =>
    validateElement(child, `${path}.elements[${i}]`, errors, warnings)
  );
}

export function validateTemplate(template: ElementorTemplate): ValidationResult {
  const errors: string[] = [];
  const warnings: string[] = [];

  if (!template.version) errors.push('Missing template version');
  if (!template.title) warnings.push('Template has no title');
  if (!['page', 'section', 'container', 'widget'].includes(template.type)) {
    errors.push(`Invalid template type: "${template.type}"`);
  }
  if (!template.page_settings || typeof template.page_settings !== 'object') {
    errors.push('Missing page_settings');
  }
  if (!Array.isArray(template.content)) {
    errors.push('content must be an array');
  } else {
    if (template.content.length === 0) {
      warnings.push('Template has no content elements');
    }
    template.content.forEach((el, i) =>
      validateElement(el, `content[${i}]`, errors, warnings)
    );
  }

  return { valid: errors.length === 0, errors, warnings };
}

export function validateGenerationResult(result: GenerationResult): ValidationResult {
  const templateValidation = validateTemplate(result.template);
  return {
    valid: templateValidation.valid,
    errors: templateValidation.errors,
    warnings: [...templateValidation.warnings, ...result.warnings],
  };
}
