// note_detail.jsx — メモの詳細モーダル
// v1.3: NoteCard / StickyNote / TimelineEntry から開かれる共通モーダル。
// 全文表示 + アクション（寝かせる / 起こす / 削除）。
// Escキー、背景タップ、閉じるボタンで閉じる。

function NoteDetailModal({ note, open, onClose, onUpdate, onDelete }) {
  const t = useT();
  const meta = note ? (TYPE_META(t)[note.type] || TYPE_META(t).memo) : null;

  // Esc で閉じる
  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, onClose]);

  // body スクロールロック
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  if (!open || !note) return null;

  const isResting = note.status === 'resting';

  const handleRest = () => {
    onUpdate({ ...note, status: 'resting', restedAt: Date.now() });
    onClose();
  };
  const handleWake = () => {
    onUpdate({ ...note, status: 'active', restedAt: null });
    onClose();
  };
  const handleDelete = () => {
    if (!confirm('このメモを削除する？')) return;
    onDelete(note.id);
    onClose();
  };

  // 投下時刻の詳細表示
  const d = new Date(note.ts);
  const days = ['日', '月', '火', '水', '木', '金', '土'];
  const fullDate = `${d.getFullYear()}年${d.getMonth()+1}月${d.getDate()}日 (${days[d.getDay()]}) ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;

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

  return (
    <>
      {/* バックドロップ */}
      <div
        onClick={onClose}
        style={{
          position: 'fixed',
          top: 0, left: 0, right: 0, bottom: 0,
          background: 'rgba(0, 0, 0, 0.5)',
          backdropFilter: 'blur(6px)',
          WebkitBackdropFilter: 'blur(6px)',
          zIndex: 60,
          animation: 'echoDetailFadeIn 0.18s ease-out',
        }}
      />
      <style>{`
        @keyframes echoDetailFadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes echoDetailSlideUp {
          from { transform: translate(-50%, 16px); opacity: 0; }
          to { transform: translate(-50%, 0); opacity: 1; }
        }
      `}</style>

      {/* モーダル本体 */}
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          position: 'fixed',
          zIndex: 61,
          left: '50%',
          top: isMobile ? 'auto' : '50%',
          bottom: isMobile ? 0 : 'auto',
          transform: isMobile ? 'translateX(-50%)' : 'translate(-50%, -50%)',
          width: isMobile ? '100vw' : 'calc(100vw - 40px)',
          maxWidth: 620,
          maxHeight: isMobile ? '88vh' : '80vh',
          background: t.bgCard,
          border: isMobile ? 'none' : `1px solid ${t.line}`,
          borderTopLeftRadius: 20,
          borderTopRightRadius: 20,
          borderBottomLeftRadius: isMobile ? 0 : 20,
          borderBottomRightRadius: isMobile ? 0 : 20,
          boxShadow: '0 24px 64px rgba(0,0,0,0.35)',
          display: 'flex',
          flexDirection: 'column',
          fontFamily: APP_FONT,
          animation: 'echoDetailSlideUp 0.22s ease-out',
          paddingBottom: isMobile ? 'env(safe-area-inset-bottom)' : 0,
        }}>
        {/* ハンドルバー (モバイル) */}
        {isMobile && (
          <div style={{
            display: 'flex', justifyContent: 'center',
            padding: '8px 0 4px',
          }}>
            <div style={{
              width: 36, height: 4, borderRadius: 999,
              background: t.line,
            }}/>
          </div>
        )}

        {/* ヘッダ */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: isMobile ? '8px 20px 14px' : '18px 22px 14px',
          borderBottom: `1px solid ${t.line}`,
        }}>
          {/* 色ドット */}
          <div style={{
            width: 10, height: 10, borderRadius: '50%',
            background: meta.color, flexShrink: 0,
          }}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontSize: 12, color: t.ink3, fontWeight: 600,
              letterSpacing: '-0.01em',
              fontVariantNumeric: 'tabular-nums',
            }}>{fullDate}</div>
            {(note.cal || note.contextEventTitle || isResting) && (
              <div style={{
                display: 'flex', gap: 8, alignItems: 'center',
                flexWrap: 'wrap', marginTop: 4,
              }}>
                {note.cal && (
                  <span style={{
                    fontSize: 10, color: t.primary, fontWeight: 600,
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                  }}>
                    {Icons.cal(10)}{note.cal}
                  </span>
                )}
                {note.contextEventTitle && (
                  <span style={{
                    fontSize: 10, color: t.ink4, fontStyle: 'italic',
                  }}>
                    《{note.contextEventTitle}》の最中
                  </span>
                )}
                {isResting && (
                  <span style={{
                    fontSize: 9, color: t.ink4, fontWeight: 800,
                    letterSpacing: '0.14em',
                    padding: '2px 6px', borderRadius: 3,
                    background: t.bgSoft,
                  }}>RESTING</span>
                )}
              </div>
            )}
          </div>
          <button
            onClick={onClose}
            aria-label="閉じる"
            style={{
              background: 'transparent', border: 'none',
              color: t.ink3, cursor: 'pointer',
              padding: 6, borderRadius: 8,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
              WebkitTapHighlightColor: 'transparent',
            }}>
            {Icons.close(18)}
          </button>
        </div>

        {/* 本文（スクロール領域） */}
        <div style={{
          flex: 1, minHeight: 0,
          overflowY: 'auto',
          padding: '20px 22px',
          WebkitOverflowScrolling: 'touch',
        }}>
          <div style={{
            fontSize: 16, lineHeight: 1.7, color: t.ink,
            textWrap: 'pretty', wordBreak: 'break-word',
            whiteSpace: 'pre-wrap',
            letterSpacing: '-0.005em',
          }}>{note.text}</div>

          {note.value && (
            <div style={{
              marginTop: 16,
              display: 'inline-block',
              padding: '6px 12px', borderRadius: 6,
              background: t.primarySoft, color: t.primary,
              fontSize: 14, fontWeight: 800,
              fontVariantNumeric: 'tabular-nums',
            }}>¥{note.value.toLocaleString()}</div>
          )}

          {note.echoedSimilarity != null && (
            <div style={{
              marginTop: 16,
              padding: '10px 12px',
              borderRadius: 8,
              background: t.primarySoft,
              fontSize: 12, color: t.primary, fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {Icons.sparkle(12)}
              過去と再会した · 類似度 {Math.round(note.echoedSimilarity * 100)}%
            </div>
          )}
        </div>

        {/* フッタ（アクション） */}
        <div style={{
          display: 'flex', gap: 8,
          padding: isMobile ? '12px 20px 16px' : '14px 22px 18px',
          borderTop: `1px solid ${t.line}`,
        }}>
          {isResting ? (
            <button
              onClick={handleWake}
              style={actionBtnStyle(t, 'primary')}>
              もう一度見る
            </button>
          ) : (
            <button
              onClick={handleRest}
              style={actionBtnStyle(t, 'ghost')}>
              今は閉じる
            </button>
          )}
          <div style={{ flex: 1 }}/>
          <button
            onClick={handleDelete}
            style={actionBtnStyle(t, 'danger')}>
            {Icons.trash(12)} 削除
          </button>
        </div>
      </div>
    </>
  );
}

function actionBtnStyle(t, variant) {
  const base = {
    padding: '10px 16px',
    borderRadius: 10,
    fontFamily: APP_FONT,
    fontSize: 13, fontWeight: 700,
    letterSpacing: '-0.01em',
    cursor: 'pointer',
    display: 'inline-flex', alignItems: 'center', gap: 6,
    WebkitTapHighlightColor: 'transparent',
    minHeight: 40,
  };
  if (variant === 'primary') {
    return { ...base, background: t.primary, color: '#fff', border: 'none' };
  }
  if (variant === 'danger') {
    return {
      ...base,
      background: 'transparent',
      color: t.danger,
      border: `1px solid ${t.danger}44`,
    };
  }
  return {
    ...base,
    background: 'transparent',
    color: t.ink2,
    border: `1px solid ${t.line}`,
  };
}

Object.assign(window, { NoteDetailModal });
