/**
 * Component-Based CMS Type Definitions
 * Defines the architecture for flexible, reusable CMS components
 */

// ========================================
// Core Component Types
// ========================================

export type ComponentCategory =
  | "content"
  | "layout"
  | "interactive"
  | "data"
  | "media"
  | "navigation";

export type ComponentType =
  // Content Components
  | "text"
  | "rich_text"
  | "heading"
  | "paragraph"
  | "list"
  | "quote"
  // Media Components
  | "image"
  | "video"
  | "audio"
  | "gallery"
  | "carousel"
  // Layout Components
  | "container"
  | "grid"
  | "section"
  | "spacer"
  | "divider"
  | "column"
  | "row"
  // Interactive Components
  | "button"
  | "cta"
  | "form"
  | "input"
  | "checkbox"
  | "radio"
  | "select"
  | "textarea"
  // Data Components
  | "table"
  | "card"
  | "list_item"
  | "accordion"
  | "tabs"
  | "chart"
  // Navigation Components
  | "menu"
  | "breadcrumb"
  | "pagination"
  | "link"
  | "navigation"
  // AgentC Specific
  | "hero_section"
  | "cta_section"
  | "pricing_section"
  | "features_section"
  | "faq_section"
  | "testimonial_section"
  | "problem_section";

export interface CMSComponent {
  id: string;
  name: string;
  type: ComponentType;
  category: ComponentCategory;
  description: string;
  version: string;

  // Component configuration
  props: ComponentProps;
  defaultProps: ComponentProps;
  requiredProps: string[];
  configuration: ComponentProps;

  // Layout and styling
  layout: LayoutConfig;
  style: StyleConfig;
  theme: ThemeConfig;

  // CMS specific
  editable: boolean;
  locked: boolean;
  hidden: boolean;

  // Metadata
  tags: string[];
  author: string;
  createdAt: Date;
  updatedAt: Date;
  metadata: ComponentMetadata;

  // Relationships
  children: CMSComponent[];
  parent?: string;
  dependencies: string[];

  // Validation
  validation: ComponentValidation;

  // Preview
  preview: PreviewConfig;
}

export interface ComponentProps {
  [key: string]: ComponentPropValue;
}

export type ComponentPropValue =
  | string
  | number
  | boolean
  | Date
  | ComponentPropValue[]
  | { [key: string]: ComponentPropValue };

export interface ComponentPropDefinition {
  name: string;
  type:
    | "string"
    | "number"
    | "boolean"
    | "date"
    | "array"
    | "object"
    | "enum"
    | "color"
    | "url"
    | "image";
  required: boolean;
  default?: ComponentPropValue;
  description: string;
  validation?: PropValidation;
  enumValues?: string[];
  editor?: PropEditorConfig;
}

export interface PropValidation {
  min?: number;
  max?: number;
  pattern?: string;
  custom?: (value: ComponentPropValue) => boolean | string;
}

export interface PropEditorConfig {
  type:
    | "text"
    | "textarea"
    | "number"
    | "select"
    | "checkbox"
    | "color"
    | "image"
    | "rich_text"
    | "date";
  placeholder?: string;
  options?: Array<{ label: string; value: string }>;
  rows?: number;
  multiple?: boolean;
}

// ========================================
// Layout System
// ========================================

export interface LayoutConfig {
  // Display
  display?: "block" | "inline" | "inline-block" | "flex" | "grid" | "none";
  position?: "static" | "relative" | "absolute" | "fixed" | "sticky";

  // Dimensions
  width?: string;
  height?: string;
  maxWidth?: string;
  maxHeight?: string;
  minWidth?: string;
  minHeight?: string;

  // Spacing
  margin?: string | SpacingConfig;
  padding?: string | SpacingConfig;

  // Flexbox
  flexDirection?: "row" | "column" | "row-reverse" | "column-reverse";
  justifyContent?:
    | "flex-start"
    | "flex-end"
    | "center"
    | "space-between"
    | "space-around"
    | "space-evenly";
  alignItems?: "stretch" | "flex-start" | "flex-end" | "center" | "baseline";
  flexWrap?: "nowrap" | "wrap" | "wrap-reverse";
  gap?: string;

  // Grid
  gridTemplateColumns?: string;
  gridTemplateRows?: string;
  gridTemplate?: string;
  gridGap?: string;
  gridConfig?: GridConfig;

  // Responsive
  responsive?: ResponsiveConfig;

  // Z-index
  zIndex?: number;

  // Overflow
  overflow?: "visible" | "hidden" | "scroll" | "auto";
  overflowX?: "visible" | "hidden" | "scroll" | "auto";
  overflowY?: "visible" | "hidden" | "scroll" | "auto";
}

export interface SpacingConfig {
  top?: string;
  right?: string;
  bottom?: string;
  left?: string;
  all?: string;
  x?: string; // left and right
  y?: string; // top and bottom
}

export interface StyleConfig {
  // Colors
  backgroundColor?: string;
  color?: string;
  borderColor?: string;

  // Typography
  fontSize?: string;
  fontWeight?: string;
  fontFamily?: string;
  lineHeight?: string;
  textAlign?: "left" | "center" | "right" | "justify";
  textDecoration?: string;
  textTransform?: "none" | "uppercase" | "lowercase" | "capitalize";

  // Border
  border?: string;
  borderWidth?: string;
  borderStyle?: string;
  borderRadius?: string;

  // Shadow
  boxShadow?: string;
  textShadow?: string;

  // Background
  backgroundImage?: string;
  backgroundSize?: string;
  backgroundPosition?: string;
  backgroundRepeat?: string;

  // Effects
  opacity?: number;
  transform?: string;
  transition?: string;

  // Spacing
  margin?: string;
  marginTop?: string;
  marginRight?: string;
  marginBottom?: string;
  marginLeft?: string;
  padding?: string;
  paddingTop?: string;
  paddingRight?: string;
  paddingBottom?: string;
  paddingLeft?: string;

  // Sizing
  width?: string;
  height?: string;
  maxWidth?: string;
  maxHeight?: string;
  minWidth?: string;
  minHeight?: string;

  // Custom CSS
  customCSS?: string;

  // Responsive
  breakpoints?: {
    [key: string]: Partial<StyleConfig>;
  };

  // Cursor
  cursor?: string;
}

export interface ThemeConfig {
  primary: string;
  secondary: string;
  accent: string;
  background: string;
  surface: string;
  text: string;
  textSecondary: string;
  border: string;
  error: string;
  warning: string;
  success: string;
  info: string;
  shadow: string;
}

// ========================================
// Content Zone System
// ========================================

export interface ContentZone {
  id: string;
  name: string;
  description: string;
  type:
    | "header"
    | "main"
    | "sidebar"
    | "footer"
    | "content"
    | "navigation"
    | "custom";

  // Layout
  layout: LayoutConfig;
  gridArea?: string;

  // Content
  components: CMSComponent[];
  allowedTypes?: ComponentType[];
  maxComponents?: number;

  // Behavior
  editable: boolean;
  sortable: boolean;
  collapsible: boolean;

  // Constraints
  constraints: ZoneConstraints;

  // Metadata
  tags: string[];
  createdAt: Date;
  updatedAt: Date;
}

export interface ZoneLayout {
  columns: number;
  rows: number;
  gridTemplate?: string;
  allowedComponents?: ComponentType[];
  maxComponents?: number;
  minComponents?: number;
}

export interface ZoneConstraints {
  allowedTypes?: ComponentType[];
  forbiddenTypes?: ComponentType[];
  maxDepth?: number;
  maxComponents?: number;
  requiresAuth?: boolean;
  roles?: string[];
}

export interface ZoneMetadata {
  title: string;
  description: string;
  icon?: string;
  category: string;
  tags: string[];
  author: string;
  createdAt: Date;
  updatedAt: Date;
}

// ========================================
// Template System
// ========================================

export interface CMSTemplate {
  id: string;
  name: string;
  description: string;
  type: "page" | "section" | "component";
  category: string;

  // Service tier constraints
  tier: "starter" | "standard" | "plus" | "enterprise";
  tierConstraints: TierConstraints;

  // Structure
  zones: ContentZone[];
  globalStyles: StyleConfig;
  globalTheme: ThemeConfig;

  // Configuration
  settings: TemplateSettings;
  variables: TemplateVariable[];

  // Preview
  thumbnail?: string;
  screenshots: string[];
  demoUrl?: string;

  // Metadata
  version: string;
  author: string;
  tags: string[];
  createdAt: Date;
  updatedAt: Date;

  // Usage tracking
  usageCount: number;
  lastUsed?: Date;
}

export interface TierConstraints {
  maxComponents?: number;
  maxZones?: number;
  allowedComponentTypes?: ComponentType[];
  customStylingAllowed?: boolean;
  customCodeAllowed?: boolean;
  advancedLayoutsAllowed?: boolean;
}

export interface TemplateSettings {
  responsive: boolean;
  seoOptimized: boolean;
  accessibilityCompliant: boolean;
  performanceOptimized: boolean;
  rtlSupport: boolean;
  darkModeSupport: boolean;
  animationsEnabled: boolean;
}

export interface TemplateVariable {
  name: string;
  type: "string" | "number" | "boolean" | "color" | "image" | "url";
  value: ComponentPropValue;
  description: string;
  category: string;
  editable: boolean;
}

// ========================================
// Editor System
// ========================================

export interface EditorConfig {
  mode: "visual" | "code" | "preview" | "split";
  toolbar: ToolbarConfig;
  panels: EditorPanel[];
  shortcuts: KeyboardShortcut[];
  autosave: AutosaveConfig;
  collaboration: CollaborationConfig;
}

export interface ToolbarConfig {
  position: "top" | "bottom" | "left" | "right" | "floating";
  tools: ToolbarTool[];
  customizable: boolean;
  responsive: boolean;
}

export interface ToolbarTool {
  id: string;
  name: string;
  icon: string;
  action: string;
  group: string;
  enabled: boolean;
  visible: boolean;
  tooltip: string;
  shortcut?: string;
}

export interface EditorPanel {
  id: string;
  name: string;
  type:
    | "properties"
    | "layers"
    | "assets"
    | "components"
    | "styles"
    | "settings";
  position: "left" | "right" | "bottom";
  width?: string;
  height?: string;
  collapsible: boolean;
  defaultCollapsed: boolean;
  resizable: boolean;
}

export interface KeyboardShortcut {
  key: string;
  action: string;
  description: string;
  enabled: boolean;
}

export interface AutosaveConfig {
  enabled: boolean;
  interval: number; // seconds
  maxVersions: number;
  compressionEnabled: boolean;
}

export interface CollaborationConfig {
  enabled: boolean;
  realTimeEditing: boolean;
  commentingEnabled: boolean;
  reviewWorkflow: boolean;
  conflictResolution: "merge" | "overwrite" | "manual";
}

// ========================================
// Preview System
// ========================================

export interface PreviewConfig {
  responsive: boolean;
  devices: PreviewDevice[];
  defaultDevice: string;
  refreshMode: "auto" | "manual";
  refreshInterval?: number;
  interactive: boolean;
  showRulers: boolean;
  showGrid: boolean;
  showBoundaries: boolean;
}

export interface PreviewDevice {
  id: string;
  name: string;
  width: number;
  height: number;
  pixelRatio: number;
  userAgent?: string;
  orientation: "portrait" | "landscape";
  type: "desktop" | "tablet" | "mobile";
}

export interface ComponentValidation {
  rules: ValidationRule[];
  async: boolean;
  realTime: boolean;
  showErrors: boolean;
  showWarnings: boolean;
}

export interface ValidationRule {
  id: string;
  name: string;
  type:
    | "required"
    | "format"
    | "range"
    | "custom"
    | "accessibility"
    | "performance"
    | "seo";
  severity: "error" | "warning" | "info";
  message: string;
  validator: (component: CMSComponent) => ValidationResult;
}

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

export interface ValidationError {
  rule: string;
  message: string;
  field?: string;
  value?: ComponentPropValue;
}

export interface ValidationWarning {
  rule: string;
  message: string;
  field?: string;
  suggestion?: string;
}

// ========================================
// Component Library
// ========================================

export interface ComponentLibrary {
  id: string;
  name: string;
  description: string;
  version: string;

  // Categories
  categories: ComponentCategory[];
  components: ComponentDefinition[];

  // Configuration
  settings: LibrarySettings;
  theme: ThemeConfig;

  // Dependencies
  dependencies: LibraryDependency[];
  peerDependencies: LibraryDependency[];

  // Metadata
  author: string;
  license: string;
  repository?: string;
  homepage?: string;
  keywords: string[];

  // Timestamps
  createdAt: Date;
  updatedAt: Date;
  publishedAt?: Date;
}

export interface ComponentDefinition {
  meta: ComponentMeta;
  props: ComponentPropDefinition[];
  defaultProps: ComponentProps;
  examples: ComponentExample[];
  documentation: ComponentDocumentation;
  implementation: ComponentImplementation;
}

export interface ComponentMeta {
  id: string;
  name: string;
  displayName: string;
  type: ComponentType;
  category: ComponentCategory;
  description: string;
  version: string;
  deprecated?: boolean;
  deprecationMessage?: string;
  replacedBy?: string;
  stability: "experimental" | "beta" | "stable" | "deprecated";
  tags: string[];
}

export interface ComponentExample {
  id: string;
  name: string;
  description: string;
  props: ComponentProps;
  code?: string;
  preview: string;
  category: string;
}

export interface ComponentDocumentation {
  overview: string;
  usage: string;
  accessibility: string;
  examples: ComponentExample[];
  bestPractices: string[];
  troubleshooting: TroubleshootingItem[];
  changelog: ChangelogEntry[];
}

export interface TroubleshootingItem {
  problem: string;
  solution: string;
  category: string;
}

export interface ChangelogEntry {
  version: string;
  date: Date;
  type: "feature" | "fix" | "breaking" | "deprecated" | "security";
  description: string;
  migration?: string;
}

export interface ComponentImplementation {
  framework: "react" | "vue" | "angular" | "svelte" | "vanilla";
  language: "typescript" | "javascript";
  styling: "css" | "scss" | "styled-components" | "emotion" | "tailwind";
  bundle: {
    esm: string;
    cjs: string;
    umd?: string;
    css?: string;
  };
  dependencies: string[];
  peerDependencies: string[];
}

export interface LibrarySettings {
  prefix: string;
  namespace: string;
  theme: ThemeConfig;
  breakpoints: { [key: string]: string };
  spacing: { [key: string]: string };
  typography: TypographyConfig;
  colors: { [key: string]: string };
  shadows: { [key: string]: string };
  animations: AnimationConfig;
}

export interface TypographyConfig {
  fontFamilies: { [key: string]: string };
  fontSizes: { [key: string]: string };
  fontWeights: { [key: string]: string };
  lineHeights: { [key: string]: string };
  letterSpacing: { [key: string]: string };
}

export interface AnimationConfig {
  enabled: boolean;
  duration: { [key: string]: string };
  easing: { [key: string]: string };
  transitions: { [key: string]: string };
}

export interface LibraryDependency {
  name: string;
  version: string;
  optional?: boolean;
  dev?: boolean;
}

// ========================================
// Runtime System
// ========================================

export interface ComponentRenderer {
  render(component: CMSComponent, context: RenderContext): Promise<string>;
  renderToReact(
    component: CMSComponent,
    context: RenderContext
  ): React.ReactElement;
  validate(component: CMSComponent): ValidationResult;
  optimize(component: CMSComponent): CMSComponent;
}

export interface RenderContext {
  mode: "production" | "development" | "preview";
  theme: ThemeConfig;
  device: PreviewDevice;
  user?: {
    id: string;
    role: string;
    permissions: string[];
  };
  site: {
    id: string;
    domain: string;
    tier: "starter" | "standard" | "plus" | "enterprise";
  };
  page: {
    id: string;
    path: string;
    metadata: { [key: string]: string };
  };
  features: {
    animations: boolean;
    interactions: boolean;
    analytics: boolean;
    seo: boolean;
  };
}

// ========================================
// API Types
// ========================================

export interface ComponentAPI {
  // Component CRUD
  getComponent(id: string): Promise<CMSComponent>;
  createComponent(
    component: Omit<CMSComponent, "id" | "createdAt" | "updatedAt">
  ): Promise<CMSComponent>;
  updateComponent(
    id: string,
    updates: Partial<CMSComponent>
  ): Promise<CMSComponent>;
  deleteComponent(id: string): Promise<boolean>;

  // Library management
  getLibrary(id: string): Promise<ComponentLibrary>;
  searchComponents(query: ComponentSearchQuery): Promise<ComponentSearchResult>;

  // Template operations
  getTemplate(id: string): Promise<CMSTemplate>;
  createTemplate(
    template: Omit<CMSTemplate, "id" | "createdAt" | "updatedAt">
  ): Promise<CMSTemplate>;
  cloneTemplate(id: string, name: string): Promise<CMSTemplate>;

  // Rendering
  renderComponent(
    component: CMSComponent,
    context: RenderContext
  ): Promise<string>;
  previewComponent(component: CMSComponent, device: string): Promise<string>;

  // Validation
  validateComponent(component: CMSComponent): Promise<ValidationResult>;
  validateTemplate(template: CMSTemplate): Promise<ValidationResult>;
}

export interface ComponentSearchQuery {
  text?: string;
  type?: ComponentType[];
  category?: ComponentCategory[];
  tags?: string[];
  author?: string;
  tier?: ("starter" | "standard" | "plus" | "enterprise")[];
  library?: string;
  dateRange?: {
    start: Date;
    end: Date;
  };
  sortBy?: "name" | "created" | "updated" | "usage" | "rating";
  sortOrder?: "asc" | "desc";
  limit?: number;
  offset?: number;
}

export interface ComponentSearchResult {
  components: CMSComponent[];
  total: number;
  page: number;
  limit: number;
  hasMore: boolean;
  facets: {
    types: { [key in ComponentType]?: number };
    categories: { [key in ComponentCategory]?: number };
    tags: { [key: string]: number };
    authors: { [key: string]: number };
    libraries: { [key: string]: number };
  };
}

// Component Metadata for library display
export interface ComponentMetadata {
  title: string;
  description: string;
  tags: string[];
  icon: string;
  previewUrl: string;
}

// ========================================
// Layout Configuration Types
// ========================================

export interface GridConfig {
  columns?: string;
  rows?: string;
  gap?: string;
  areas?: string[];
  autoFlow?: "row" | "column" | "dense" | "row dense" | "column dense";
  autoColumns?: string;
  autoRows?: string;
}

export interface ResponsiveConfig {
  breakpoints: {
    [key: string]: LayoutConfig;
  };
  defaultBreakpoint?: string;
}

export interface SpacingConfig {
  all?: string;
  x?: string;
  y?: string;
  top?: string;
  right?: string;
  bottom?: string;
  left?: string;
}
