"use client";

import React, { useEffect, useMemo, useRef, useState } from "react";
import { Scale, ExternalLink } from "lucide-react";
import Link from "next/link";

interface MinimaCCNPreviewProps {
  isRegimeRG: boolean;
  datesRep?: string;
  datesServ?: string;
  joursTravail?: string;
}

export default function MinimaCCNPreview({ isRegimeRG }: MinimaCCNPreviewProps) {
  const iframeRef = useRef<HTMLIFrameElement | null>(null);
  const [height, setHeight] = useState(320);

  const src = useMemo(() => {
    // Point d'entrée: hub des minima avec mode embed
    return "/minima-ccn?embed=1";
  }, []);

  useEffect(() => {
    function onMessage(e: MessageEvent) {
      if (typeof e.data === 'object' && e.data && e.data.type === 'minima-ccn:height') {
        const h = Number(e.data.height);
        if (Number.isFinite(h) && h > 100 && h < 4000) {
          setHeight(Math.ceil(h));
        }
      }
    }
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, []);

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Scale className="w-4 h-4 text-amber-600" />
          <p className="font-semibold text-slate-900 text-sm">Minima des CCN</p>
        </div>
        <Link href="/minima-ccn" target="_blank" className="text-xs text-amber-700 hover:text-amber-900 inline-flex items-center gap-1">
          Ouvrir la page
          <ExternalLink className="w-3 h-3" />
        </Link>
      </div>

      <div className="rounded-lg border overflow-hidden bg-white">
        <iframe
          ref={iframeRef}
          src={src}
          title="Minima CCN"
          style={{ width: '100%', height: `${height}px` }}
          scrolling="no"
        />
      </div>
    </div>
  );
}
