
// CompNotes.jsx — Shared cozy comment-thread used in Comp > Build and Comp > Saved.
//
// Comments are crew members chiming in on the team comp recipe. Each note carries:
//   { id, authorId, authorName, authorColor, text, createdAt, editedAt? }
//
// The component is "controlled" — the parent owns the notes array and supplies
// callbacks for add/edit/delete. Author defaults to the current "me" (myUserId).

const CompNotesNS = (() => {
  const { useState, useRef, useEffect } = React;

  function relTime(iso) {
    if (!iso) return '';
    const now = Date.now();
    const t   = new Date(iso).getTime();
    const s   = Math.round((now - t) / 1000);
    if (s < 5) return 'just now';
    if (s < 60) return `${s}s ago`;
    const m = Math.round(s / 60);
    if (m < 60) return `${m}m ago`;
    const h = Math.round(m / 60);
    if (h < 24) return `${h}h ago`;
    const d = Math.round(h / 24);
    if (d < 7) return `${d}d ago`;
    return new Date(iso).toLocaleDateString();
  }

  function Avatar({ name, color }) {
    return (
      <window.HexFrame size={28} color={color || '#F7DFA0'} borderColor="var(--border-emphasis)" borderWidth={1.8}>
        <span style={{ fontFamily: 'Fredoka One', fontSize: 11, color: 'var(--text-on-light)' }}>
          {(name || '?')[0].toUpperCase()}
        </span>
      </window.HexFrame>
    );
  }

  function NoteRow({ note, mine, onEdit, onDelete }) {
    const [editing, setEditing] = useState(false);
    const [draft, setDraft]     = useState(note.text);
    const taRef = useRef(null);

    useEffect(() => {
      if (editing && taRef.current) {
        taRef.current.focus();
        taRef.current.selectionStart = taRef.current.value.length;
      }
    }, [editing]);

    const commit = () => {
      const v = draft.trim();
      if (v && v !== note.text) onEdit(note.id, v);
      setEditing(false);
    };

    return (
      <div style={{
        display: 'flex', gap: 10, alignItems: 'flex-start',
        background: mine ? 'var(--surface-modal)' : 'var(--surface-nested)',
        border: mine ? '1.5px solid var(--border-emphasis)' : '1.5px solid var(--border-default)',
        borderRadius: 14, padding: '10px 12px',
      }}>
        <Avatar name={note.authorName} color={note.authorColor} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 3, flexWrap: 'wrap' }}>
            <span style={{ fontFamily: 'Nunito', fontWeight: 800, fontSize: 13, color: 'var(--text-primary)' }}>
              {note.authorName}
            </span>
            <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)' }}>
              {relTime(note.createdAt)}
              {note.editedAt && note.editedAt !== note.createdAt && (
                <span style={{ marginLeft: 4, fontStyle: 'italic' }}>· edited</span>
              )}
            </span>
            {mine && !editing && (
              <span style={{ marginLeft: 'auto', display: 'inline-flex', gap: 4 }}>
                <button
                  onClick={() => { setDraft(note.text); setEditing(true); }}
                  style={{
                    border: 'none', background: 'transparent', cursor: 'pointer',
                    fontSize: 11, fontFamily: 'Nunito', fontWeight: 800,
                    color: 'var(--accent-orange)', padding: '2px 6px', borderRadius: 8,
                  }}
                  title="Edit"
                >✏️</button>
                <button
                  onClick={() => onDelete(note.id)}
                  style={{
                    border: 'none', background: 'transparent', cursor: 'pointer',
                    fontSize: 11, fontFamily: 'Nunito', fontWeight: 800,
                    color: 'var(--text-muted)', padding: '2px 6px', borderRadius: 8,
                  }}
                  title="Delete"
                >🗑️</button>
              </span>
            )}
          </div>

          {editing ? (
            <>
              <textarea
                ref={taRef}
                value={draft}
                onChange={e => setDraft(e.target.value)}
                onKeyDown={e => {
                  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) commit();
                  if (e.key === 'Escape') setEditing(false);
                }}
                style={{
                  width: '100%', minHeight: 60, resize: 'vertical',
                  border: '2px solid var(--border-default)', borderRadius: 12,
                  padding: '8px 10px', background: 'var(--surface-modal)', color: 'var(--text-primary)',
                  fontFamily: 'Nunito', fontWeight: 700, fontSize: 13,
                  lineHeight: 1.45, outline: 'none',
                }}
              />
              <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
                <window.CozyButton small color="sage" onClick={commit}>Save</window.CozyButton>
                <window.CozyButton small color="cream" onClick={() => setEditing(false)}>Cancel</window.CozyButton>
                <span style={{ fontSize: 10, color: 'var(--text-muted)', alignSelf: 'center', marginLeft: 'auto' }}>⌘+Enter to save</span>
              </div>
            </>
          ) : (
            <div style={{
              fontFamily: 'Nunito', fontWeight: 700, fontSize: 13.5,
              color: 'var(--text-primary)', lineHeight: 1.5, whiteSpace: 'pre-wrap',
              wordBreak: 'break-word',
            }}>
              {note.text}
            </div>
          )}
        </div>
      </div>
    );
  }

  function CompNotes({
    notes = [],
    onAdd, onEdit, onDelete,
    title = 'Crew notes',
    emoji = '💬',
    accent = 'var(--accent-orange)',
    placeholder = 'Share a thought with the crew…',
    compact = false,
  }) {
    const { players, myUserId } = window.useApp();
    const me = players.find(p => p.id === myUserId) || players[0];
    const [draft, setDraft] = useState('');
    const [posting, setPosting] = useState(false);

    const handleAdd = async () => {
      const v = draft.trim();
      if (!v || posting) return;
      setPosting(true);
      try {
        const now = new Date().toISOString();
        await onAdd({
          id: Date.now() + Math.floor(Math.random() * 1000),
          authorId: me.id,
          authorName: me.name,
          authorColor: me.identityColor,
          text: v,
          createdAt: now,
        });
        setDraft('');
      } catch (err) {
        console.error("Error adding note:", err);
      } finally {
        setPosting(false);
      }
    };

    const uniqueNotes = (notes || []).filter((n, idx, arr) =>
      n && idx === arr.findIndex(item => item && String(item.id || item.timestamp) === String(n.id || n.timestamp))
    );

    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: compact ? 6 : 8 }}>
        <div style={{
          display: 'flex', alignItems: 'baseline', gap: 8,
          marginBottom: compact ? 2 : 4,
        }}>
          <h2 className="fredoka" style={{
            color: accent, fontSize: compact ? 16 : 22, margin: 0,
            display: 'inline-flex', alignItems: 'center', gap: 8,
          }}>
            {title} <span style={{ fontSize: compact ? 14 : 18 }}>{emoji}</span>
          </h2>
          <span style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-muted)' }}>
            {uniqueNotes.length} {uniqueNotes.length === 1 ? 'note' : 'notes'}
          </span>
        </div>
        {!compact && (
          <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 12.5, margin: '0 0 4px' }}>
            Anything the team should remember about this comp? Synergies, threats, tilted teammates 💛
          </p>
        )}

        {/* Existing notes */}
        {uniqueNotes.length > 0 ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[...uniqueNotes].sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt)).map(n => (
              <NoteRow
                key={n.id}
                note={n}
                mine={n.authorId === me.id}
                onEdit={onEdit}
                onDelete={onDelete}
              />
            ))}
          </div>
        ) : (
          <div style={{
            color: 'var(--text-muted)', fontWeight: 700, fontSize: 12.5,
            background: 'var(--surface-nested)', border: '1.5px dashed var(--border-default)',
            borderRadius: 12, padding: '12px 14px', textAlign: 'center',
          }}>
            No notes yet — be the first to chime in! 🌱
          </div>
        )}

        {/* Compose row */}
        <div style={{
          display: 'flex', gap: 8, alignItems: 'flex-start',
          marginTop: compact ? 2 : 6,
          padding: '8px 10px',
          background: 'var(--surface-modal)',
          border: '1.5px solid var(--border-default)',
          borderRadius: 14,
        }}>
          <Avatar name={me.name} color={me.identityColor} />
          <textarea
            value={draft}
            onChange={e => setDraft(e.target.value)}
            onKeyDown={e => {
              if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); handleAdd(); }
            }}
            placeholder={`${me.name}: ${placeholder}`}
            style={{
              flex: 1, minHeight: compact ? 36 : 52, resize: 'vertical',
              border: 'none', outline: 'none', background: 'transparent',
              fontFamily: 'Nunito', fontWeight: 700, fontSize: 13,
              color: 'var(--text-primary)', lineHeight: 1.45,
            }}
          />
          <window.CozyButton small color="terracotta" onClick={handleAdd} disabled={posting || !draft.trim()}>
            {posting ? 'Posting…' : 'Post 🌸'}
          </window.CozyButton>
        </div>
      </div>
    );
  }

  return { CompNotes };
})();

Object.assign(window, { CompNotes: CompNotesNS.CompNotes });
