// Csoport chat — projekt-szintű üzenetváltás, file attach, "Kérdés" funkció (email triggerrel)

const Chat = ({ user, onClose, onToast }) => {
  const [, force] = React.useReducer(x => x + 1, 0);
  const [text, setText] = React.useState('');
  const [attachments, setAttachments] = React.useState([]);
  const [askUser, setAskUser] = React.useState(null);
  const [showAskPicker, setShowAskPicker] = React.useState(false);
  const fileRef = React.useRef(null);
  const scrollRef = React.useRef(null);
  const [reactionPickerFor, setReactionPickerFor] = React.useState(null);

  const REACTION_SET = [
    { emoji: '👍', label: 'Like' },
    { emoji: '👎', label: 'Dislike' },
    { emoji: '😄', label: 'Happy' },
    { emoji: '❤️', label: 'Love' },
    { emoji: '😢', label: 'Cry' },
    { emoji: '🫡', label: 'Salute' },
    { emoji: '🙏', label: 'Thank' },
    { emoji: '🚀', label: 'Rocket' },
  ];

  const toggleReaction = async (msg, emoji) => {
    // Optimistic local toggle so the UI feels instant.
    if (!msg.reactions) msg.reactions = {};
    const list = msg.reactions[emoji] || [];
    const idx = list.indexOf(user.id);
    if (idx >= 0) {
      list.splice(idx, 1);
      if (list.length === 0) delete msg.reactions[emoji];
      else msg.reactions[emoji] = list;
    } else {
      msg.reactions[emoji] = [...list, user.id];
    }
    setReactionPickerFor(null);
    force();
    try {
      await window.api.messages.reaction({ message_id: msg.id, emoji });
      await window.refreshData();
    } catch (err) {
      onToast(window.apiErrorMessage(err));
    }
  };

  // Auto-scroll a végére
  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [window.MESSAGES.length]);

  // Olvasott jelölés: amikor megnyílik, kérjük a szerveren is, hogy
  // jegyezze meg a jelenlegi időpontot (törli az unread badge-et).
  React.useEffect(() => {
    window.CHAT_LAST_READ = new Date().toISOString();
    (async () => {
      try { await window.api.messages.read(); } catch (e) { /* offline ok */ }
    })();
    return () => { window.CHAT_LAST_READ = new Date().toISOString(); };
  }, []);

  const projectMembers = window.USERS;

  const sendMessage = async () => {
    if (!text.trim() && attachments.length === 0) return;
    const body = text.trim();
    const askedId = askUser ? askUser.id : null;
    const askedEmail = askUser?.email;
    const files = attachments.map(a => a._file).filter(Boolean);

    // Optimistic local push so the bubble shows up immediately.
    const optimistic = {
      id: (window.MESSAGES.length ? Math.max(...window.MESSAGES.map(m => m.id)) : 0) + 1000000,
      authorId: user.id,
      body,
      createdAt: new Date().toISOString(),
      askedUserId: askedId,
      attachments: attachments.map(a => ({ name: a.name, type: a.type, size: a.size, url: a.url })),
      reactions: {},
      _pending: true,
    };
    window.MESSAGES.push(optimistic);
    setText('');
    setAttachments([]);
    setAskUser(null);
    force();

    try {
      const fd = new FormData();
      fd.append('body', body);
      if (askedId) fd.append('asked_user_id', String(askedId));
      files.forEach(f => fd.append('attachments[]', f));
      await window.api.messages.create(fd);
      // Refresh from server so the optimistic placeholder is replaced with the
      // canonical record (with proper id, server timestamps, attachment URLs).
      await window.refreshData();
      if (askedEmail) onToast(`✉ Email küldve: ${askedEmail}`);
    } catch (err) {
      // Roll back the optimistic message.
      const i = window.MESSAGES.findIndex(m => m.id === optimistic.id);
      if (i >= 0) window.MESSAGES.splice(i, 1);
      force();
      onToast('Hiba: ' + window.apiErrorMessage(err));
    }
  };

  const onFilePick = (e) => {
    const files = Array.from(e.target.files || []);
    const next = files.map(f => ({
      _file: f,
      name: f.name,
      type: f.type.startsWith('image/') ? 'image' : 'file',
      size: (f.size / 1024 / 1024).toFixed(1) + ' MB',
      url: f.type.startsWith('image/') ? URL.createObjectURL(f) : null,
    }));
    setAttachments([...attachments, ...next]);
    e.target.value = '';
  };

  const removeAttachment = (i) => {
    setAttachments(attachments.filter((_, idx) => idx !== i));
  };

  // Csoportosítás nap szerint
  const grouped = [];
  let lastDay = null;
  window.MESSAGES.forEach(m => {
    const d = m.createdAt.slice(0, 10);
    if (d !== lastDay) {
      grouped.push({ kind: 'day', day: d });
      lastDay = d;
    }
    grouped.push({ kind: 'msg', msg: m });
  });

  return (
    <div className="chat-overlay">
      <div className="chat-backdrop" onClick={onClose}></div>
      <div className="chat-window">
        {/* Desktop sidebar — projekt tagok */}
        <aside className="chat-sidebar">
          <div className="chat-sidebar-head">
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Projekt</div>
            <div style={{ fontSize: 16, fontWeight: 700, marginTop: 2 }}>H1 csapat</div>
            <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{projectMembers.length} tag · csoport chat</div>
          </div>
          {['admin', 'approver', 'contractor'].map(role => {
            const list = projectMembers.filter(u => u.role === role);
            if (!list.length) return null;
            const lbl = role === 'admin' ? 'Admin' : role === 'approver' ? 'Jóváhagyók' : 'Vállalkozók';
            return (
              <div key={role} className="chat-sidebar-section">
                <div className="chat-sidebar-section-title">{lbl} <span>{list.length}</span></div>
                {list.map(u => (
                  <button key={u.id} className="chat-member-row" onClick={() => { setAskUser(u); }}
                    title={`Kérdés: ${u.name}`}>
                    <div className="chat-member-avatar">
                      <Avatar user={u} size="sm"/>
                      {u.id === user.id && <span className="chat-online-dot"></span>}
                    </div>
                    <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
                      <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {u.name}{u.id === user.id && <span className="muted" style={{ fontWeight: 400 }}> (te)</span>}
                      </div>
                      <div className="muted" style={{ fontSize: 11, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {u.skill || (role === 'admin' ? 'Projektvezető' : 'Jóváhagyó')}
                      </div>
                    </div>
                    {u.id !== user.id && <Icon name="help" size={14} stroke={2.2}/>}
                  </button>
                ))}
              </div>
            );
          })}
        </aside>

        <div className="chat-main">
        {/* Header */}
        <div className="chat-header">
          <button className="bare chat-back-btn" onClick={onClose} style={{ padding: 6 }} aria-label="Bezárás">
            <Icon name="arrow-l" size={22}/>
          </button>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 600 }}>H1 csapat</div>
            <div className="muted" style={{ fontSize: 11 }}>{projectMembers.length} tag</div>
          </div>
          <div className="chat-avatars">
            {projectMembers.slice(0, 4).map((u, i) => (
              <div key={u.id} style={{ marginLeft: i === 0 ? 0 : -8, zIndex: 4 - i }}>
                <Avatar user={u} size="sm"/>
              </div>
            ))}
            {projectMembers.length > 4 && (
              <div className="chat-avatar-more">+{projectMembers.length - 4}</div>
            )}
          </div>
          <button className="bare chat-close-btn" onClick={onClose} aria-label="Bezárás">
            <Icon name="x" size={20}/>
          </button>
        </div>

      {/* Üzenetek */}
      <div className="chat-stream" ref={scrollRef}>
        {grouped.map((g, i) => {
          if (g.kind === 'day') {
            return (
              <div key={i} className="chat-day">
                <span>{window.relativeDay(g.day)}</span>
              </div>
            );
          }
          const m = g.msg;
          const author = window.getUser(m.authorId);
          const mine = m.authorId === user.id;
          const askedUser = m.askedUserId ? window.getUser(m.askedUserId) : null;
          const time = m.createdAt.slice(11, 16);
          return (
            <div key={i} className={'chat-row ' + (mine ? 'mine' : 'other')}>
              {!mine && <Avatar user={author} size="sm"/>}
              <div style={{ minWidth: 0, maxWidth: '78%' }}>
                {!mine && (
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 3, marginLeft: 4 }}>
                    {author?.name?.split(' ')[0]} <span style={{ opacity: 0.6 }}>· {time}</span>
                  </div>
                )}
                {askedUser && (
                  <div className="chat-ask-tag">
                    <Icon name="help" size={11} stroke={2.4}/>
                    <span>Kérdés <b>{askedUser.name.split(' ')[0]}</b> felé</span>
                    <span className="muted" style={{ fontSize: 10 }}>· email küldve</span>
                  </div>
                )}
                <div className={'chat-bubble ' + (mine ? 'mine' : 'other') + (askedUser ? ' has-ask' : '')}>
                  {m.body && <div style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{m.body}</div>}
                  {m.attachments && m.attachments.length > 0 && (
                    <div className="stack-2" style={{ marginTop: m.body ? 8 : 0 }}>
                      {m.attachments.map((a, j) => (
                        <div key={j} className="chat-attach">
                          {a.type === 'image' && a.url ? (
                            <img src={a.url} alt={a.name} style={{ maxWidth: '100%', borderRadius: 8, display: 'block' }}/>
                          ) : a.type === 'image' ? (
                            <div className="chat-attach-image-stub">
                              <Icon name="image" size={28}/>
                              <div style={{ fontSize: 11, marginTop: 4 }}>{a.name}</div>
                            </div>
                          ) : (
                            <div className="chat-attach-file">
                              <Icon name="doc" size={20}/>
                              <div style={{ flex: 1, minWidth: 0 }}>
                                <div style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.name}</div>
                                <div className="muted" style={{ fontSize: 10 }}>{a.size}</div>
                              </div>
                              <Icon name="download" size={16}/>
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  )}
                  {mine && (
                    <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.7)', marginTop: 4, textAlign: 'right' }}>
                      {time}
                    </div>
                  )}
                </div>
                {/* Reactions */}
                <div className={'chat-reactions ' + (mine ? 'mine' : 'other')}>
                  {m.reactions && Object.entries(m.reactions).map(([emoji, userIds]) => {
                    const reactedByMe = userIds.includes(user.id);
                    const names = userIds.map(uid => window.getUser(uid)?.name?.split(' ')[0]).filter(Boolean).join(', ');
                    return (
                      <button key={emoji}
                        className={'chat-reaction-pill' + (reactedByMe ? ' mine' : '')}
                        onClick={() => toggleReaction(m, emoji)}
                        title={names}>
                        <span className="emo">{emoji}</span>
                        <span className="num">{userIds.length}</span>
                      </button>
                    );
                  })}
                  <button className="chat-reaction-add"
                    onClick={() => setReactionPickerFor(reactionPickerFor === m.id ? null : m.id)}
                    aria-label="Reakció hozzáadása">
                    <Icon name="smile" size={14} stroke={2}/>
                  </button>
                  {reactionPickerFor === m.id && (
                    <div className="chat-reaction-picker">
                      {REACTION_SET.map(r => (
                        <button key={r.emoji}
                          className="chat-reaction-choice"
                          onClick={() => toggleReaction(m, r.emoji)}
                          title={r.label}>
                          <span>{r.emoji}</span>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Composer */}
      <div className="chat-composer">
        {/* Pending kérdés címke */}
        {askUser && (
          <div className="chat-ask-pending">
            <Icon name="help" size={13} stroke={2.4}/>
            <span>Kérdés <b>{askUser.name}</b> felé · email értesítés</span>
            <button className="bare" onClick={() => setAskUser(null)} style={{ padding: 2 }}>
              <Icon name="x" size={14}/>
            </button>
          </div>
        )}
        {/* Pending csatolmányok */}
        {attachments.length > 0 && (
          <div className="chat-attach-row">
            {attachments.map((a, i) => (
              <div key={i} className="chat-attach-pill">
                {a.type === 'image' && a.url ? (
                  <img src={a.url} alt="" style={{ width: 28, height: 28, borderRadius: 4, objectFit: 'cover' }}/>
                ) : (
                  <Icon name={a.type === 'image' ? 'image' : 'doc'} size={14}/>
                )}
                <span style={{ fontSize: 11, maxWidth: 110, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.name}</span>
                <button className="bare" onClick={() => removeAttachment(i)} style={{ padding: 0 }}>
                  <Icon name="x" size={12}/>
                </button>
              </div>
            ))}
          </div>
        )}

        <div className="chat-composer-row">
          <button className="btn ghost sm chat-icon-btn" onClick={() => fileRef.current?.click()} aria-label="Csatolás">
            <Icon name="paperclip" size={18}/>
          </button>
          <input ref={fileRef} type="file" multiple style={{ display: 'none' }} onChange={onFilePick} accept="image/*,.pdf,.doc,.docx,.xls,.xlsx"/>

          <button className={'btn ghost sm chat-icon-btn ' + (askUser ? 'active' : '')} onClick={() => setShowAskPicker(true)} aria-label="Kérdés">
            <Icon name="help" size={18}/>
          </button>

          <textarea
            className="chat-input"
            value={text}
            onChange={e => setText(e.target.value)}
            onKeyDown={e => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
              }
            }}
            placeholder={askUser ? `Üzenet ${askUser.name.split(' ')[0]} részére…` : 'Üzenet…'}
            rows={1}
          />

          <button className="btn accent chat-send-btn"
            onClick={sendMessage}
            disabled={!text.trim() && attachments.length === 0}
            aria-label="Küldés">
            <Icon name="send" size={18}/>
          </button>
        </div>
      </div>

      </div>{/* /chat-main */}
      </div>{/* /chat-window */}

      {/* Kérdés címzett kiválasztó */}
      {showAskPicker && (
        <Sheet open onClose={() => setShowAskPicker(false)} title="Kérdés feltevése">
          <div className="muted" style={{ fontSize: 12, marginBottom: 10 }}>
            Válassz egy projekttagot. Az üzenet mellett kérdés-jelzés jelenik meg, és a címzett <b>email értesítést kap</b> a kérdésről.
          </div>
          <div className="stack-2">
            {projectMembers.filter(u => u.id !== user.id).map(u => {
              const roleL = u.role === 'admin' ? 'Admin' : u.role === 'approver' ? 'Jóváhagyó' : 'Vállalkozó';
              return (
                <button key={u.id} className="card tap" onClick={() => { setAskUser(u); setShowAskPicker(false); }}
                  style={{ padding: 10, display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left' }}>
                  <Avatar user={u} size="sm"/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>{u.name}</div>
                    <div className="muted" style={{ fontSize: 11, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {roleL}{u.skill ? ` · ${u.skill}` : ''} · {u.email}
                    </div>
                  </div>
                  <Icon name="mail" size={16}/>
                </button>
              );
            })}
          </div>
        </Sheet>
      )}
    </div>
  );
};

window.Chat = Chat;
