import { createSignal, createEffect, onCleanup, type Component } from 'solid-js';
import clsx from 'clsx';

/**
 * Window chrome clip-path polygon (8 vertices).
 * TL: straight corner. TR: deep notch for floating controls island.
 * BL: 45-degree angled slope (20px depth). BR: straight corner.
 */
export const CHROME_CLIP_PATH = `polygon(
  0 0,
  calc(100% - 182px) 0,
  calc(100% - 140px) 42px,
  calc(100% - 16px) 42px,
  100% 58px,
  100% 100%,
  20px 100%,
  0 calc(100% - 20px)
)`;

interface GlowPerimeterProps {
  class?: string;
}

/**
 * Animated glow-line perimeter (WIN-02).
 * SVG path with stroke draws a 2px ring 6px inset from the window edge.
 * Sweep uses a conic-gradient CSS mask for perfectly smooth leading/trailing fades.
 * Four edge-strip divs with backdrop-filter create frosted glass margin between glow ring and chrome edge.
 * Z-index 10 renders above all content.
 */
export const GlowPerimeter: Component<GlowPerimeterProps> = (rawProps) => {
  let containerRef: HTMLDivElement | undefined;
  const [size, setSize] = createSignal({ w: 0, h: 0 });

  // Track container dimensions
  createEffect(() => {
    if (!containerRef) return;
    const observer = new ResizeObserver((entries) => {
      const rect = entries[0].contentRect;
      setSize({ w: Math.round(rect.width), h: Math.round(rect.height) });
    });
    observer.observe(containerRef);
    onCleanup(() => observer.disconnect());
  });

  /**
   * SVG path for the glow ring, 6px perpendicular inset from CHROME_CLIP_PATH.
   * 8 vertices matching the window chrome shape.
   */
  const glowPath = () => {
    const { w, h } = size();
    if (w === 0 || h === 0) return '';
    return [
      `M 6,6`,
      `L ${w - 185},6`,       // top edge
      `L ${w - 143},48`,      // notch left diagonal
      `L ${w - 19},48`,       // notch bottom
      `L ${w - 6},61`,        // notch right diagonal
      `L ${w - 6},${h - 6}`,  // right edge → BR
      `L 23,${h - 6}`,        // bottom edge → BL
      `L 6,${h - 23}`,        // BL diagonal
      `Z`,                     // left edge → TL
    ].join(' ');
  };

  /** Shared blur style for edge strips (const + spread for reliable SolidJS rendering) */
  const blurStyle = {
    'backdrop-filter': 'blur(12px)',
    '-webkit-backdrop-filter': 'blur(12px)',
  };

  /**
   * SVG path for the margin ring (evenodd).
   * Outer rect = full bounds, inner path = glow ring polygon.
   * Used for the dark tint fill — covers entire margin strip with no gaps,
   * including diagonal areas that blur strip divs can't darken uniformly.
   */
  const marginRingPath = () => {
    const { w, h } = size();
    if (w === 0 || h === 0) return '';
    return [
      // Outer path: matches CHROME_CLIP_PATH exactly (8 vertices)
      `M 0,0 L ${w - 182},0 L ${w - 140},42 L ${w - 16},42 L ${w},58 L ${w},${h} L 20,${h} L 0,${h - 20} Z`,
      // Inner path: glow ring (6px inset)
      `M 6,6 L ${w - 185},6 L ${w - 143},48 L ${w - 19},48 L ${w - 6},61 L ${w - 6},${h - 6} L 23,${h - 6} L 6,${h - 23} Z`,
    ].join(' ');
  };


  return (
    <div
      ref={containerRef}
      class={clsx('hh-glow-perimeter', rawProps.class)}
      style={{
        position: 'absolute',
        inset: '0',
        'pointer-events': 'none',
        'z-index': '10',
      }}
    >
      {/* Diagonal/notch blur strips — rendered FIRST so straight strips sit on top,
          hiding anti-aliased edges at joints. Parent clip-path trims excess. */}

      {/* BL corner diagonal: 45° strip covering margin between chrome (0,h-20)→(20,h) and glow (6,h-23)→(23,h-6) */}
      {size().w > 0 && (
        <div style={{
          position: 'absolute',
          left: '-3px',
          top: `${size().h - 17}px`,
          width: '30px',
          height: '10px',
          transform: 'rotate(45deg)',
          ...blurStyle,
        }} />
      )}

      {/* TR notch left diagonal: 45° strip covering margin along (w-182,0)→(w-140,42) */}
      {size().w > 0 && (
        <div style={{
          position: 'absolute',
          left: `${size().w - 194}px`,
          top: '20px',
          width: '63px',
          height: '8px',
          transform: 'rotate(45deg)',
          ...blurStyle,
        }} />
      )}

      {/* TR notch horizontal: margin strip along bottom of notch (y=42 to y=48) */}
      {size().w > 0 && (
        <div style={{
          position: 'absolute',
          left: `${size().w - 142}px`,
          top: '42px',
          width: '125px',
          height: '6px',
          ...blurStyle,
        }} />
      )}

      {/* TR notch right diagonal: 45° strip covering margin along (w-16,42)→(w,58) */}
      {size().w > 0 && (
        <div style={{
          position: 'absolute',
          left: `${size().w - 24}px`,
          top: '48px',
          width: '27px',
          height: '8px',
          transform: 'rotate(45deg)',
          ...blurStyle,
        }} />
      )}

      {/* Straight edge blur strips — on top of diagonal divs to hide seams */}
      <div style={{ position: 'absolute', top: '0', left: '0', right: '0', height: '6px', ...blurStyle }} />
      <div style={{ position: 'absolute', top: '0', right: '0', bottom: '0', width: '6px', ...blurStyle }} />
      <div style={{ position: 'absolute', bottom: '0', left: '0', right: '0', height: '6px', ...blurStyle }} />
      <div style={{ position: 'absolute', top: '0', left: '0', bottom: '0', width: '6px', ...blurStyle }} />

      <svg
        width="100%"
        height="100%"
        style={{ position: 'absolute', inset: '0', overflow: 'visible' }}
      >
        {/* Dark tint ring — SVG evenodd covers entire margin strip continuously,
            including diagonals where blur divs alone can't darken uniformly */}
        <path
          d={marginRingPath()}
          fill="rgba(3, 7, 18, 0.4)"
          fill-rule="evenodd"
        />

        {/* Base ring — always visible, subtle glow */}
        <path
          d={glowPath()}
          fill="none"
          stroke="var(--hh-color-primary)"
          stroke-width="2"
          opacity="0.6"
          style={{
            filter: 'drop-shadow(0 0 3px color-mix(in srgb, var(--hh-color-primary) 50%, transparent))',
          }}
        />

        {/* Sweep — single path masked by conic-gradient for smooth fade on both edges */}
        <path
          d={glowPath()}
          fill="none"
          stroke="var(--hh-color-primary)"
          stroke-width="2"
          style={{
            '-webkit-mask-image': `conic-gradient(
              from var(--hh-sweep-angle),
              rgba(255,255,255,0.01) 0deg,
              rgba(255,255,255,0.03) 30deg,
              rgba(255,255,255,0.06) 60deg,
              rgba(255,255,255,0.1) 100deg,
              rgba(255,255,255,0.16) 140deg,
              rgba(255,255,255,0.24) 180deg,
              rgba(255,255,255,0.35) 220deg,
              rgba(255,255,255,0.5) 255deg,
              rgba(255,255,255,0.7) 285deg,
              rgba(255,255,255,0.9) 310deg,
              white 330deg,
              rgba(255,255,255,0.7) 340deg,
              rgba(255,255,255,0.4) 348deg,
              rgba(255,255,255,0.15) 354deg,
              rgba(255,255,255,0.04) 358deg,
              rgba(255,255,255,0.01) 360deg
            )`,
            'mask-image': `conic-gradient(
              from var(--hh-sweep-angle),
              rgba(255,255,255,0.01) 0deg,
              rgba(255,255,255,0.03) 30deg,
              rgba(255,255,255,0.06) 60deg,
              rgba(255,255,255,0.1) 100deg,
              rgba(255,255,255,0.16) 140deg,
              rgba(255,255,255,0.24) 180deg,
              rgba(255,255,255,0.35) 220deg,
              rgba(255,255,255,0.5) 255deg,
              rgba(255,255,255,0.7) 285deg,
              rgba(255,255,255,0.9) 310deg,
              white 330deg,
              rgba(255,255,255,0.7) 340deg,
              rgba(255,255,255,0.4) 348deg,
              rgba(255,255,255,0.15) 354deg,
              rgba(255,255,255,0.04) 358deg,
              rgba(255,255,255,0.01) 360deg
            )`,
            animation: 'hh-sweep-rotate 8s linear infinite',
            filter: 'drop-shadow(0 0 6px var(--hh-color-primary)) drop-shadow(0 0 14px var(--hh-color-primary))',
          }}
        />
      </svg>
    </div>
  );
};
