// note_card.jsx — 1件のメモカード
// v1.3 変更点:
//  - 完了概念を UI から削除（チェックボックスなし、取消線なし、「種類を変える」メニューも削除）
//  - バッジの英字ラベル（MEMO/TASK/IDEA/OUTPUT/OUTCOME）を削除、色ドットだけ残す
//  - 長文は 60文字でプレビュー表示 → カードタップで全文モーダル（NoteDetailModal）
//  - done プロパティはデータとして残す（破壊的変更を避けるため）

const NOTE_PREVIEW_LIMIT = 60;

function NoteCard({ note, onUpdate, onDelete }) {
  const t = useT();
  const meta = TYPE_META(t)[note.type] || TYPE_META(t).memo;
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [detailOpen, setDetailOpen] = React.useState(false);
  const menuRef = React.useRef(null);

  React.useEffect(() => {
    if (!menuOpen) return;
    const h = (e) => { if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [menuOpen]);

  const openDetail = () => setDetailOpen(true);

  const rest = (e) => {
    e.stopPropagation();
    onUpdate({ ...note, status: 'resting', restedAt: Date.now() });
    setMenuOpen(false);
  };
  const wake = (e) => {
    e.stopPropagation();
    onUpdate({ ...note, status: 'active', restedAt: null });
    setMenuOpen(false);
  };

  const fullText = note.text || '';
  const needsFold = fullText.length > NOTE_PREVIEW_LIMIT;
  const displayText = needsFold
    ? fullText.slice(0, NOTE_PREVIEW_LIMIT).trimEnd() + '…'
    : fullText;

  return (
    <>
      <div
        onClick={openDetail}
        role="button"
        tabIndex={0}
        onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openDetail(); } }}
        style={{
          background: t.bgCard, border: `1px solid ${t.line}`,
          borderRadius: 12, padding: '14px 16px',
          display: 'flex', gap: 12, alignItems: 'flex-start',
          position: 'relative', fontFamily: APP_FONT,
          cursor: 'pointer',
          transition: 'border-color 0.12s, transform 0.08s',
          WebkitTapHighlightColor: 'transparent',
        }}
        onMouseEnter={(e) => { e.currentTarget.style.borderColor = t.ink4 + '55'; }}
        onMouseLeave={(e) => { e.currentTarget.style.borderColor = t.line; }}
      >
        {/* 色ドット（タイプの視覚的シグナルだけ。文字なし） */}
        <div style={{
          width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
          marginTop: 8, marginLeft: 2,
          background: meta.color,
        }}/>

        <div style={{ flex: 1, minWidth: 0 }}>
          {/* メタ列: 時刻・カレンダー・金額だけ。タイプラベルは出さない */}
          <div style={{
            display: 'flex', gap: 10, alignItems: 'center',
            marginBottom: 4, flexWrap: 'wrap',
          }}>
            <span style={{ fontSize: 11, color: t.ink4 }}>{relTime(note.ts)}</span>
            {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.value && (
              <span style={{
                fontSize: 10, color: t.primary, fontWeight: 700,
                padding: '2px 6px', borderRadius: 3, background: t.primarySoft,
              }}>¥{note.value.toLocaleString()}</span>
            )}
            {needsFold && (
              <span style={{
                fontSize: 10, color: t.ink4, fontWeight: 500,
                marginLeft: 'auto',
              }}>{fullText.length}字</span>
            )}
          </div>

          <div style={{
            fontSize: 14, color: t.ink2, lineHeight: 1.55,
            textWrap: 'pretty', wordBreak: 'break-word',
            whiteSpace: 'pre-wrap',
          }}>{displayText}</div>
        </div>

        <div
          style={{ position: 'relative' }}
          ref={menuRef}
          onClick={(e) => e.stopPropagation()}
        >
          <IconBtn onClick={() => setMenuOpen(!menuOpen)}>
            {Icons.more(15)}
          </IconBtn>
          {menuOpen && (
            <div style={{
              position: 'absolute', top: 36, right: 0, zIndex: 20,
              background: t.bgCard, border: `1px solid ${t.line}`,
              borderRadius: 10, padding: 6, minWidth: 160,
              boxShadow: t.shadowLg,
            }}>
              {note.status === 'resting' ? (
                <button onClick={wake} style={menuItemStyle(t)}>
                  もう一度見る
                </button>
              ) : (
                <button onClick={rest} style={menuItemStyle(t)}>
                  今は閉じる
                </button>
              )}
              <div style={{ height: 1, background: t.line, margin: '4px 0' }}/>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setMenuOpen(false);
                  setDetailOpen(true);
                }}
                style={menuItemStyle(t)}>
                詳細を開く
              </button>
              <div style={{ height: 1, background: t.line, margin: '4px 0' }}/>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onDelete(note.id);
                  setMenuOpen(false);
                }}
                style={{ ...menuItemStyle(t), color: t.danger }}>
                {Icons.trash(12)} 削除
              </button>
            </div>
          )}
        </div>
      </div>

      <NoteDetailModal
        note={note}
        open={detailOpen}
        onClose={() => setDetailOpen(false)}
        onUpdate={onUpdate}
        onDelete={onDelete}
      />
    </>
  );
}

function menuItemStyle(t) {
  return {
    display: 'flex', alignItems: 'center', gap: 8,
    width: '100%', textAlign: 'left',
    padding: '8px 10px', border: 'none', background: 'transparent',
    fontSize: 13, color: t.ink2, fontWeight: 600,
    cursor: 'pointer', borderRadius: 4,
    fontFamily: APP_FONT,
    WebkitTapHighlightColor: 'transparent',
  };
}

Object.assign(window, { NoteCard, NOTE_PREVIEW_LIMIT });
