// Grape Elevate — Inbox screen

function Inbox({ t, conversations, setConversations }) {
  const [filter, setFilter] = React.useState('all');
  const [activeId, setActiveId] = React.useState(conversations[0]?.id);
  const [draft, setDraft] = React.useState('');
  const scrollRef = React.useRef(null);

  const list = conversations.filter((c) => {
    if (filter === 'unread') return c.unread > 0;
    if (filter === 'bot')    return c.bot;
    if (filter === 'human')  return !c.bot;
    return true;
  });

  const active = conversations.find((c) => c.id === activeId);

  React.useEffect(() => {
    if (active && active.unread > 0) {
      setConversations((cs) => cs.map((c) => c.id === active.id ? { ...c, unread: 0 } : c));
    }
    // scroll to bottom on switch
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [activeId]);

  const send = () => {
    const text = draft.trim();
    if (!text || !active) return;
    setConversations((cs) => cs.map((c) => c.id === active.id ? { ...c, msgs: [...c.msgs, { from: 'me', text, t: 'agora' }], last: text, time: 'agora' } : c));
    setDraft('');
    setTimeout(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, 30);
  };

  return (
    <>
      <style>{inboxStyles}</style>
      <div className="page-head">
        <div>
          <h1 className="page-title">{t('inbox.title')}</h1>
          <p className="page-sub">{t('inbox.subtitle')}</p>
        </div>
      </div>

      <div className="ib-shell">
        {/* Conversation list */}
        <aside className="ib-list">
          <div className="ib-filters seg">
            {[['all', t('inbox.filter.all')], ['unread', t('inbox.filter.unread')], ['bot', t('inbox.filter.bot')], ['human', t('inbox.filter.human')]].map(([k, l]) => (
              <button key={k} className={filter === k ? 'active' : ''} onClick={() => setFilter(k)}>{l}</button>
            ))}
          </div>
          <div className="ib-search">
            <div className="search-wrap" style={{ width: '100%' }}>
              <Icons.Search size={14} />
              <input className="input input-search" placeholder="Buscar conversa…" />
            </div>
          </div>
          <div className="ib-rows">
            {list.map((c) => (
              <button key={c.id} className={`ib-conv ${activeId === c.id ? 'active' : ''}`} onClick={() => setActiveId(c.id)}>
                <Avatar hue={c.avatarHue} name={c.name} />
                <div className="ib-conv-body">
                  <div className="row-between">
                    <span className="ib-name">{c.name}</span>
                    <span className="ib-time">{c.time}</span>
                  </div>
                  <div className="row-between">
                    <span className="ib-last">{c.bot && <span className="ib-bot">🤖 </span>}{c.last}</span>
                    {c.unread > 0 && <span className="ib-badge">{c.unread}</span>}
                  </div>
                </div>
              </button>
            ))}
          </div>
        </aside>

        {/* Thread */}
        <section className="ib-thread">
          {active ? (
            <>
              <header className="ib-thread-head">
                <Avatar hue={active.avatarHue} name={active.name} size={40} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700 }}>{active.name}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{active.handle} · {active.source}</div>
                </div>
                <button className="btn btn-sm"><Icons.Users size={14} /> {t('inbox.assign')}</button>
                <button className="btn btn-ghost btn-icon"><Icons.Dots size={16} /></button>
              </header>
              <div className="ib-msgs" ref={scrollRef}>
                {active.msgs.map((m, i) => (
                  <div key={i} className={`ib-msg ib-msg-${m.from}`}>
                    {m.from === 'bot' && <div className="ib-msg-tag"><Icons.Bolt size={11} /> {t('inbox.bot')}</div>}
                    <div className="ib-bubble">{m.text}</div>
                    <div className="ib-time-sm">{m.t}</div>
                  </div>
                ))}
              </div>
              <div className="ib-composer">
                <div className="ib-composer-tools">
                  <button className="btn btn-ghost btn-icon" title="Templates"><Icons.Sparkle size={16} /></button>
                  <button className="btn btn-ghost btn-icon" title="Link"><Icons.Link size={16} /></button>
                  <button className="btn btn-ghost btn-icon" title="Tag"><Icons.Tag size={16} /></button>
                </div>
                <textarea className="ib-input" placeholder={t('inbox.placeholder')} value={draft}
                          onChange={(e) => setDraft(e.target.value)}
                          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }} />
                <button className="btn btn-primary" onClick={send}><Icons.Send size={14} /> {t('inbox.send')}</button>
              </div>
            </>
          ) : (
            <div className="empty">Nenhuma conversa selecionada.</div>
          )}
        </section>

        {/* Details */}
        <aside className="ib-details">
          {active && (
            <>
              <div className="eyebrow" style={{ marginBottom: 12 }}>{t('inbox.details')}</div>
              <div className="ib-contact">
                <Avatar hue={active.avatarHue} name={active.name} size={48} />
                <div>
                  <div style={{ fontWeight: 700 }}>{active.name}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{active.handle}</div>
                </div>
              </div>
              <div className="ib-meta">
                <div className="ib-meta-row"><span className="muted">{t('inbox.firstSeen')}</span><b>há 14 dias</b></div>
                <div className="ib-meta-row"><span className="muted">{t('inbox.lastActive')}</span><b>{active.time}</b></div>
                <div className="ib-meta-row"><span className="muted">{t('inbox.source')}</span><b>{active.source}</b></div>
              </div>
              <div className="ib-section">
                <div className="eyebrow">{t('inbox.tags')}</div>
                <div className="row" style={{ gap: 6, flexWrap: 'wrap', marginTop: 6 }}>
                  {active.tags.map((tg) => <span key={tg} className="pill pill-pop">#{tg}</span>)}
                  <button className="btn btn-sm btn-ghost"><Icons.Plus size={12} /></button>
                </div>
              </div>
              <div className="ib-section">
                <div className="eyebrow">{t('inbox.notes')}</div>
                <textarea className="ib-note" placeholder="Adicione um lembrete sobre este contato…" />
              </div>
            </>
          )}
        </aside>
      </div>
    </>
  );
}

const Avatar = ({ hue = 270, name = '', size = 36 }) => {
  const initials = name.split(' ').slice(0, 2).map((s) => s[0]).join('').toUpperCase();
  const bg = `linear-gradient(135deg, oklch(0.7 0.16 ${hue}), oklch(0.5 0.18 ${(hue + 60) % 360}))`;
  return <div className="avatar" style={{ background: bg, width: size, height: size, fontSize: size * 0.4 }}>{initials}</div>;
};

const inboxStyles = `
.ib-shell {
  display: grid;
  grid-template-columns: 300px 1fr 280px;
  border: 1px solid var(--line);
  border-radius: var(--radius-lg);
  background: var(--surface);
  overflow: hidden;
  height: calc(100vh - 180px);
  min-height: 560px;
  box-shadow: var(--shadow-card);
}
.ib-list { border-right: 1px solid var(--line); background: var(--surface-2); display: flex; flex-direction: column; min-height: 0; }
.ib-filters { margin: 12px; padding: 3px; background: var(--surface); }
.ib-filters button { font-size: 12px; padding: 6px 10px; }
.ib-search { padding: 0 12px 8px; }
.ib-rows { flex: 1; overflow-y: auto; padding: 0 6px 6px; }
.ib-conv {
  display: flex; align-items: center; gap: 10px;
  width: 100%; padding: 10px;
  background: transparent; border: 0; border-radius: 10px;
  cursor: pointer; text-align: left;
  margin-bottom: 2px;
  transition: background 120ms;
}
.ib-conv:hover { background: var(--surface); }
.ib-conv.active { background: var(--surface); box-shadow: inset 0 0 0 1px color-mix(in oklch, var(--grape) 28%, transparent); }
.ib-conv-body { flex: 1; min-width: 0; }
.ib-name { font-weight: 600; font-size: 13.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ib-time { font-size: 11px; color: var(--text-mute); flex-shrink: 0; }
.ib-last { font-size: 12.5px; color: var(--text-soft); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 200px; }
.ib-bot { color: var(--grape); }
.ib-badge { font-size: 10px; font-weight: 700; background: var(--coral); color: #fff; padding: 1px 6px; border-radius: 999px; }

.ib-thread { display: flex; flex-direction: column; min-width: 0; }
.ib-thread-head { display: flex; align-items: center; gap: 12px; padding: 14px 18px; border-bottom: 1px solid var(--line); }
.ib-msgs { flex: 1; overflow-y: auto; padding: 18px; display: flex; flex-direction: column; gap: 16px; background: linear-gradient(180deg, transparent, color-mix(in oklch, var(--grape) 3%, transparent)); }
.ib-msg { display: flex; flex-direction: column; gap: 4px; max-width: 70%; }
.ib-msg-them { align-self: flex-start; }
.ib-msg-me, .ib-msg-bot { align-self: flex-end; align-items: flex-end; }
.ib-msg-tag { font-size: 10.5px; font-weight: 700; color: var(--grape); display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; background: color-mix(in oklch, var(--grape) 14%, var(--surface)); border-radius: 999px; align-self: flex-end; }
.ib-bubble { padding: 10px 14px; border-radius: 16px; font-size: 13.5px; line-height: 1.45; }
.ib-msg-them .ib-bubble { background: var(--surface-2); color: var(--text); border-bottom-left-radius: 6px; }
.ib-msg-me   .ib-bubble { background: linear-gradient(135deg, var(--cyan), var(--grape)); color: #fff; border-bottom-right-radius: 6px; }
.ib-msg-bot  .ib-bubble { background: linear-gradient(135deg, color-mix(in oklch, var(--grape) 16%, var(--surface)), color-mix(in oklch, var(--cyan) 16%, var(--surface))); color: var(--text); border-bottom-right-radius: 6px; border: 1px solid color-mix(in oklch, var(--grape) 28%, transparent); }
.ib-time-sm { font-size: 10.5px; color: var(--text-mute); padding: 0 4px; }

.ib-composer { display: grid; grid-template-columns: auto 1fr auto; gap: 8px; align-items: end; padding: 12px; border-top: 1px solid var(--line); background: var(--surface); }
.ib-composer-tools { display: flex; gap: 2px; padding-bottom: 4px; }
.ib-input { resize: none; min-height: 38px; max-height: 120px; padding: 10px 12px; border-radius: 10px; border: 1px solid var(--line); background: var(--surface); color: var(--text); font-family: inherit; font-size: 13.5px; outline: none; }
.ib-input:focus { border-color: var(--grape); box-shadow: 0 0 0 3px color-mix(in oklch, var(--grape) 22%, transparent); }

.ib-details { border-left: 1px solid var(--line); padding: 16px; background: var(--surface-2); overflow-y: auto; }
.ib-contact { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
.ib-meta { display: flex; flex-direction: column; gap: 8px; padding: 12px; background: var(--surface); border-radius: 10px; border: 1px solid var(--line); font-size: 12.5px; }
.ib-meta-row { display: flex; justify-content: space-between; align-items: center; }
.ib-section { margin-top: 16px; }
.ib-note { width: 100%; height: 80px; resize: none; padding: 10px 12px; border-radius: 10px; border: 1px solid var(--line); background: var(--surface); color: var(--text); font-family: inherit; font-size: 12.5px; outline: none; margin-top: 6px; }
.ib-note:focus { border-color: var(--grape); }
`;

window.Inbox = Inbox;
