// Memos.jsx — 건물 메모 화면 (수신기 위치, 전달사항 등)

function MemosScreen({ theme }) {
  const THEME = theme || window.THEME || {};
  const [memos, setMemos] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [text, setText] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  const getToken = () => localStorage.getItem('soritalk:token') || localStorage.getItem('token');

  const fetchMemos = React.useCallback(() => {
    fetch('/api/memos', {
      headers: { 'Authorization': 'Bearer ' + getToken() }
    })
    .then(r => r.json())
    .then(data => { if (Array.isArray(data)) setMemos(data); })
    .catch(() => {})
    .finally(() => setLoading(false));
  }, []);

  React.useEffect(() => { fetchMemos(); }, [fetchMemos]);

  const handleAdd = () => {
    if (!text.trim() || saving) return;
    setSaving(true);
    fetch('/api/memos', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + getToken() },
      body: JSON.stringify({ content: text.trim() })
    })
    .then(r => r.json())
    .then(data => {
      if (data.ok && data.memo) {
        setMemos(prev => [data.memo, ...prev]);
        setText('');
      }
    })
    .catch(() => {})
    .finally(() => setSaving(false));
  };

  const handleDelete = (id) => {
    if (!confirm('이 메모를 삭제하시겠습니까?')) return;
    fetch('/api/memos/' + id, {
      method: 'DELETE',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    })
    .then(r => r.json())
    .then(data => {
      if (data.ok) setMemos(prev => prev.filter(m => m.id !== id));
    })
    .catch(() => {});
  };

  const formatDate = (dt) => {
    if (!dt) return '';
    const d = new Date(dt);
    if (isNaN(d)) return dt;
    return d.getFullYear() + '.' +
      String(d.getMonth() + 1).padStart(2, '0') + '.' +
      String(d.getDate()).padStart(2, '0') + ' ' +
      String(d.getHours()).padStart(2, '0') + ':' +
      String(d.getMinutes()).padStart(2, '0');
  };

  return (
    <div style={{ padding: '20px 16px 100px' }}>
      <div style={{ fontSize: 18, fontWeight: 800, marginBottom: 16, color: THEME.textPrimary || '#1a1a1a' }}>
        건물 메모
      </div>

      {/* 메모 입력 */}
      <div style={{
        background: '#fff', borderRadius: 14, padding: 16,
        boxShadow: '0 2px 8px rgba(0,0,0,0.06)', marginBottom: 20,
        border: '1px solid #e5e7eb'
      }}>
        <textarea
          value={text}
          onChange={e => setText(e.target.value)}
          placeholder="수신기 위치, 전달사항 등을 기록하세요..."
          rows={3}
          style={{
            width: '100%', border: '1px solid #e5e7eb', borderRadius: 10,
            padding: '12px 14px', fontSize: 14, fontFamily: 'inherit',
            resize: 'vertical', outline: 'none', boxSizing: 'border-box',
            background: '#fafafa'
          }}
          onFocus={e => e.target.style.borderColor = THEME.brand || '#2563eb'}
          onBlur={e => e.target.style.borderColor = '#e5e7eb'}
        />
        <button
          onClick={handleAdd}
          disabled={!text.trim() || saving}
          style={{
            marginTop: 10, width: '100%', padding: '12px 0',
            background: text.trim() ? (THEME.brand || '#2563eb') : '#d1d5db',
            color: '#fff', border: 'none', borderRadius: 10,
            fontSize: 14, fontWeight: 700, cursor: text.trim() ? 'pointer' : 'not-allowed',
            fontFamily: 'inherit', transition: 'background 200ms'
          }}
        >
          {saving ? '저장 중...' : '메모 추가'}
        </button>
      </div>

      {/* 메모 목록 */}
      {loading ? (
        <div style={{ textAlign: 'center', color: '#999', padding: 40 }}>불러오는 중...</div>
      ) : memos.length === 0 ? (
        <div style={{ textAlign: 'center', color: '#999', padding: 40, fontSize: 14 }}>
          등록된 메모가 없습니다
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {memos.map(m => (
            <div key={m.id} style={{
              background: '#fff', borderRadius: 12, padding: '14px 16px',
              boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
              border: '1px solid #f0f0f0'
            }}>
              <div style={{
                fontSize: 14, color: '#333', lineHeight: 1.6,
                whiteSpace: 'pre-wrap', wordBreak: 'break-word'
              }}>
                {m.content}
              </div>
              <div style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                marginTop: 10, paddingTop: 8, borderTop: '1px solid #f5f5f5'
              }}>
                <span style={{ fontSize: 11, color: '#aaa' }}>
                  {formatDate(m.created_at)}
                </span>
                <button
                  onClick={() => handleDelete(m.id)}
                  style={{
                    background: 'none', border: 'none', fontSize: 12,
                    color: '#ef4444', cursor: 'pointer', padding: '4px 8px',
                    borderRadius: 6, fontFamily: 'inherit'
                  }}
                >
                  삭제
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

window.MemosScreen = MemosScreen;
