"use client"

import type React from "react"
import { useState, useEffect, useRef } from "react"
import { cn } from "@/lib/utils"
import { iconSvgPaths } from "@/lib/icons"

interface PreviewWidgetProps {
  removeImages: boolean
  grayscale: boolean
  // colorblindMode wurde entfernt
  fontSize: number
  disableAnimations: boolean
  largeCursor: boolean
  dyslexiaFont: boolean
  highlightLinks: boolean
  invertColors: boolean
  highlightHeadings: boolean
  // readingMode wurde entfernt
  contrastMode: "normal" | "dark" | "light"
  saturationMode: "normal" | "low" | "high"
  contentScaling: number
  // lineHeight wurde entfernt
  letterSpacing: number
  widgetPosition: "bottom-right" | "bottom-left"
  buttonColor: string
  accentColor: string
  widgetIcon: string
  // New props
  blueFilter: boolean
  muteSounds: boolean
}

export function PreviewWidget({
  removeImages,
  grayscale,
  // colorblindMode wurde entfernt
  fontSize,
  disableAnimations,
  largeCursor,
  dyslexiaFont,
  highlightLinks,
  invertColors,
  highlightHeadings,
  // readingMode wurde entfernt
  contrastMode,
  saturationMode,
  contentScaling,
  // lineHeight wurde entfernt
  letterSpacing,
  widgetPosition,
  buttonColor,
  accentColor,
  widgetIcon,
  // New props
  blueFilter,
  muteSounds,
}: PreviewWidgetProps) {
  const [isOpen, setIsOpen] = useState(false)
  const widgetContainerRef = useRef<HTMLDivElement>(null)

  const SelectedIconClass = iconSvgPaths[widgetIcon] || iconSvgPaths.accessibility
  const resetIconClass = iconSvgPaths.rotateRight
  const closeIconClass = iconSvgPaths.xmark

  const activeFeaturesCount = [
    invertColors,
    grayscale,
    contrastMode !== "normal",
    saturationMode !== "normal",
    highlightLinks,
    highlightHeadings,
    removeImages,
    // colorblindMode wurde entfernt
    fontSize !== 100,
    contentScaling !== 100,
    // lineHeight !== 100, // lineHeight wurde entfernt
    letterSpacing !== 0,
    disableAnimations,
    largeCursor,
    dyslexiaFont,
    // New features
    blueFilter,
    muteSounds,
  ].filter(Boolean).length

  // Effect to load CSS and JS and initialize the widget
  useEffect(() => {
    const baseUrl = "https://v0-next-js-widget-configurator.vercel.app" // Replace with your actual deployed URL

    // Load CSS (only once)
    let cssLink = document.querySelector(`link[href="${baseUrl}/widget.css"]`) as HTMLLinkElement
    if (!cssLink) {
      cssLink = document.createElement("link")
      cssLink.rel = "stylesheet"
      cssLink.href = `${baseUrl}/widget.css`
      document.head.appendChild(cssLink)
    }

    // Load JS (and re-initialize on settings change)
    // We need to ensure the script is loaded before calling initializeAccessibilityWidget
    const loadScript = () => {
      let jsScript = document.querySelector(`script[src="${baseUrl}/widget.js"]`) as HTMLScriptElement
      if (!jsScript) {
        jsScript = document.createElement("script")
        jsScript.src = `${baseUrl}/widget.js`
        jsScript.onload = () => {
          // Ensure the global function is available after script loads
          if (window.initializeAccessibilityWidget) {
            window.initializeAccessibilityWidget()
          }
        }
        document.body.appendChild(jsScript)
      } else {
        // If script is already loaded, just re-initialize
        if (window.initializeAccessibilityWidget) {
          window.initializeAccessibilityWidget()
        }
      }
    }

    loadScript()

    // Cleanup function for when the component unmounts or dialog closes
    return () => {
      // The widget.js cleanup logic is now handled internally by initializeAccessibilityWidget()
      // when it's called again. For a full unmount, we might want to remove the CSS/JS,
      // but for a dialog close, it's usually fine to leave them.
      // For this specific case, since the widget.js is designed to be persistent on the page,
      // we rely on its internal cleanup when re-initialized.
    }
  }, []) // Empty dependency array means this runs once on mount

  // Effect to re-initialize widget when props change
  useEffect(() => {
    if (window.initializeAccessibilityWidget) {
      // This will trigger the widget.js to re-read data attributes and apply settings
      window.initializeAccessibilityWidget()
    }
  }, [
    removeImages,
    grayscale,
    // colorblindMode wurde entfernt
    fontSize,
    disableAnimations,
    largeCursor,
    dyslexiaFont,
    highlightLinks,
    invertColors,
    highlightHeadings,
    // readingMode wurde entfernt
    contrastMode,
    saturationMode,
    contentScaling,
    // lineHeight wurde entfernt
    letterSpacing,
    buttonColor,
    accentColor,
    widgetIcon,
    // New props
    blueFilter,
    muteSounds,
  ])

  // This local state `isOpen` is only for the preview's toggle button
  // The actual widget.js will manage its own open/close state based on its toggle button
  // We need to ensure the preview's toggle button interacts with the actual widget.js
  const handlePreviewToggleClick = () => {
    setIsOpen(!isOpen)
    // Trigger the actual widget's toggle button click
    const actualToggleButton = widgetContainerRef.current?.querySelector(
      "#accessibility-widget-toggle",
    ) as HTMLButtonElement
    if (actualToggleButton) {
      actualToggleButton.click()
    }
  }

  // This local state `isOpen` is only for the preview's close button
  const handlePreviewCloseClick = () => {
    setIsOpen(false)
    // Trigger the actual widget's close button click
    const actualCloseButton = widgetContainerRef.current?.querySelector(".a11y-close-button") as HTMLButtonElement
    if (actualCloseButton) {
      actualCloseButton.click()
    }
  }

  // This local state `isOpen` is only for the preview's reset button
  const handlePreviewResetClick = () => {
    // Trigger the actual widget's reset button click
    const actualResetButton = widgetContainerRef.current?.querySelector(".a11y-reset-button") as HTMLButtonElement
    if (actualResetButton) {
      actualResetButton.click()
    }
  }

  return (
    <div
      ref={widgetContainerRef} // Attach ref to the container
      id="accessibility-widget-container"
      className={cn(
        "fixed z-[9999] transition-all duration-300",
        widgetPosition === "bottom-right" ? "bottom-5 right-5" : "bottom-5 left-5",
      )}
      // Pass all settings as data attributes for widget.js to read
      data-invert-colors={invertColors}
      data-grayscale={grayscale}
      data-contrast-mode={contrastMode}
      data-saturation-mode={saturationMode}
      data-highlight-links={highlightLinks}
      data-highlight-headings={highlightHeadings}
      data-content-scaling={contentScaling}
      data-fontSize={fontSize}
      data-letterSpacing={letterSpacing}
      data-remove-images={removeImages}
      data-disable-animations={disableAnimations}
      data-large-cursor={largeCursor}
      data-dyslexia-font={dyslexiaFont}
      data-button-color={buttonColor}
      data-accent-color={accentColor}
      data-position={widgetPosition}
      // New data attributes
      data-blue-filter={blueFilter}
      data-mute-sounds={muteSounds}
      style={{ "--a11y-accent-color": accentColor, "--a11y-button-color": buttonColor } as React.CSSProperties}
    >
      {/* The actual widget HTML structure, which widget.js will manipulate */}
      <button id="accessibility-widget-toggle" className="a11y-widget-toggle" onClick={handlePreviewToggleClick}>
        <i className={`${SelectedIconClass} fa-2x`}></i>
        {activeFeaturesCount > 0 && (
          <span className="a11y-active-badge" style={{ backgroundColor: accentColor }}>
            {activeFeaturesCount}
          </span>
        )}
      </button>
      <div
        id="accessibility-widget-content"
        className={cn("a11y-widget-content", isOpen && "is-open")} // isOpen here is just for initial render, widget.js will control actual class
        style={{
          position: "absolute",
          bottom: "calc(56px + 15px)",
          left: widgetPosition === "bottom-right" ? "auto" : "0",
          right: widgetPosition === "bottom-right" ? "0" : "auto",
          // Removed hardcoded height, now controlled by CSS
        }}
      >
        <div className="a11y-widget-header">
          <h3 className="a11y-widget-title">Barrierefreiheits-Menü</h3>
          <div className="a11y-header-actions">
            <button className="a11y-reset-button" onClick={handlePreviewResetClick}>
              <i className={resetIconClass}></i>
            </button>
            <button className="a11y-close-button" onClick={handlePreviewCloseClick}>
              <i className={closeIconClass}></i>
            </button>
          </div>
        </div>
        {/* New scrollable container for sliders and tiles */}
        <div className="a11y-scrollable-content">
          {/* Sliders as individual rows */}
          <div className="a11y-sliders-container">
            <div className="a11y-slider-row" data-setting="contentScaling">
              <span className="a11y-slider-label">Inhaltsskalierung</span>
              <div className="a11y-slider-control">
                <button
                  className="a11y-slider-btn"
                  data-action="decrease"
                  data-setting="contentScaling"
                  data-min="80"
                  data-max="200"
                  data-step="10"
                >
                  -
                </button>
                <span className="a11y-slider-value" data-setting="contentScaling">
                  {contentScaling}%
                </span>
                <button
                  className="a11y-slider-btn"
                  data-action="increase"
                  data-setting="contentScaling"
                  data-min="80"
                  data-max="200"
                  data-step="10"
                >
                  +
                </button>
              </div>
            </div>

            <div className="a11y-slider-row" data-setting="fontSize">
              <span className="a11y-slider-label">Schriftgröße</span>
              <div className="a11y-slider-control">
                <button
                  className="a11y-slider-btn"
                  data-action="decrease"
                  data-setting="fontSize"
                  data-min="80"
                  data-max="200"
                  data-step="10"
                >
                  -
                </button>
                <span className="a11y-slider-value" data-setting="fontSize">
                  {fontSize}%
                </span>
                <button
                  className="a11y-slider-btn"
                  data-action="increase"
                  data-setting="fontSize"
                  data-min="80"
                  data-max="200"
                  data-step="10"
                >
                  +
                </button>
              </div>
            </div>

            <div className="a11y-slider-row" data-setting="letterSpacing">
              <span className="a11y-slider-label">Buchstabenabstand</span>
              <div className="a11y-slider-control">
                <button
                  className="a11y-slider-btn"
                  data-action="decrease"
                  data-setting="letterSpacing"
                  data-min="-50"
                  data-max="100"
                  data-step="10"
                >
                  -
                </button>
                <span className="a11y-slider-value" data-setting="letterSpacing">
                  {letterSpacing / 100}em
                </span>
                <button
                  className="a11y-slider-btn"
                  data-action="increase"
                  data-setting="letterSpacing"
                  data-min="-50"
                  data-max="100"
                  data-step="10"
                >
                  +
                </button>
              </div>
            </div>
          </div>

          {/* Toggle Tiles - Bilder ausblenden first */}
          <div className="a11y-options-grid">
            <div className={cn("a11y-option-tile", removeImages && "is-active")} data-setting="removeImages">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.imageOff}></i>
              </div>
              <span className="a11y-option-label">Bilder aus</span>
            </div>
            <div className={cn("a11y-option-tile", invertColors && "is-active")} data-setting="invertColors">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.circleHalfStroke}></i>
              </div>
              <span className="a11y-option-label">Farben umkehren</span>
            </div>
            <div className={cn("a11y-option-tile", grayscale && "is-active")} data-setting="grayscale">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.circleDot}></i>
              </div>
              <span className="a11y-option-label">Monochrom</span>
            </div>
            <div className={cn("a11y-option-tile", blueFilter && "is-active")} data-setting="blueFilter">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.blueFilter}></i>
              </div>
              <span className="a11y-option-label">Blaufilter</span>
            </div>
            <div className={cn("a11y-option-tile", contrastMode === "dark" && "is-active")} data-setting="darkContrast">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.moon}></i>
              </div>
              <span className="a11y-option-label">Dunkler Kontrast</span>
            </div>
            <div
              className={cn("a11y-option-tile", contrastMode === "light" && "is-active")}
              data-setting="lightContrast"
            >
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.sun}></i>
              </div>
              <span className="a11y-option-label">Heller Kontrast</span>
            </div>
            <div
              className={cn("a11y-option-tile", saturationMode === "low" && "is-active")}
              data-setting="lowSaturation"
            >
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.dropletSlash}></i>
              </div>
              <span className="a11y-option-label">Niedrige Sättigung</span>
            </div>
            <div
              className={cn("a11y-option-tile", saturationMode === "high" && "is-active")}
              data-setting="highSaturation"
            >
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.droplet}></i>
              </div>
              <span className="a11y-option-label">Hohe Sättigung</span>
            </div>
            <div className={cn("a11y-option-tile", highlightLinks && "is-active")} data-setting="highlightLinks">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.link}></i>
              </div>
              <span className="a11y-option-label">Links hervorheben</span>
            </div>
            <div className={cn("a11y-option-tile", highlightHeadings && "is-active")} data-setting="highlightHeadings">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.heading}></i>
              </div>
              <span className="a11y-option-label">Überschriften hervorheben</span>
            </div>

            {/* Existing features not in screenshot, but kept */}
            <div className={cn("a11y-option-tile", disableAnimations && "is-active")} data-setting="disableAnimations">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.zapOff}></i>
              </div>
              <span className="a11y-option-label">Bewegung reduzieren</span>
            </div>
            <div className={cn("a11y-option-tile", largeCursor && "is-active")} data-setting="largeCursor">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.mousepointer2}></i>
              </div>
              <span className="a11y-option-label">Großer Cursor</span>
            </div>
            <div className={cn("a11y-option-tile", dyslexiaFont && "is-active")} data-setting="dyslexiaFont">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.type}></i>
              </div>
              <span className="a11y-option-label">Dyslexie Schrift</span>
            </div>
            <div className={cn("a11y-option-tile", muteSounds && "is-active")} data-setting="muteSounds">
              <div className="a11y-option-icon">
                <i className={iconSvgPaths.muteSounds}></i>
              </div>
              <span className="a11y-option-label">Töne aus</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
