// Responsive Breakpoints
// Breakpoints for mobile, tablet, and desktop

export interface BreakpointConfig {
  sm: string;
  md: string;
  lg: string;
  xl: string;
  '2xl': string;
}

export const breakpoints: BreakpointConfig = {
  sm: '640px',   // Mobile landscape / small tablet
  md: '768px',   // Tablet portrait
  lg: '1024px',  // Tablet landscape / small desktop
  xl: '1280px',  // Desktop
  '2xl': '1536px', // Large desktop
};

export type BreakpointName = keyof BreakpointConfig;

export interface DeviceType {
  mobile: boolean;
  tablet: boolean;
  desktop: boolean;
}

export class BreakpointService {
  /**
   * Get breakpoint value
   */
  static getBreakpoint(name: BreakpointName): string {
    return breakpoints[name];
  }

  /**
   * Get min-width media query
   */
  static getMinWidthQuery(name: BreakpointName): string {
    return `(min-width: ${breakpoints[name]})`;
  }

  /**
   * Get max-width media query
   */
  static getMaxWidthQuery(name: BreakpointName): string {
    return `(max-width: ${breakpoints[name]})`;
  }

  /**
   * Get range media query
   */
  static getRangeQuery(
    min: BreakpointName | null,
    max: BreakpointName | null
  ): string {
    const queries: string[] = [];

    if (min) {
      queries.push(this.getMinWidthQuery(min));
    }
    if (max) {
      queries.push(this.getMaxWidthQuery(max));
    }

    return queries.join(' and ');
  }

  /**
   * Detect device type from window width
   */
  static detectDeviceType(width: number): DeviceType {
    return {
      mobile: width < parseInt(breakpoints.md),
      tablet: width >= parseInt(breakpoints.md) && width < parseInt(breakpoints.lg),
      desktop: width >= parseInt(breakpoints.lg),
    };
  }

  /**
   * Check if current viewport matches breakpoint
   */
  static matchesBreakpoint(name: BreakpointName): boolean {
    if (typeof window === 'undefined') {
      return false;
    }
    return window.matchMedia(this.getMinWidthQuery(name)).matches;
  }

  /**
   * Get responsive value based on breakpoint
   */
  static getResponsiveValue<T>(
    values: Partial<Record<BreakpointName, T>>,
    defaultValue: T
  ): T {
    if (typeof window === 'undefined') {
      return defaultValue;
    }

    // Check from largest to smallest
    const breakpointOrder: BreakpointName[] = ['2xl', 'xl', 'lg', 'md', 'sm'];

    for (const bp of breakpointOrder) {
      if (values[bp] !== undefined && this.matchesBreakpoint(bp)) {
        return values[bp] as T;
      }
    }

    return defaultValue;
  }
}

