'use client';

import { useEffect, useRef, useState } from 'react';

interface LivePreviewProps {
  sessionId: string;
  token: string;
  apiUrl: string;
  onInteraction: (event: any) => void;
  isVisible: boolean;
  htmlVersion: number;
  currentUrl?: string;
}

export default function LivePreview({ sessionId, token, apiUrl, onInteraction, isVisible, htmlVersion, currentUrl }: LivePreviewProps) {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [scale, setScale] = useState(1);

  // Update iframe src when sessionId, apiUrl, or htmlVersion changes
  useEffect(() => {
    if (iframeRef.current && sessionId && token) {
      const htmlUrl = `${apiUrl}/api/proxy/session/${sessionId}/html?token=${encodeURIComponent(token)}&v=${htmlVersion}`;
      iframeRef.current.src = htmlUrl;
    }
  }, [sessionId, token, apiUrl, htmlVersion]);

  // Listen for postMessage events from the iframe
  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.data && event.data.type === 'proxyInteraction') {
        onInteraction(event.data.interactionData);
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [onInteraction]);

  if (!isVisible) return null;

  return (
    <div>
      <div className="flex justify-between items-center mb-3 gap-2">
        <h2 className="text-sm font-bold text-brand-navy shrink-0">Live Preview</h2>
        {currentUrl && (
          <input
            type="text"
            readOnly
            value={currentUrl}
            className="flex-1 min-w-0 px-3 py-1.5 border border-gray-200 rounded-lg bg-gray-50 text-xs font-mono text-gray-500 truncate"
          />
        )}
        <div className="flex gap-1.5 shrink-0">
          <button
            onClick={() => setScale(Math.max(0.5, scale - 0.1))}
            className="w-7 h-7 flex items-center justify-center bg-gray-50 hover:bg-gray-100 rounded-lg border border-gray-200 text-xs text-gray-600"
          >
            -
          </button>
          <span className="px-2 py-1 text-xs text-gray-500 tabular-nums">{Math.round(scale * 100)}%</span>
          <button
            onClick={() => setScale(Math.min(2, scale + 0.1))}
            className="w-7 h-7 flex items-center justify-center bg-gray-50 hover:bg-gray-100 rounded-lg border border-gray-200 text-xs text-gray-600"
          >
            +
          </button>
        </div>
      </div>

      <div className="border border-gray-200 rounded-xl overflow-hidden bg-white">
        <iframe
          ref={iframeRef}
          title="Live Preview"
          sandbox="allow-same-origin allow-scripts allow-forms allow-modals"
          style={{
            width: '100%',
            height: '600px',
            border: 'none',
            transform: `scale(${scale})`,
            transformOrigin: 'top left',
          }}
        />
      </div>
    </div>
  );
}
