const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Sub-schema: Posizione layer
const PositionSchema = new Schema({
  x: { type: Number, required: true, min: 0, max: 1 },
  y: { type: Number, required: true, min: 0, max: 1 },
  w: { type: Number, required: true, min: 0, max: 1 },
  h: { type: Number, required: true, min: 0, max: 1 }
}, { _id: false });

// Sub-schema: Ombra
const ShadowSchema = new Schema({
  enabled: { type: Boolean, default: false },
  blur: { type: Number, default: 10 },
  spread: { type: Number, default: 0 },
  offsetX: { type: Number, default: 0 },
  offsetY: { type: Number, default: 4 },
  color: { type: String, default: 'rgba(0,0,0,0.5)' }
}, { _id: false });

// Sub-schema: Stroke
const StrokeSchema = new Schema({
  enabled: { type: Boolean, default: false },
  width: { type: Number, default: 2 },
  color: { type: String, default: '#000000' }
}, { _id: false });

// Sub-schema: Border
const BorderSchema = new Schema({
  enabled: { type: Boolean, default: false },
  width: { type: Number, default: 2 },
  color: { type: String, default: '#ffffff' },
  style: { type: String, enum: ['solid', 'dashed', 'dotted'], default: 'solid' }
}, { _id: false });

// Sub-schema: Gradient Stop
const GradientStopSchema = new Schema({
  position: { type: Number, required: true, min: 0, max: 1 },
  color: { type: String, required: true }
}, { _id: false });

// Sub-schema: Overlay
const OverlaySchema = new Schema({
  enabled: { type: Boolean, default: false },
  type: { type: String, enum: ['solid', 'gradient'], default: 'gradient' },
  color: { type: String },
  direction: { type: String, default: 'to-bottom' },
  stops: [GradientStopSchema]
}, { _id: false });

// Sub-schema: Fallback
const FallbackSchema = new Schema({
  type: { type: String, enum: ['solid', 'gradient'], default: 'solid' },
  color: { type: String },
  direction: { type: String },
  colors: [{ type: String }]
}, { _id: false });

// Sub-schema: Icon
const IconSchema = new Schema({
  enabled: { type: Boolean, default: false },
  name: { type: String },
  size: { type: Number, default: 24 },
  color: { type: String, default: '#ffffff' }
}, { _id: false });

// Sub-schema: Stile Layer (unificato per immagini e testi)
const LayerStyleSchema = new Schema({
  // Comuni
  opacity: { type: Number, default: 1, min: 0, max: 1 },
  
  // Per immagini
  objectFit: { type: String, enum: ['cover', 'contain', 'fill', 'none'], default: 'cover' },
  blur: { type: Number, default: 0 },
  borderRadius: { type: Number, default: 0 },
  overlay: OverlaySchema,
  border: BorderSchema,
  
  // Per testi
  fontFamily: { type: String },
  fontWeight: { type: Number, default: 400 },
  fontSize: { type: Number },
  fontSizeMin: { type: Number },
  fontSizeMax: { type: Number },
  autoFit: { type: Boolean, default: false },
  fontStyle: { type: String, enum: ['normal', 'italic'], default: 'normal' },
  color: { type: String },
  textAlign: { type: String, enum: ['left', 'center', 'right'], default: 'center' },
  textTransform: { type: String, enum: ['none', 'uppercase', 'lowercase', 'capitalize'], default: 'none' },
  letterSpacing: { type: Number, default: 0 },
  lineHeight: { type: Number, default: 1.2 },
  
  // Effetti
  shadow: ShadowSchema,
  stroke: StrokeSchema
}, { _id: false });

// Sub-schema: Layer
const LayerSchema = new Schema({
  id: { type: String, required: true },
  type: { 
    type: String, 
    required: true,
    enum: ['backgroundImage', 'mainImage', 'logo', 'title', 'subtitle', 'eventDate', 'eventTime', 'location', 'contacts', 'extraText', 'customText', 'customImage', 'shape', 'divider']
  },
  zIndex: { type: Number, default: 0 },
  position: { type: PositionSchema, required: true },
  anchor: { 
    type: String, 
    enum: ['top-left', 'top-center', 'top-right', 'center-left', 'center', 'center-right', 'bottom-left', 'bottom-center', 'bottom-right'],
    default: 'center'
  },
  required: { type: Boolean, default: false },
  visible: { type: Boolean, default: true },
  locked: { type: Boolean, default: false },
  maxLines: { type: Number },
  fallback: FallbackSchema,
  icon: IconSchema,
  style: { type: LayerStyleSchema, default: () => ({}) }
}, { _id: false });

// Sub-schema: Logo Slot
const LogoSlotSchema = new Schema({
  id: { type: String, required: true },
  position: { type: PositionSchema, required: true },
  anchor: { type: String, default: 'center' },
  style: { type: LayerStyleSchema, default: () => ({}) }
}, { _id: false });

// Sub-schema: Logo Slots Config
const LogoSlotsConfigSchema = new Schema({
  enabled: { type: Boolean, default: true },
  maxCount: { type: Number, default: 3, min: 1, max: 10 },
  collapseIfEmpty: { type: Boolean, default: true },
  slots: [LogoSlotSchema]
}, { _id: false });

// Sub-schema: Format
const FormatSchema = new Schema({
  preset: { type: String, default: 'custom' }, // A4, A3, Instagram, Facebook, custom
  width: { type: Number, required: true },
  height: { type: Number, required: true },
  unit: { type: String, enum: ['px', 'mm', 'in'], default: 'px' },
  dpi: { type: Number, default: 300 }
}, { _id: false });

// Sub-schema: Safe Area
const SafeAreaSchema = new Schema({
  top: { type: Number, default: 0, min: 0, max: 0.5 },
  right: { type: Number, default: 0, min: 0, max: 0.5 },
  bottom: { type: Number, default: 0, min: 0, max: 0.5 },
  left: { type: Number, default: 0, min: 0, max: 0.5 }
}, { _id: false });

// Sub-schema: Palette
const PaletteSchema = new Schema({
  primary: { type: String, default: '#e94560' },
  secondary: { type: String, default: '#0f3460' },
  accent: { type: String, default: '#ffd700' },
  background: { type: String, default: '#1a1a2e' },
  text: { type: String, default: '#ffffff' },
  textSecondary: { type: String, default: '#cccccc' },
  textMuted: { type: String, default: '#888888' }
}, { _id: false });

// Sub-schema: Typography
const TypographySchema = new Schema({
  titleFont: { type: String, default: 'Montserrat' },
  headingFont: { type: String, default: 'Bebas Neue' },
  bodyFont: { type: String, default: 'Open Sans' },
  accentFont: { type: String, default: 'Playfair Display' }
}, { _id: false });

// Sub-schema: AI Prompt Hints
const AiPromptHintsSchema = new Schema({
  backgroundImage: { type: String },
  mainImage: { type: String }
}, { _id: false });

// Sub-schema: Metadata
const TemplateMetadataSchema = new Schema({
  author: { type: String, default: 'System' },
  version: { type: String, default: '1.0.0' },
  tags: [{ type: String }],
  isPublic: { type: Boolean, default: false },
  usageCount: { type: Number, default: 0 }
}, { _id: false });

// MAIN SCHEMA: Template
const TemplateSchema = new Schema({
  name: { type: String, required: true, trim: true, maxlength: 200 },
  templateType: { type: String, required: true, trim: true, index: true },
  description: { type: String, maxlength: 1000 },
  
  format: { type: FormatSchema, required: true },
  safeArea: { type: SafeAreaSchema, default: () => ({}) },
  backgroundColor: { type: String, default: '#1a1a2e' },
  
  layers: { type: [LayerSchema], required: true, validate: [arr => arr.length > 0, 'Almeno un layer richiesto'] },
  logoSlots: { type: LogoSlotsConfigSchema, default: () => ({}) },
  
  palette: { type: PaletteSchema, default: () => ({}) },
  typography: { type: TypographySchema, default: () => ({}) },
  defaultAiPromptHints: { type: AiPromptHintsSchema, default: () => ({}) },
  
  previewUrl: { type: String },
  thumbnailUrl: { type: String },
  
  metadata: { type: TemplateMetadataSchema, default: () => ({}) },
  
  isActive: { type: Boolean, default: true },
  userId: { type: Schema.Types.ObjectId, ref: 'User', index: true }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Indexes
TemplateSchema.index({ templateType: 1, isActive: 1 });
TemplateSchema.index({ 'metadata.tags': 1 });
TemplateSchema.index({ name: 'text', description: 'text', templateType: 'text' });

// Virtual: layer count
TemplateSchema.virtual('layerCount').get(function() {
  return this.layers ? this.layers.length : 0;
});

// Methods
TemplateSchema.methods.getLayerById = function(layerId) {
  return this.layers.find(l => l.id === layerId);
};

TemplateSchema.methods.getLayersByType = function(type) {
  return this.layers.filter(l => l.type === type);
};

TemplateSchema.methods.incrementUsage = async function() {
  this.metadata.usageCount = (this.metadata.usageCount || 0) + 1;
  return this.save();
};

// Statics
TemplateSchema.statics.findByType = function(templateType) {
  return this.find({ templateType, isActive: true }).sort({ 'metadata.usageCount': -1 });
};

TemplateSchema.statics.findPublic = function() {
  return this.find({ 'metadata.isPublic': true, isActive: true });
};

module.exports = mongoose.model('Template', TemplateSchema);