import React, { useState, useEffect } from "react";
import { VCProduct, VCOverlayInstruction } from "../../types/VideoCommerceTypes";

type Props = {
  product: VCProduct;
  overlay: VCOverlayInstruction;
  onClick: (p: VCProduct) => void;
};

export default function ProductBadge({ product, overlay, onClick }: Props) {
  console.log('[COMMERCE] 🎨 Rendering ProductBadge:', product.id, product.title);
  const [isPaused, setIsPaused] = useState(false);
  const [controlsVisible, setControlsVisible] = useState(false);
  const showPrice = overlay.style?.badge?.showPrice !== false;
  const showThumb = overlay.style?.badge?.showThumb !== false;
  
  // Detect if video is paused and monitor controls visibility
  useEffect(() => {
    const checkPauseState = () => {
      const video = document.querySelector('.uvf-video') as HTMLVideoElement;
      if (video) {
        const newPausedState = video.paused;
        setIsPaused(newPausedState);
        console.log('[COMMERCE] Video paused state:', newPausedState, 'video element:', !!video);
      }
    };
    
    const checkControlsVisible = () => {
      const wrapper = document.querySelector('.uvf-player-wrapper') as HTMLElement | null;
      const visible = (wrapper?.classList.contains('controls-visible') ?? false) || (wrapper?.matches(':hover') ?? false);
      setControlsVisible(visible);
    };
    
    const video = document.querySelector('.uvf-video') as HTMLVideoElement;
    const wrapper = document.querySelector('.uvf-player-wrapper') as HTMLElement | null;
    
    console.log('[COMMERCE] Setup - video element found:', !!video, 'wrapper found:', !!wrapper);
    
    // Poll pause state every 100ms instead of relying on events
    const pausePollInterval = setInterval(checkPauseState, 100);
    
    // Also poll controls visibility every 100ms
    const controlsPollInterval = setInterval(checkControlsVisible, 100);
    
    // Monitor controls visibility with mutation observer
    let observer: MutationObserver | null = null;
    if (wrapper) {
      observer = new MutationObserver(checkControlsVisible);
      observer.observe(wrapper, { attributes: true, attributeFilter: ['class'] });
      checkControlsVisible();
    }
    
    // Also check on mount
    checkPauseState();
    
    return () => {
      clearInterval(pausePollInterval);
      clearInterval(controlsPollInterval);
      if (observer) {
        observer.disconnect();
      }
    };
  }, []);
  
  console.log('[COMMERCE] Rendering - isPaused:', isPaused, 'controlsVisible:', controlsVisible);

  // Default to dock-bottom if no placement specified
  const placementMode = overlay.placement?.mode ?? "dock";
  const placementEdge = overlay.placement?.mode === "dock" ? (overlay.placement?.edge ?? "bottom") : undefined;
  
  const base: React.CSSProperties = {
    position: "fixed",
    // Default to bottom positioning
    bottom: placementMode === "dock" && placementEdge === "bottom" 
      ? ((isPaused || controlsVisible) ? 155 : 16) 
      : placementMode !== "anchor" ? ((isPaused || controlsVisible) ? 155 : 16)
      : undefined,
    top: placementMode === "dock" && placementEdge === "top" ? 25 : undefined,
    left: placementMode === "dock" && placementEdge === "left" ? 25 : (placementMode === "anchor" ? undefined : 25),
    right: placementMode === "dock" && placementEdge === "right" ? 25 : undefined,
    background: "rgba(0,0,0,0.6)",
    backdropFilter: "blur(8px)",
    border: "1px solid rgba(255,255,255,0.2)",
    borderRadius: 12,
    padding: "8px 12px",
    display: "flex",
    alignItems: "center",
    gap: 8,
    cursor: "pointer",
    pointerEvents: "auto",
    zIndex: overlay.behavior?.zIndex ?? 300,
    transition: "bottom 0.3s ease",
  };

  // anchor placement in % of video frame
  if (placementMode === "anchor" && overlay.placement && 'x' in overlay.placement && 'y' in overlay.placement) {
    base.left = `calc(${overlay.placement.x}% - 60px)`;
    base.top = `calc(${overlay.placement.y}% - 20px)`;
  }

  return (
    <div style={base} onClick={() => onClick(product)} aria-label={`View ${product.title}`}>
      {showThumb && product.thumbnails.square && (
        <img src={product.thumbnails.square} alt="" width={32} height={32} style={{ borderRadius: 6, objectFit: "cover" }} />
      )}
      <div style={{ display: "grid", gap: 2 }}>
        <div style={{ color: "#fff", fontSize: 13, fontWeight: 600, lineHeight: 1.1 }}>{product.title}</div>
        {showPrice && (
          <div style={{ color: "#FFD166", fontSize: 12 }}>
            {product.pricing.priceText ?? `${product.pricing.currency} ${product.pricing.amount}`}
          </div>
        )}
      </div>
    </div>
  );
}
