/* Inbox tab — unified DMs / comments / mentions across all channels */

const THREAD_MESSAGES_INITIAL = {
  t1: [
    { id: 'm1', side: 'them', text: 'Hey! Saw the Berlin pop-up post — when does it open this Saturday?', time: null },
    { id: 'm2', side: 'them', text: 'Also: any chance of the carbon-edition pieces being there?', time: '14:09' },
    { id: 'm3', side: 'me',   text: 'Hi Maria 👋 We open Saturday 10:00 at Linienstraße 81. Carbon-edition will be on display from 11:00.', time: '14:14', suggested: true },
    { id: 'm4', side: 'them', text: 'Wann ist der Pop-Up in Berlin? 🙌', time: '14:21' },
  ],
};

function InboxTab() {
  const [filter, setFilter] = useState('all');
  const [search, setSearch] = useState('');
  const [activeId, setActiveId] = useState('t1');
  const [threads, setThreads] = useState(() => INBOX_THREADS.map(t => ({ ...t })));
  const [threadMessages, setThreadMessages] = useState(THREAD_MESSAGES_INITIAL);
  const [composerText, setComposerText] = useState('');
  const messagesEndRef = useRef(null);

  const active = threads.find(t => t.id === activeId);
  const messages = threadMessages[activeId] || [];

  const visible = threads.filter(t => {
    const matchesFilter =
      filter === 'all' ? true :
      filter === 'unread' ? t.unread > 0 :
      filter === 'dm' ? t.kind === 'dm' :
      filter === 'comment' ? t.kind === 'comment' :
      filter === 'mention' ? t.kind === 'mention' :
      true;

    if (!matchesFilter) return false;
    if (!search) return true;
    const q = search.toLowerCase();
    return t.name.toLowerCase().includes(q) || t.last.toLowerCase().includes(q);
  });

  function selectThread(id) {
    setActiveId(id);
    setThreads(prev => prev.map(t => t.id === id ? { ...t, unread: 0 } : t));
  }

  function sendMessage() {
    const text = composerText.trim();
    if (!text) return;
    const newMsg = {
      id: 'm' + Date.now(),
      side: 'me',
      text,
      time: 'just now',
    };
    setThreadMessages(prev => ({
      ...prev,
      [activeId]: [...(prev[activeId] || []), newMsg],
    }));
    setThreads(prev => prev.map(t =>
      t.id === activeId ? { ...t, last: text, time: 'just now' } : t
    ));
    setComposerText('');
  }

  function handleKeyDown(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  }

  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages.length, activeId]);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr 320px', height: '100%' }}>

      {/* Thread list */}
      <div style={{ borderRight: '1px solid var(--line)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <div style={{ padding: '16px 16px 12px', display: 'flex', flexDirection: 'column', gap: 10, borderBottom: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div className="caps" style={{ color: 'var(--fg-3)' }}>Conversations</div>
            <span className="chip mono" style={{ fontSize: 10 }}>{threads.reduce((a, t) => a + t.unread, 0)} unread</span>
          </div>
          <input
            className="input"
            placeholder="Search messages…"
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
          <div className="seg" style={{ width: '100%' }}>
            <button className={filter==='all'?'on':''} style={{ flex: 1 }} onClick={()=>setFilter('all')}>All</button>
            <button className={filter==='unread'?'on':''} style={{ flex: 1 }} onClick={()=>setFilter('unread')}>Unread</button>
            <button className={filter==='dm'?'on':''} style={{ flex: 1 }} onClick={()=>setFilter('dm')}>DMs</button>
            <button className={filter==='comment'?'on':''} style={{ flex: 1 }} onClick={()=>setFilter('comment')}>Comments</button>
          </div>
        </div>

        <div className="stagger" style={{ flex: 1, overflow: 'auto', padding: '8px 8px' }}>
          {visible.length === 0 && (
            <div style={{ padding: '24px 12px', textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
              No threads match
            </div>
          )}
          {visible.map(t => (
            <button key={t.id} onClick={()=>selectThread(t.id)} className="press" style={{
              display: 'flex', gap: 10, alignItems: 'flex-start',
              padding: '10px 10px', borderRadius: 10,
              background: activeId === t.id ? 'var(--bg-2)' : 'transparent',
              border: '1px solid ' + (activeId === t.id ? 'var(--line-2)' : 'transparent'),
              width: '100%', textAlign: 'left', color: 'var(--fg)', cursor: 'pointer',
              transition: 'all .2s var(--ease)',
            }}>
              <Avatar name={t.name} ch={t.ch} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                  <span style={{ fontSize: 12.5, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.name}</span>
                  <Flag code={t.mk} size={11} />
                  <span style={{ flex: 1 }} />
                  <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>{t.time}</span>
                </div>
                <div style={{ fontSize: 12, color: t.unread ? 'var(--fg)' : 'var(--fg-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.last}</div>
                <div style={{ display: 'flex', gap: 6, marginTop: 6, alignItems: 'center' }}>
                  <span className="caps" style={{ color: 'var(--fg-4)', fontSize: 9.5 }}>{t.kind}</span>
                  {t.tag && <span className="chip" style={{ padding: '1px 6px', fontSize: 9.5 }}>{t.tag}</span>}
                  <div style={{ flex: 1 }} />
                  {t.unread > 0 && (
                    <span className="chip accent" style={{ padding: '0 6px', fontSize: 10, height: 16 }}>{t.unread}</span>
                  )}
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* Conversation pane */}
      <div style={{ display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <div style={{ padding: '14px 24px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <Avatar name={active.name} ch={active.ch} size={40} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontFamily: 'Hanken Grotesk', fontSize: 16, fontWeight: 600 }}>{active.name}</span>
              <Flag code={active.mk} size={13} />
              <ChannelGlyph ch={active.ch} size={11} />
              {active.tag && <span className="chip">{active.tag}</span>}
            </div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)' }}>{active.who} · {active.kind}</div>
          </div>
          <button className="btn sm press"><Icon name="archive" size={14} /> Archive</button>
          <button className="btn sm press"><Icon name="more_horiz" size={14} /></button>
        </div>

        <div className="stagger" style={{ flex: 1, overflow: 'auto', padding: '24px 80px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <DateDivider label="Today, 14:08" />
          {messages.map(m => (
            <Message key={m.id} side={m.side} name={active.name} text={m.text} time={m.time} suggested={m.suggested} />
          ))}
          <div ref={messagesEndRef} />
        </div>

        {/* Composer */}
        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <span className="caps" style={{ color: 'var(--fg-3)' }}>AI suggestions</span>
            <button className="chip press" style={{ cursor: 'pointer' }} onClick={() => setComposerText('Saturday at 10:00 · Linienstraße 81')}>Saturday at 10:00 · Linienstraße 81</button>
            <button className="chip press" style={{ cursor: 'pointer' }} onClick={() => setComposerText('Yes, carbon edition is on display')}>Yes, carbon edition is on display</button>
          </div>
          <div style={{
            display: 'flex', gap: 8, alignItems: 'flex-end',
            padding: 10, background: 'var(--bg-2)', border: '1px solid var(--line-2)', borderRadius: 14,
          }}>
            <button className="btn ghost sm press" style={{ width: 32, padding: 0, justifyContent: 'center' }}><Icon name="attach_file" size={16} /></button>
            <textarea
              placeholder="Reply to Maria K. on Instagram…"
              value={composerText}
              onChange={e => setComposerText(e.target.value)}
              onKeyDown={handleKeyDown}
              style={{
                flex: 1, background: 'transparent', border: 'none', outline: 'none',
                color: 'var(--fg)', fontFamily: 'Geist', fontSize: 14, resize: 'none',
                minHeight: 28, lineHeight: 1.45,
              }}
            />
            <button className="btn ghost sm press" style={{ width: 32, padding: 0, justifyContent: 'center' }}><Icon name="auto_awesome" size={16} /></button>
            <button className="btn primary press" onClick={sendMessage}><Icon name="send" size={14} /> Send</button>
          </div>
        </div>
      </div>

      {/* Right rail — context */}
      <aside style={{ borderLeft: '1px solid var(--line)', padding: '20px 18px', display: 'flex', flexDirection: 'column', gap: 14, overflow: 'auto' }}>
        <div className="caps" style={{ color: 'var(--fg-3)' }}>Context</div>

        <div className="panel" style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Avatar name={active.name} ch={active.ch} size={44} />
            <div>
              <div style={{ fontFamily: 'Hanken Grotesk', fontSize: 14, fontWeight: 600 }}>{active.name}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)' }}>{active.who}</div>
            </div>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <SmallStat label="Followers" value="4.2k" />
            <SmallStat label="Engagement" value="6.1%" />
            <SmallStat label="Sent" value="3" />
          </div>
        </div>

        <div className="panel" style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div className="caps" style={{ color: 'var(--fg-3)' }}>Tags</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            <span className="chip" style={{ color: 'var(--good)', borderColor: 'rgba(121,210,163,.3)' }}>lead</span>
            <span className="chip">berlin</span>
            <span className="chip">pop-up</span>
            <button className="btn sm ghost press" style={{ height: 22, padding: '0 8px', fontSize: 11 }}><Icon name="add" size={11}/> Add</button>
          </div>
        </div>

        <div className="panel" style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div className="caps" style={{ color: 'var(--fg-3)' }}>Linked post</div>
          <div style={{ display: 'flex', gap: 10 }}>
            <PhotoTile ph="ph-warm" style={{ width: 56, height: 56, borderRadius: 8 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, lineHeight: 1.35 }}>Pop-Up Berlin — Saturday 10:00</div>
              <div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-3)' }}>IG · 12.4k views · 18 comments</div>
            </div>
          </div>
        </div>

        <div className="panel" style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div className="caps" style={{ color: 'var(--fg-3)' }}>Channels connected</div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {['ig','tt','li','x','fb','yt'].map(ch => (
              <ChannelGlyph key={ch} ch={ch} size={14} />
            ))}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>3 / 6 active · routed into one inbox.</div>
        </div>
      </aside>
    </div>
  );
}

function Avatar({ name, ch, size = 36 }) {
  const initials = name.split(' ').map(n => n[0]).slice(0,2).join('').toUpperCase();
  const grads = ['#2a323a','#322a3a','#3a322a','#2a3a32'];
  const idx = name.length % grads.length;
  return (
    <div style={{ position: 'relative', flexShrink: 0 }}>
      <div style={{
        width: size, height: size, borderRadius: 99,
        background: grads[idx],
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'Hanken Grotesk', fontWeight: 600, fontSize: size * 0.36,
        color: 'var(--fg)', border: '1px solid var(--line-2)',
      }}>{initials}</div>
      <div style={{ position: 'absolute', bottom: -2, right: -2 }}><ChannelGlyph ch={ch} size={9} /></div>
    </div>
  );
}

function DateDivider({ label }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'var(--fg-3)', margin: '8px 0' }}>
      <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
      <span className="mono" style={{ fontSize: 10.5, letterSpacing: 0.04 }}>{label}</span>
      <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
    </div>
  );
}

function Message({ side, name, text, time, suggested }) {
  const me = side === 'me';
  return (
    <div className="anim-fade-up" style={{ display: 'flex', flexDirection: 'column', alignItems: me ? 'flex-end' : 'flex-start', gap: 4 }}>
      <div style={{
        maxWidth: '70%',
        padding: '10px 14px',
        borderRadius: me ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
        background: me ? 'var(--fg)' : 'var(--bg-2)',
        color: me ? '#0e0e10' : 'var(--fg)',
        border: me ? 'none' : '1px solid var(--line-2)',
        fontSize: 13.5, lineHeight: 1.5,
      }}>{text}</div>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        {time && <span className="mono" style={{ fontSize: 10, color: 'var(--fg-4)' }}>{time}</span>}
        {suggested && <span className="chip" style={{ padding: '1px 6px', fontSize: 9.5, color: 'var(--accent)' }}>AI suggested</span>}
      </div>
    </div>
  );
}

function SmallStat({ label, value }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
      <span style={{ fontFamily: 'Hanken Grotesk', fontSize: 16, fontWeight: 600 }}>{value}</span>
      <span className="caps" style={{ color: 'var(--fg-3)' }}>{label}</span>
    </div>
  );
}

Object.assign(window, { InboxTab });
