import React from 'react';

export interface DesignMD {
  brandName?: string;
  primaryColor: string;
  secondaryColor: string;
  textColor: string;
  baseFont: string;
  logoUrl: string;
  frameThickness: number;
  introVideoUrl?: string;
  outroVideoUrl?: string;
  brandStickers?: string[];
  defaultTransitionIn?: TransitionType;
  defaultTransitionOut?: TransitionType;
  
  titleFont?: string;
  titleSize?: number;
  titleColor?: string;
  
  subtitleFont?: string;
  subtitleSize?: number;
  subtitleColor?: string;
  
  paragraphFont?: string;
  paragraphSize?: number;
  paragraphColor?: string;
  
  defaultVideoTransition?: string;
  
  autoFadeInAudio?: boolean;
  autoFadeOutAudio?: boolean;

  introDurationFrames?: number;
  outroDurationFrames?: number;
  brandAudioUrl?: string;
  brandAudioVolume?: number;
  audioFadeInDuration?: number;
  audioFadeOutDuration?: number;

  // Social handles
  socialHandles?: {
    instagram?: string;
    tiktok?: string;
    twitter?: string;
    youtube?: string;
    website?: string;
  };

  // Layout & positioning
  logoPosition?: 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right';
  logoX?: number;   // Freeform % position (overrides logoPosition when set)
  logoY?: number;
  contentPosition?: 'top' | 'center' | 'bottom';
  contentX?: number; // Freeform % position for text block
  contentY?: number;

  // Video fit & position
  introVideoFit?: 'cover' | 'contain' | 'fill';
  introVideoBgColor?: string | null;
  introVideoPosition?: string;
  outroVideoFit?: 'cover' | 'contain' | 'fill';
  outroVideoBgColor?: string | null;
  outroVideoPosition?: string;
  // Freeform video placement (% of canvas)
  introVideoX?: number;
  introVideoY?: number;
  introVideoW?: number;  // width as % (default 100)
  introVideoH?: number;  // height as % (default 100)
  outroVideoX?: number;
  outroVideoY?: number;
  outroVideoW?: number;
  outroVideoH?: number;

  // Blend modes for background removal
  introBlendMode?: 'normal' | 'multiply' | 'screen';
  outroBlendMode?: 'normal' | 'multiply' | 'screen';
}

export interface BrandContentPiece {
  id: string;
  name: string;
  type: 'text-card' | 'social-badge' | 'logo-badge' | 'custom-image';
  content: {
    text?: string;
    subtext?: string;
    icon?: string;
    imageUrl?: string;
    // Freeform positions (0-100%)
    logoX?: number;
    logoY?: number;
    textX?: number;
    textY?: number;
    subtextX?: number;
    subtextY?: number;
  };
  style: {
    backgroundColor?: string;
    backgroundImage?: string;  // URL for custom background image
    textColor?: string;
    font?: string;
    fontSize?: number;
    borderRadius?: number;
    padding?: number;
    width?: number;
    height?: number;
  };
  thumbnail?: string;
  createdAt: string;
}

export interface Project {
  id: string;
  name: string;
  format: 'video' | 'image';
  elements: TimelineElement[];
  layers: TimelineLayer[];
}

export interface CompanyProfile {
  id: string;
  name: string;
  tagline?: string;
  industry?: string;
  socialLinks?: {
    website?: string;
    instagram?: string;
    x?: string;
    tiktok?: string;
    youtube?: string;
  };
  design: DesignMD;
  brandContent?: BrandContentPiece[];
  brandTemplates?: ExpressTemplate[];
  projects: Project[];
}

export type MediaFilter = 'none' | 'grayscale' | 'sepia' | 'contrast';

export type TransitionType = 'none' | 'fade' | 'slideUp' | 'slideDown' | 'slideLeft' | 'slideRight' | 'typewriter' | 'bounce' | 'scale' | 'blur' | 'spin' | 'flip';

export type EasingType = 'linear' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'spring' | 'bounce';

export interface AnimationKeyframe {
  frame: number;         // Absolute frame number
  x?: number;            // Position X (%)
  y?: number;            // Position Y (%)
  scale?: number;        // Scale factor
  opacity?: number;      // Opacity (0-1)
  rotation?: number;     // Rotation (degrees)
  easing?: EasingType;   // Easing curve TOWARDS this keyframe
}

export interface AudioVolumeKeyframe {
  frame: number;    // Frame relative to the clip start
  volume: number;   // 0 to 1
}

export interface TimelineLayer {
  id: string;
  name: string;
  isVisible?: boolean;
  isLocked?: boolean;
  opacity?: number;
  type?: 'visual' | 'video' | 'audio' | 'brand';
  volume?: number;
  colorLabel?: string;
  isMuted?: boolean;
  isSolo?: boolean;
}

export interface ElementTransition {
  type: TransitionType;
  duration: number;
}

export interface TimelineElement {
  id: string;
  /** Original TemplateField/ExpressField ID — used for mediaFit override lookup */
  sourceFieldId?: string;
  layerId: string;
  type: 'text' | 'sticker' | 'audio' | 'image' | 'video' | 'color' | 'shape';
  content: string;
  isBrandElement?: boolean; // true = generated by brand, cannot be deleted
  isLocked?: boolean; // true = cannot drag/resize on canvas
  isHidden?: boolean; // true = hidden from canvas render (still in timeline)
  brandDisplayMode?: 'fullscreen' | 'overlay'; // how brand video renders (default: fullscreen)
  startFrame: number;
  useBranding?: boolean;
  endFrame: number;
  x: number; // Percentage 0-100
  y: number; // Percentage 0-100
  w?: number; // Width percentage (for brand videos)
  h?: number; // Height percentage (for brand videos)
  scale?: number;
  rotation?: number;
  opacity?: number;
  color?: string;
  fontSize?: number;
  fontFamily?: string;
  shadowOffset?: number;
  shadowBlur?: number;
  shadowColor?: string;          // Shadow color hex, default '#000000'
  transitionIn?: ElementTransition;
  transitionOut?: ElementTransition;
  transitionType?: TransitionType;
  volume?: number;
  fadeInFrames?: number;
  fadeOutFrames?: number;
  volumeKeyframes?: AudioVolumeKeyframe[];
  originalFileName?: string;
  filter?: MediaFilter;
  brightness?: number;
  contrast?: number;
  saturation?: number;
  hueRotate?: number;            // Hue rotation in degrees (0-360)
  sepia?: number;                // Sepia intensity (0-100)
  // Legacy 2-point keyframes (backwards compatible)
  animEndX?: number;
  animEndY?: number;
  animEndScale?: number;
  animEndOpacity?: number;
  // Multi-keyframe animation (replaces animEnd* when present)
  keyframes?: AnimationKeyframe[];
  // Blend mode for background removal
  blendMode?: 'normal' | 'multiply' | 'screen' | 'overlay' | 'soft-light' | 'color-dodge';
  // Chroma Key settings
  chromaKeyEnabled?: boolean;
  chromaKeyColor?: string;       // Hex color, default '#ffffff'
  chromaKeyTolerance?: number;   // 0-100, default 30
  chromaKeySoftness?: number;    // 0-100, default 10
  // Text styling
  textAlign?: 'left' | 'center' | 'right';
  textStrokeWidth?: number;      // px, default 0
  textStrokeColor?: string;      // Hex color, default '#000000'
  lineHeight?: number;           // Multiplier, default 1.2
  letterSpacing?: number;        // px, default 0
  textTransform?: 'none' | 'uppercase' | 'lowercase' | 'capitalize';
  // Element metadata
  elementName?: string;          // User-given name for the element
  notes?: string;                // User notes/annotations for the element
  // Text gradient (overrides color when set)
  textGradient?: string;         // CSS linear-gradient string, e.g. 'linear-gradient(90deg, #ff0000, #0000ff)'
  // Text background (pill/highlight)
  textBackground?: string;       // color with alpha, e.g. '#000000AA'
  textBackgroundPadding?: number; // px, default 8
  textBackgroundRadius?: number;  // px, default 4
  // Rich text
  fontWeight?: number;           // 100-900, default 400
  fontStyle?: 'normal' | 'italic';
  textDecoration?: 'none' | 'underline' | 'line-through';
  // Element dimensions (% of canvas)
  width?: number;                // % of canvas width, default ~25 for new elements
  height?: number;               // % of canvas height, auto if not set (maintain aspect ratio)
  // Shape properties
  shapeType?: 'rectangle' | 'circle' | 'triangle' | 'line' | 'arrow' | 'star';
  shapeFill?: string;            // fill color
  shapeStroke?: string;          // stroke color
  shapeStrokeWidth?: number;     // stroke width px
  shapeCornerRadius?: number;    // border radius for rectangles
  // Speed / Playback Rate
  playbackRate?: number;         // 0.25 - 4.0, default 1.0
  // Source trimming (crop the source video/audio start/end)
  trimStartSec?: number;         // Seconds into source to start playback
  trimEndSec?: number;           // Seconds into source to end playback
  // Flip / Mirror
  flipH?: boolean;               // Horizontal flip
  flipV?: boolean;               // Vertical flip
  aspectLocked?: boolean;        // Lock width/height aspect ratio
  // Element Border
  borderColor?: string;          // Border color hex
  borderWidth?: number;          // Border width px (0 = no border)
  borderRadius?: number;         // Border radius px
  borderStyle?: 'solid' | 'dashed' | 'dotted';  // Border style
  // Drop Shadow (for media/shapes)
  boxShadowX?: number;           // Shadow X offset px
  boxShadowY?: number;           // Shadow Y offset px
  boxShadowBlur?: number;        // Shadow blur px
  boxShadowColor?: string;       // Shadow color with alpha
  // Blur Effect
  blurAmount?: number;           // Gaussian blur px (0 = no blur)
  // Fit Mode for images/videos
  objectFit?: 'cover' | 'contain' | 'fill';  // Default: 'contain'
  objectPosition?: string;  // CSS object-position, e.g., 'center top', 'left center'
  /** Background color for the empty space when objectFit is 'contain'. null/undefined = transparent */
  containBgColor?: string | null;
  backgroundPattern?: string;    // CSS background-image pattern for color elements
  // Placeholder mode (for production preview of empty media fields)
  isPlaceholder?: boolean;       // true = render a visual placeholder instead of actual content
  placeholderLabel?: string;     // Label to show inside the placeholder (e.g. "Imagen de fondo")
}

export interface RenderProps {
  designMD: DesignMD;
  textOverlay: string;
  timelineElements: TimelineElement[];
  layers?: TimelineLayer[];
  onElementClick?: (id: string) => void;
  onElementContextMenu?: (id: string, e: React.MouseEvent) => void;
  onElementDoubleClick?: (id: string) => void;
  onElementPositionChange?: (id: string, x: number, y: number) => void;
  onElementTransformChange?: (id: string, updates: Partial<TimelineElement>) => void;
  onElementDuplicate?: (id: string) => void;
  onElementDelete?: (id: string) => void;
  onElementLock?: (id: string) => void;
  selectedElementId?: string | null;
  activeLayerId?: string | null;
  activeAction?: 'move' | 'scale' | 'rotate';
  brandVisibility?: { logo: boolean; frame: boolean; background: boolean };
  outputFormat?: 'video' | 'image';
  onDragStart?: (e: React.PointerEvent, id: string, origPos: { x: number; y: number; w: number; h: number; rotation?: number }) => void;
  startResize?: (e: React.PointerEvent, id: string, origPos: { x: number; y: number; w: number; h: number; rotation?: number }) => void;
  startRotate?: (e: React.PointerEvent, id: string, origPos: { x: number; y: number; w: number; h: number; rotation?: number }) => void;
  snapGuides?: { x?: number; y?: number };
}

// ═══ Content Grid / Malla de Contenidos ═══

export type ContentStatus = 'idea' | 'draft' | 'in-review' | 'approved' | 'scheduled' | 'published';

export interface ContentPillar {
  id: string;
  name: string;
  color: string;
  icon?: string;
}

export type Platform = 'instagram' | 'tiktok' | 'youtube' | 'facebook' | 'twitter' | 'linkedin';

export interface ContentPiece {
  id: string;
  projectId?: string;
  companyId: string;
  title: string;
  description?: string;
  status: ContentStatus;
  pillarId?: string;
  platforms: Platform[];
  scheduledDate?: string;
  scheduledTime?: string;
  caption?: string;
  hashtags?: string[];
  thumbnailUrl?: string;
  createdAt: string;
  updatedAt: string;
  publishedAt?: string;
  notes?: string;
}

export interface ContentCalendar {
  companyId: string;
  pillars: ContentPillar[];
  pieces: ContentPiece[];
}

// ═══ Batch Production ═══

/** A single piece in a batch production run */
export interface BatchPieceData {
  /** Index (0-based) */
  index: number;
  /** Background file (blob URL) */
  backgroundUrl: string;
  /** Original filename of the background file */
  backgroundFilename: string;
  /** Field data for this piece (fieldId → value) */
  fieldData: Record<string, string>;
  /** Validation status */
  isValid: boolean;
  /** Validation errors per field */
  errors: Record<string, string>;
}

// ═══ Express Editor Types ═══

// ═══ Express Editor — Scene-based Storyboard ═══

/** Layout presets for content scenes */
export type SceneLayout = 'fullscreen-media' | 'media-left' | 'media-right' | 'text-only' | 'split' | 'overlay';

// ═══ Template Field Schema (new model for Template Builder) ═══

/** The explicit nature of an element in a template */
export type TemplateFieldNature = 'static' | 'brand-variable' | 'editable-slot';

/** Brand variable sources that auto-resolve from DesignMD / CompanyProfile */
export type BrandSource = 'brand-name' | 'tagline' | 'title-font' | 'body-font' | 'primary-color' | 'secondary-color' | 'logo' | 'intro-video' | 'outro-video' | 'instagram' | 'tiktok' | 'twitter' | 'youtube' | 'website';

/** Field type for template schema */
export type TemplateFieldType = 'image' | 'text' | 'video' | 'shape' | 'sticker';

/** Validation rules for editable-slot fields */
export interface TemplateFieldRules {
  // image / video
  aspectRatio?: string;       // e.g. '16:9'
  minWidth?: number;
  minHeight?: number;
  // text
  maxChars?: number;
  multiline?: boolean;
}

/** Visual style for a template field */
export interface TemplateFieldStyle {
  /** How media (images/videos) fits within its bounding box */
  mediaFit?: 'cover' | 'contain' | 'fill';
  /** CSS mix-blend-mode for media effects (e.g., removing black/white backgrounds) */
  blendMode?: 'normal' | 'multiply' | 'screen' | 'overlay' | 'soft-light' | 'color-dodge';
  /** Use brand typographic role for font/size/weight/color (default: true) */
  useBrandStyle?: boolean;
  /** Typographic role — resolves font/size/weight/color from DesignMD when useBrandStyle is true */
  textRole?: 'title' | 'subtitle' | 'paragraph';
  fontSize?: number;
  fontWeight?: number;
  fontFamily?: string;
  textAlign?: 'left' | 'center' | 'right';
  color?: string;
  opacity?: number;
  // Shape-specific
  shapeType?: 'rectangle' | 'circle' | 'triangle' | 'line' | 'arrow' | 'star';
  shapeFill?: string;
  shapeStroke?: string;
  shapeStrokeWidth?: number;
  shapeCornerRadius?: number;
  // Sticker-specific (for social/contact brand variables)
  sticker?: StickerConfig;
}

/** Configuration for brand sticker fields (icon + text composites) */
export interface StickerConfig {
  /** Show the platform icon (default: true) */
  showIcon: boolean;
  /** Icon placement relative to text (default: 'left') */
  iconPosition: 'left' | 'right';
  /** Show @ before handle (default: true for socials, false for website) */
  showAtPrefix: boolean;
  /** Visual style: plain text or pill (rounded bg) */
  stickerStyle: 'plain' | 'pill';
  /** Gap in px between icon and text (default: 6) */
  gap: number;
  /** Icon color override (default: brand primary) */
  iconColor?: string;
}

/**
 * TemplateField — A single element in the template schema.
 * 
 * Each field has an explicit `nature` that determines its behavior:
 * - `static`: Fixed decorative element, never editable by end-user.
 * - `brand-variable`: Auto-fills from DesignMD (logo, name, handles). No form field generated.
 * - `editable-slot`: Becomes a form input in production. The only type that generates a form field.
 */
export interface TemplateField {
  id: string;
  nature: TemplateFieldNature;
  label: string;
  type: TemplateFieldType;
  required: boolean;

  /** Static content (for nature='static', the actual rendered content; for others, placeholder text) */
  content: string;

  /** Position in the canvas (% of canvas) */
  position: { x: number; y: number; w: number; h: number; rotation?: number };

  /** Brand auto-fill source (only for nature='brand-variable') */
  brandSource?: BrandSource;
  /** ID of a BrandContentPiece to use as default (e.g. a logo badge asset) */
  brandAssetId?: string;

  /** Validation rules (primarily for nature='editable-slot') */
  rules?: TemplateFieldRules;

  /** Visual style */
  style: TemplateFieldStyle;

  /** Order in the production form (only for editable-slots). Lower = first */
  formOrder: number;

  /** Layer visibility — hidden layers don't render on canvas but aren't deleted. Default: true */
  visible?: boolean;
  /** Layer lock — locked layers can't be selected/moved on canvas. Default: false */
  locked?: boolean;
  /** Background layer — pinned to the bottom of the z-stack. Default: false */
  isBackground?: boolean;
}

// ═══ Legacy Express Field (kept for backward compatibility) ═══

/** A single editable field within a scene (legacy format) */
export interface ExpressField {
  id: string;
  type: 'text' | 'media' | 'logo' | 'shape';
  label: string;
  placeholder: string;
  required: boolean;
  /**
   * Brand variable source — auto-resolves from DesignMD / CompanyProfile.
   * e.g. 'brand-name' → company.name, 'instagram' → company.socialLinks.instagram
   * When set, the field auto-fills but the user can still override it.
   */
  brandSource?: BrandSource;
  /** ID of a BrandContentPiece to use as default value (e.g. a logo badge asset) */
  brandAssetId?: string;
  /** Position within the scene (% of scene canvas) */
  position: { x: number; y: number; w: number; h: number };
  /** Default style */
  style: {
    fontSize?: number;
    fontWeight?: number;
    fontFamily?: string;
    textAlign?: string;
    color?: string;       // If not set, resolved from brandSource
    opacity?: number;
    // Shape-specific
    shapeType?: 'rectangle' | 'circle' | 'triangle' | 'line' | 'arrow' | 'star';
    shapeFill?: string;
    shapeStroke?: string;
    shapeStrokeWidth?: number;
    shapeCornerRadius?: number;
  };
}

/** A single scene block in the storyboard */
export interface ExpressScene {
  id: string;
  type: 'intro' | 'content' | 'outro' | 'transition';
  name: string;
  durationSeconds: number;
  layout: SceneLayout;
  /** Legacy field format (backward compat) */
  editableFields: ExpressField[];
  /** New schema-based fields (used by redesigned builder) */
  fields?: TemplateField[];
  /** Scene-level transition animation */
  transition?: { type: string; duration: number };
  /** Background: solid color, gradient, or media (user-replaceable) */
  background?: {
    type: 'solid' | 'gradient' | 'media' | 'brand';
    value?: string;   // color hex or media URL
  };
  /** Thumbnail for storyboard card display */
  thumbnailUrl?: string;
  /** Source for intro/outro scenes: 'brand' = auto from DesignMD, 'form' = user uploads video */
  segmentSource?: 'brand' | 'form';
  /** Form field label (only when segmentSource === 'form'), e.g. "Video de intro" */
  segmentFieldLabel?: string;
  /** Whether the form field is required (only when segmentSource === 'form'). Default true */
  segmentFieldRequired?: boolean;
  /** Transition applied at the boundary of this segment (e.g. intro→content or content→outro) */
  segmentTransition?: { type: string; duration: number };
  /** Video position for segment scenes (center-based %, like TemplateField.position) */
  segmentVideoX?: number;      // center X (0-100), default 50
  segmentVideoY?: number;      // center Y (0-100), default 50
  segmentVideoW?: number;      // width (0-100), default 100
  segmentVideoH?: number;      // height (0-100), default 100
  /** Object fit mode for the segment video */
  segmentVideoFit?: 'cover' | 'contain' | 'fill';
}

/** Express template — a sequence of scenes */
export interface ExpressTemplate {
  id: string;
  name: string;
  description: string;
  category: 'social' | 'ad' | 'promo' | 'story' | 'announcement';
  icon: string;
  aspectRatio: string;
  format: 'video' | 'image';
  /** Ordered list of scenes (the storyboard) */
  scenes: ExpressScene[];
  /** If set, this template belongs to a specific brand */
  brandId?: string;
  /** Auto-include brand audio */
  usesBrandAudio: boolean;
  /** User-created template */
  isCustom?: boolean;
  createdAt?: string;
}
