'use client';

import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { BOX_CLASS } from './menuStyles.js';

// Popover ouvert au simple clic sur un lien existant. Rendu en `position:
// absolute` à l'intérieur du container relatif du BlockEditor : il scrolle
// avec le texte. `rect` est en coords locales au container (top/left/bottom).
// Flip-up vs flip-down se base sur la position viewport du container pour
// rester proche du lien visible.

const GAP = 8;
const VIEWPORT_MARGIN = 8;

export default function LinkPopover({ rect, mark, onSetLink, onRemoveLink, onClose }) {
  const ref = useRef(null);
  const [pos, setPos] = useState({ top: 0, left: 0 });
  const [url, setUrl] = useState(mark?.href ?? '');
  const [newTab, setNewTab] = useState(mark?.newTab ?? false);

  useLayoutEffect(() => {
    if (!rect || typeof window === 'undefined') return;
    const el = ref.current;
    if (!el) return;
    const w = el.offsetWidth || 280;
    const h = el.offsetHeight || 80;
    const container = el.offsetParent;
    const containerW = container?.clientWidth ?? Infinity;
    const containerVPRect = container?.getBoundingClientRect?.();
    const linkVPBottom = (containerVPRect?.top ?? 0) + rect.bottom;
    const vh = window.innerHeight;
    const spaceBelow = vh - linkVPBottom - VIEWPORT_MARGIN;
    const flipUp = spaceBelow < h + GAP;
    let top = flipUp ? rect.top - h - GAP : rect.bottom + GAP;
    let left = rect.left;
    if (left + w + VIEWPORT_MARGIN > containerW) left = containerW - w - VIEWPORT_MARGIN;
    if (left < VIEWPORT_MARGIN) left = VIEWPORT_MARGIN;
    if (top < 0) top = 0;
    setPos({ top, left });
  }, [rect]);

  useEffect(() => {
    function onKey(e) {
      if (e.key === 'Escape') { e.preventDefault(); onClose?.(); }
    }
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  function handleSubmit() {
    if (!url) return;
    onSetLink?.(url, newTab);
    onClose?.();
  }

  return (
    <div
      ref={ref}
      data-link-popover
      style={{ top: pos.top, left: pos.left }}
      className={`absolute z-50 flex flex-col gap-1.5 p-2 ${BOX_CLASS}`}
    >
      <div className="flex items-center gap-1">
        <input
          autoFocus
          type="url"
          placeholder="https://..."
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleSubmit(); } }}
          className="w-56 px-2 py-1 text-sm rounded border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 text-neutral-900 dark:text-white outline-none focus:border-blue-500"
        />
        <button
          type="button"
          onClick={handleSubmit}
          className="px-2 py-1 text-xs rounded bg-blue-600 hover:bg-blue-700 text-white"
        >
          OK
        </button>
        <button
          type="button"
          onClick={() => { onRemoveLink?.(); onClose?.(); }}
          title="Retirer le lien"
          className="px-2 py-1 text-xs rounded text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30"
        >
          ✕
        </button>
      </div>
      <label className="flex items-center gap-2 text-xs text-neutral-700 dark:text-neutral-300 select-none cursor-pointer">
        <input
          type="checkbox"
          checked={newTab}
          onChange={(e) => setNewTab(e.target.checked)}
          className="cursor-pointer"
        />
        Ouvrir dans un nouvel onglet
      </label>
    </div>
  );
}
