import React, { useCallback, useEffect, useRef, useState } from 'react';
import { captureApi } from './api.js';

interface PastedImage { url: string; buffer: ArrayBuffer; }

export function App(): React.ReactElement {
  const [text, setText] = useState('');
  const [images, setImages] = useState<PastedImage[]>([]);
  const [err, setErr] = useState<string | null>(null);
  const ref = useRef<HTMLTextAreaElement>(null);

  useEffect(() => { ref.current?.focus(); }, []);

  const submit = useCallback(async () => {
    setErr(null);
    if (text.trim().length === 0 && images.length === 0) return;
    try {
      await captureApi.submit({ text, images: images.map((i) => i.buffer) });
      setText(''); setImages([]); captureApi.hide();
    } catch (e) { setErr('저장에 실패했습니다. 다시 시도해주세요.'); }
  }, [text, images]);

  const cancel = useCallback(() => {
    if (text.trim().length > 5) {
      const ok = window.confirm('이 한 줄을 흘려보낼까요?');
      if (!ok) return;
    }
    setText(''); setImages([]); captureApi.hide();
  }, [text]);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') { e.preventDefault(); cancel(); }
      else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); void submit(); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [cancel, submit]);

  const onPaste = useCallback(async (e: React.ClipboardEvent<HTMLTextAreaElement>) => {
    const items = Array.from(e.clipboardData.items);
    const imgs = items.filter((i) => i.type.startsWith('image/'));
    if (imgs.length === 0) return;
    e.preventDefault();
    for (const it of imgs) {
      const blob = it.getAsFile();
      if (!blob) continue;
      const buffer = await blob.arrayBuffer();
      const url = URL.createObjectURL(blob);
      setImages((prev) => [...prev, { url, buffer }]);
    }
  }, []);

  return (
    <div className="card">
      <textarea
        ref={ref}
        value={text}
        onChange={(e) => setText(e.target.value)}
        onPaste={onPaste}
        placeholder="지금 머릿속에 있는 것 한 줄. 정리는 나중입니다."
      />
      {images.length > 0 && (
        <div className="thumbs">
          {images.map((i, idx) => (<img key={idx} src={i.url} alt="" />))}
        </div>
      )}
      <div className="hint">Ctrl+Enter 저장 · Esc 취소 · 이미지 붙여넣기</div>
      {err && <div className="err">{err}</div>}
    </div>
  );
}
