// quick_composer.jsx — フローティング＋ボタン + ミニComposer オーバーレイ

function QuickFAB({ onOpen, visible = true }) {
  const t = useT();
  const [settings] = useEchoSettings();
  const fabPos = settings.fabPosition === 'left' ? 'left' : 'right';

  if (!visible) return null;

  const positionStyle = fabPos === 'left'
    ? { left: 20, right: 'auto' }
    : { right: 20, left: 'auto' };

  return (
    <button
      onClick={onOpen}
      aria-label="投下"
      style={{
        position: 'fixed',
        ...positionStyle,
        bottom: 'calc(140px + env(safe-area-inset-bottom))',
        zIndex: 25,
        width: 56,
        height: 56,
        borderRadius: '50%',
        border: 'none',
        background: t.primary,
        color: '#fff',
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        cursor: 'pointer',
        boxShadow: `0 12px 28px ${t.primary}66, 0 4px 10px rgba(0,0,0,0.15)`,
        WebkitTapHighlightColor: 'transparent',
        transition: 'transform 0.1s ease-out',
      }}
      onMouseDown={e => e.currentTarget.style.transform = 'scale(0.92)'}
      onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
      onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
      onTouchStart={e => e.currentTarget.style.transform = 'scale(0.92)'}
      onTouchEnd={e => e.currentTarget.style.transform = 'scale(1)'}
    >
      {Icons.plus(24)}
    </button>
  );
}

function QuickComposerOverlay({ open, onClose, onPosted, pastNotes }) {
  const t = useT();
  const [draft, setDraft] = React.useState('');
  const [pending, setPending] = React.useState(false);
  const [flash, setFlash] = React.useState(null);
  const [echo, setEcho] = React.useState(null);
  const textareaRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setDraft('');
      setFlash(null);
      setEcho(null);
      setPending(false);
      setTimeout(() => {
        if (textareaRef.current) textareaRef.current.focus();
      }, 50);
    }
  }, [open]);

  React.useEffect(() => {
    if (!open) return;

    const onKeyDown = (e) => {
      if (e.key === 'Escape' && !pending) {
        closeAll();
      }
    };

    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [open, pending]);

  const closeAll = () => {
    setDraft('');
    setFlash(null);
    setEcho(null);
    setPending(false);
    onClose();
  };

  const submit = async () => {
    const text = draft.trim();
    if (!text || pending) return;

    setPending(true);
    setFlash('Echoが整理中…');
    setEcho(null);

    let echoFound = false;

    try {
      await postNote({
        text,
        pastNotes,

        onOptimistic: (n) => {
          if (onPosted) onPosted(n);
          setDraft('');
        },

        onFinal: (n) => {
          if (onPosted) onPosted(n);

          const typeLabel =
            n.type === 'task' ? '一歩' :
            n.type === 'idea' ? '着想' :
            '断片';

          setFlash(`投下完了。${typeLabel}として置いた。`);
          setPending(false);

          setTimeout(() => {
            if (!echoFound) {
              closeAll();
            }
          }, 900);
        },

        onEcho: (echoResult) => {
          echoFound = true;
          setEcho(echoResult);
          setPending(false);
          setFlash('過去の自分が近いことを書いていた。');
        },
      });
    } catch (e) {
      console.error('[echo] quick post failed:', e);
      setFlash('投下できなかった。もう一度。');
      setPending(false);
    }
  };

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

  if (!open) return null;

  const isMobile = typeof window !== 'undefined' &&
    window.matchMedia('(max-width: 640px)').matches;

  return (
    <>
      <div
        onClick={() => {
          if (!pending) closeAll();
        }}
        style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'rgba(0, 0, 0, 0.4)',
          backdropFilter: 'blur(4px)',
          WebkitBackdropFilter: 'blur(4px)',
          zIndex: 50,
        }}
      />

      <div
        style={{
          position: 'fixed',
          zIndex: 51,
          left: '50%',
          bottom: isMobile ? 'calc(12px + env(safe-area-inset-bottom))' : '20vh',
          transform: 'translateX(-50%)',
          width: 'calc(100vw - 24px)',
          maxWidth: 560,
        }}
      >
        <div
          style={{
            background: t.bgCard,
            border: `1.5px solid ${t.primary}`,
            borderRadius: 16,
            padding: 16,
            boxShadow: `0 16px 48px rgba(0,0,0,0.3), 0 4px 16px ${t.primary}33`,
            fontFamily: APP_FONT,
          }}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 8,
              marginBottom: 10,
            }}
          >
            <span
              style={{
                width: 6,
                height: 6,
                borderRadius: '50%',
                background: t.primary,
                boxShadow: `0 0 8px ${t.primary}`,
              }}
            />

            <span
              style={{
                fontSize: 10,
                fontWeight: 800,
                letterSpacing: '0.12em',
                color: t.primary,
              }}
            >
              NOW · クイック投下
            </span>

            {flash && (
              <span
                style={{
                  marginLeft: 'auto',
                  fontSize: 11,
                  color: t.ink4,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  maxWidth: isMobile ? 160 : 260,
                }}
              >
                {flash}
              </span>
            )}

            {!flash && (
              <button
                onClick={closeAll}
                style={{
                  marginLeft: 'auto',
                  background: 'transparent',
                  border: 'none',
                  color: t.ink4,
                  cursor: 'pointer',
                  padding: 2,
                  display: 'inline-flex',
                }}
                aria-label="閉じる"
              >
                {Icons.close(16)}
              </button>
            )}
          </div>

          <textarea
            ref={textareaRef}
            value={draft}
            onChange={e => setDraft(e.target.value)}
            onKeyDown={onTextareaKeyDown}
            placeholder="今、頭にあることをそのまま投げる。"
            rows={3}
            autoCapitalize="sentences"
            autoCorrect="on"
            spellCheck="true"
            disabled={pending}
            style={{
              width: '100%',
              border: 'none',
              outline: 'none',
              resize: 'none',
              fontFamily: APP_FONT,
              fontSize: 16,
              lineHeight: 1.6,
              color: t.ink,
              background: 'transparent',
              padding: 0,
              minHeight: 60,
              WebkitAppearance: 'none',
            }}
          />

          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              paddingTop: 10,
              borderTop: `1px solid ${t.line}`,
              gap: 10,
            }}
          >
            <div
              style={{
                fontSize: 11,
                color: t.ink4,
                display: 'flex',
                gap: 10,
                alignItems: 'center',
              }}
            >
              {!isMobile && <span>⌘ + Enter で投下</span>}
              {isMobile && <span>外側タップで閉じる</span>}
            </div>

            <button
              onClick={submit}
              disabled={!draft.trim() || pending}
              style={{
                padding: '9px 18px',
                borderRadius: 10,
                border: 'none',
                background: draft.trim() && !pending ? t.primary : t.line,
                color: draft.trim() && !pending ? '#fff' : t.ink4,
                fontFamily: APP_FONT,
                fontSize: 13,
                fontWeight: 700,
                cursor: draft.trim() && !pending ? 'pointer' : 'not-allowed',
                letterSpacing: '-0.01em',
                display: 'inline-flex',
                alignItems: 'center',
                gap: 6,
              }}
            >
              {Icons.plus(13)} {pending ? '投下中' : '投下'}
            </button>
          </div>
        </div>

        {echo && (
          <div style={{ marginTop: 12 }}>
            <EchoBanner
              echo={echo}
              onClose={closeAll}
            />
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, {
  QuickFAB,
  QuickComposerOverlay,
});
