import { forwardRef } from 'react';

const RIM_SHADOWS = {
  none: [],
  subtle: ['var(--rim-light-inner)', 'var(--rim-light-outer)'],
  pronounced: ['var(--rim-light-inner)', 'var(--rim-light-outer)'],
  'ember-subtle': ['var(--rim-light-inner)', 'var(--ember-rim-subtle)'],
  'ember-pronounced': ['var(--rim-light-inner)', 'var(--ember-rim-pronounced)'],
};

const ELEVATION_SHADOWS = {
  flat: [],
  ambient: ['var(--elevation-ambient)'],
  pronounced: ['var(--elevation-pronounced)'],
};

const CORNER_LIGHT_TOKENS = {
  subtle: {
    warm: 'var(--corner-light-warm-subtle)',
    cool: 'var(--corner-light-cool-subtle)',
  },
  chrome: {
    warm: 'var(--corner-light-warm)',
    cool: 'var(--corner-light-cool)',
  },
};

function composeBackground(tint, cornerLights) {
  const fill = `var(--glass-surface-${tint})`;
  if (cornerLights === 'none') {
    return fill;
  }
  const tokens =
    CORNER_LIGHT_TOKENS[cornerLights] ?? CORNER_LIGHT_TOKENS.subtle;
  return [
    `linear-gradient(${fill}, ${fill}) padding-box`,
    `radial-gradient(at 0% 100%, ${tokens.warm} 0%, transparent 42%) border-box`,
    `radial-gradient(at 100% 0%, ${tokens.cool} 0%, transparent 42%) border-box`,
    'var(--chip-border-base) border-box',
  ].join(', ');
}

const GlassSurface = forwardRef(function GlassSurface(
  {
    as: As = 'div',
    tint = 'mid',
    rim = 'subtle',
    elevation = 'flat',
    blur = 'mid',
    cornerLights = 'subtle',
    className,
    style,
    children,
    ...rest
  },
  ref
) {
  const shadowParts = [
    ...(RIM_SHADOWS[rim] ?? []),
    ...(ELEVATION_SHADOWS[elevation] ?? []),
  ];
  const composedStyle = {
    background: composeBackground(tint, cornerLights),
    backdropFilter: `blur(var(--glass-blur-${blur})) saturate(var(--glass-saturate))`,
    WebkitBackdropFilter: `blur(var(--glass-blur-${blur})) saturate(var(--glass-saturate))`,
    boxShadow: shadowParts.length > 0 ? shadowParts.join(', ') : undefined,
    ...(cornerLights !== 'none' ? { border: '1px solid transparent' } : {}),
    ...style,
  };

  return (
    <As ref={ref} className={className} style={composedStyle} {...rest}>
      {children}
    </As>
  );
});

export default GlassSurface;
