/* ============================================================
   composer.jsx — inline popover for comments + suggestions
   Replaces the legacy prompt() flow. Anchored to a viewport
   coordinate; closes on Esc / outside-click / submit.
   ============================================================ */

function CommentComposer({ anchor, mode, original, snippet, onSubmit, onCancel }) {
  // anchor: { x, y }  in canvas-wrapper coords
  // mode:   'comment' | 'suggestion' | 'reply'
  // original: existing text for suggestion (prefill)
  // snippet:  visible quote to show as context
  const [text, setText] = useState(mode === 'suggestion' ? (original || '') : '');
  const [comment, setComment] = useState('');
  const taRef = useRef(null);
  const rootRef = useRef(null);

  useEffect(() => {
    setTimeout(() => taRef.current?.focus(), 30);
  }, []);

  // close on outside click
  useEffect(() => {
    const onDown = (e) => {
      if (rootRef.current && !rootRef.current.contains(e.target)) {
        onCancel();
      }
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [onCancel]);

  const onKey = (e) => {
    if (e.key === 'Escape') { e.preventDefault(); onCancel(); }
    if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); submit(); }
  };

  const canSubmit = mode === 'suggestion'
    ? (text.trim() && text !== original)
    : (text.trim().length > 0);

  const submit = () => {
    if (!canSubmit) return;
    if (mode === 'suggestion') onSubmit({ proposed: text, comment: comment.trim() || null });
    else                       onSubmit({ text: text.trim() });
  };

  const headLabel = mode === 'comment' ? 'Opmerking' : mode === 'suggestion' ? 'Tekstvoorstel' : 'Antwoord';
  const placeholder = mode === 'comment'
    ? 'Schrijf een opmerking…  (⌘↵ versturen)'
    : mode === 'reply'
    ? 'Reageer in de thread…  (⌘↵ versturen)'
    : 'Voorgestelde nieuwe tekst…';

  return (
    <div
      ref={rootRef}
      className={'comment-composer mode-' + mode}
      style={{ left: anchor.x, top: anchor.y }}
      onClick={(e) => e.stopPropagation()}
      onMouseDown={(e) => e.stopPropagation()}
    >
      <div className="cc-head">
        <span className={'cc-kind cc-kind-' + mode}>{headLabel}</span>
        {snippet && (
          <span className="cc-snippet" title={snippet}>
            "{snippet.length > 60 ? snippet.slice(0, 60) + '…' : snippet}"
          </span>
        )}
        <button className="cc-close" onClick={onCancel} title="Sluiten (Esc)">×</button>
      </div>

      {mode === 'suggestion' && (
        <div className="cc-orig">
          <span className="cc-orig-label">Was</span>
          <span className="cc-orig-text">{original}</span>
        </div>
      )}

      <textarea
        ref={taRef}
        className={'cc-textarea' + (mode === 'suggestion' ? ' cc-suggestion-input' : '')}
        value={text}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={onKey}
        placeholder={placeholder}
        rows={mode === 'suggestion' ? 2 : 3}
      />

      {mode === 'suggestion' && (
        <textarea
          className="cc-textarea cc-suggestion-note"
          value={comment}
          onChange={(e) => setComment(e.target.value)}
          onKeyDown={onKey}
          placeholder="Toelichting (optioneel)…"
          rows={2}
        />
      )}

      <div className="cc-actions">
        <span className="cc-hint">⌘↵ versturen · Esc sluiten</span>
        <div style={{flex: 1}}/>
        <button className="cc-btn cc-btn-ghost" onClick={onCancel}>Annuleren</button>
        <button
          className={'cc-btn cc-btn-primary' + (mode === 'suggestion' ? ' cc-btn-suggest' : '')}
          disabled={!canSubmit}
          onClick={submit}
        >
          {mode === 'comment'    && 'Plaats opmerking'}
          {mode === 'suggestion' && 'Voorstel versturen'}
          {mode === 'reply'      && 'Reageer'}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { CommentComposer });
