import { Component, Input, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';

interface ColorPoint {
  hex: string;
  rgb: { r: number; g: number; b: number };
  hsl: { h: number; s: number; l: number };
  angle: number;
  radius: number;
  percentage?: number;
  name?: string;
}

@Component({
  selector: 'app-color-wheel-visualizer',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './color-wheel-visualizer.html',
  styleUrls: ['./color-wheel-visualizer.scss']
})
export class ColorWheelVisualizerComponent implements OnInit, OnChanges {
  @Input() colors: Array<{
    hex: string;
    rgb: { r: number; g: number; b: number };
    percentage: number;
    name?: string;
  }> = [];
  
  @Input() size: number = 200; // 色轮大小
  @Input() showLabels: boolean = true; // 是否显示标签
  @Input() showPercentages: boolean = true; // 是否显示百分比

  colorPoints: ColorPoint[] = [];
  centerX: number = 100;
  centerY: number = 100;
  outerRadius: number = 90;
  innerRadius: number = 30;
  
  // 暴露Math对象供模板使用
  Math = Math;

  ngOnInit(): void {
    this.updateColorPoints();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['colors'] || changes['size']) {
      this.updateColorPoints();
    }
  }

  private updateColorPoints(): void {
    this.colorPoints = this.colors.map(color => {
      const hsl = this.rgbToHsl(color.rgb.r, color.rgb.g, color.rgb.b);
      
      return {
        hex: color.hex,
        rgb: color.rgb,
        hsl,
        angle: hsl.h,
        radius: hsl.s * (this.outerRadius - this.innerRadius) + this.innerRadius,
        percentage: color.percentage,
        name: color.name
      };
    });
  }

  /**
   * 将RGB转换为HSL
   */
  private rgbToHsl(r: number, g: number, b: number): { h: number; s: number; l: number } {
    r /= 255;
    g /= 255;
    b /= 255;

    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    let h = 0;
    let s = 0;
    const l = (max + min) / 2;

    if (max !== min) {
      const d = max - min;
      s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

      switch (max) {
        case r:
          h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
          break;
        case g:
          h = ((b - r) / d + 2) / 6;
          break;
        case b:
          h = ((r - g) / d + 4) / 6;
          break;
      }
    }

    return {
      h: h * 360,
      s: s,
      l: l
    };
  }

  /**
   * 获取色轮背景渐变（用SVG实现）
   */
  getColorWheelGradient(): string {
    const steps = 60;
    const gradientStops: string[] = [];
    
    for (let i = 0; i < steps; i++) {
      const hue = (i / steps) * 360;
      const color = this.hslToHex(hue, 100, 50);
      const percentage = (i / steps) * 100;
      gradientStops.push(`${color} ${percentage}%`);
    }
    
    return `conic-gradient(${gradientStops.join(', ')})`;
  }

  /**
   * 将HSL转换为十六进制颜色
   */
  private hslToHex(h: number, s: number, l: number): string {
    s /= 100;
    l /= 100;

    const c = (1 - Math.abs(2 * l - 1)) * s;
    const x = c * (1 - Math.abs((h / 60) % 2 - 1));
    const m = l - c / 2;
    
    let r = 0, g = 0, b = 0;

    if (0 <= h && h < 60) {
      r = c; g = x; b = 0;
    } else if (60 <= h && h < 120) {
      r = x; g = c; b = 0;
    } else if (120 <= h && h < 180) {
      r = 0; g = c; b = x;
    } else if (180 <= h && h < 240) {
      r = 0; g = x; b = c;
    } else if (240 <= h && h < 300) {
      r = x; g = 0; b = c;
    } else if (300 <= h && h < 360) {
      r = c; g = 0; b = x;
    }

    const toHex = (value: number) => {
      const hex = Math.round((value + m) * 255).toString(16);
      return hex.length === 1 ? '0' + hex : hex;
    };

    return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
  }

  /**
   * 获取颜色点在色轮上的坐标
   */
  getColorPosition(color: ColorPoint): { x: number; y: number } {
    const angleRad = (color.angle - 90) * (Math.PI / 180);
    const x = this.centerX + color.radius * Math.cos(angleRad);
    const y = this.centerY + color.radius * Math.sin(angleRad);
    
    return { x, y };
  }

  /**
   * 获取标签位置（在色轮外侧）
   */
  getLabelPosition(color: ColorPoint): { x: number; y: number } {
    const angleRad = (color.angle - 90) * (Math.PI / 180);
    const labelRadius = this.outerRadius + 15;
    const x = this.centerX + labelRadius * Math.cos(angleRad);
    const y = this.centerY + labelRadius * Math.sin(angleRad);
    
    return { x, y };
  }

  /**
   * 获取文本锚点（根据角度决定左对齐还是右对齐）
   */
  getTextAnchor(angle: number): string {
    if (angle > 90 && angle < 270) {
      return 'end';
    }
    return 'start';
  }

  /**
   * 生成色轮渐变ID
   */
  get colorWheelGradientId(): string {
    return 'color-wheel-gradient';
  }

  /**
   * 生成圆锥渐变的SVG定义
   */
  getConicGradientStops(): Array<{ offset: string; color: string }> {
    const steps = 60;
    const stops: Array<{ offset: string; color: string }> = [];
    
    for (let i = 0; i <= steps; i++) {
      const hue = (i / steps) * 360;
      const color = this.hslToHex(hue, 100, 50);
      const offset = ((i / steps) * 100).toFixed(1);
      stops.push({ offset: `${offset}%`, color });
    }
    
    return stops;
  }
}

