// Conversations inbox — email-shape: list left, thread right.

const ACard3 = window.ACard;
const ACardHeader3 = window.ACardHeader;
const { useState: ibUseState } = React;

function AInbox({ branchId, lang, onOpenStudent }) {
  const t = lang === 'zh';
  const [filter, setFilter] = ibUseState('all');
  const [selected, setSelected] = ibUseState('th1');
  const [composeOpen, setComposeOpen] = ibUseState(false);

  const filters = [
    { id: 'all',    en: 'All',         zh: '全部',   count: TL_THREADS.length },
    { id: 'unread', en: 'Unread',      zh: '未讀',   count: TL_THREADS.filter(x => x.unread > 0).length },
    { id: 'star',   en: 'Starred',     zh: '已加星', count: TL_THREADS.filter(x => x.starred).length },
    { id: 'urgent', en: 'Needs reply', zh: '待回覆', count: TL_THREADS.filter(x => x.unread > 0 || x.urgent).length },
    { id: 'sent',   en: 'Sent by you', zh: '已送出', count: TL_THREADS.filter(x => x.you).length },
  ];
  const filtered = TL_THREADS.filter(x => {
    if (filter === 'all') return true;
    if (filter === 'unread') return x.unread > 0;
    if (filter === 'star') return x.starred;
    if (filter === 'urgent') return x.unread > 0 || x.urgent;
    if (filter === 'sent') return x.you;
    return true;
  });

  const sel = TL_THREADS.find(x => x.id === selected);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#F8F8F8' }}>
      {/* page heading */}
      <div style={{ padding: '24px 28px 12px', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#A0A0A0' }}>
            {t ? '通訊收件箱 · 尖沙咀分行' : 'Conversations · Tsim Sha Tsui'}
          </div>
          <h1 style={{ fontFamily: TL_FONTS.serif, fontSize: 32, fontWeight: 500, lineHeight: 1.1, margin: '6px 0 4px', paddingBottom: 4, letterSpacing: '-0.02em', whiteSpace: 'nowrap' }}>
            {t ? <>家長<em style={{ fontStyle: 'italic' }}>對話。</em></> : <>Parent <em style={{ fontStyle: 'italic' }}>conversations.</em></>}
          </h1>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={() => setComposeOpen(true)} style={btnDark2}>
            <TLIcon name="plus" size={12} color="#FFE003" /> {t ? '群發訊息' : 'Broadcast'}
          </button>
          <button style={btnYellow}>
            <TLIcon name="msg" size={12} /> {t ? '新訊息' : 'New message'}
          </button>
        </div>
      </div>

      {/* filter chips */}
      <div style={{ padding: '0 28px 14px', display: 'flex', gap: 6 }}>
        {filters.map(f => {
          const active = filter === f.id;
          return (
            <button key={f.id} onClick={() => setFilter(f.id)} style={{
              padding: '6px 12px',
              background: active ? '#141414' : '#FFFFFF',
              color: active ? '#F8F8F8' : '#333',
              border: '1px solid ' + (active ? '#141414' : 'rgba(20,20,20,0.1)'),
              fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              {t ? f.zh : f.en}
              <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: active ? '#FFE003' : '#A0A0A0' }}>{f.count}</span>
            </button>
          );
        })}
      </div>

      {/* split view */}
      <div style={{ flex: 1, display: 'flex', minHeight: 0, padding: '0 28px 24px', gap: 12 }}>
        {/* THREAD LIST */}
        <div style={{ width: 360, background: '#FFFFFF', border: '1px solid rgba(20,20,20,0.08)', overflow: 'auto' }} className="tl-noscroll">
          {filtered.map(th => {
            const active = th.id === selected;
            return (
              <button key={th.id} onClick={() => setSelected(th.id)} style={{
                display: 'block', width: '100%', textAlign: 'left',
                padding: '14px 16px',
                background: active ? 'rgba(255,224,3,0.16)' : 'transparent',
                borderLeft: active ? '3px solid #FFE003' : '3px solid transparent',
                borderBottom: '1px solid rgba(20,20,20,0.05)',
                border: 'none',
                cursor: 'pointer',
              }}>
                <div style={{
                  display: 'block',
                  borderLeft: active ? '3px solid #FFE003' : '3px solid transparent',
                  paddingLeft: active ? 10 : 13, marginLeft: -16, paddingRight: 16,
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 2 }}>
                    <span style={{ fontFamily: TL_FONTS.sans, fontSize: 13, fontWeight: th.unread > 0 ? 600 : 500, color: '#141414' }}>
                      {th.starred && <span style={{ color: '#FFB800', marginRight: 4 }}>★</span>}
                      {th.name}
                    </span>
                    <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0' }}>{th.when}</span>
                  </div>
                  <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#6B6B6B', letterSpacing: '0.04em', marginBottom: 4 }}>
                    {th.family}
                  </div>
                  <div style={{
                    display: 'flex', alignItems: 'center', gap: 8,
                    fontFamily: TL_FONTS.sans, fontSize: 11,
                    color: th.unread > 0 ? '#141414' : '#6B6B6B',
                    fontWeight: th.unread > 0 ? 500 : 400,
                  }}>
                    {th.you && <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0' }}>YOU:</span>}
                    <span style={{
                      flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }}>{th.lastMsg}</span>
                    {th.unread > 0 && (
                      <span style={{
                        background: '#FFE003', color: '#141414',
                        padding: '1px 6px', fontFamily: TL_FONTS.mono, fontSize: 9, fontWeight: 600,
                      }}>{th.unread}</span>
                    )}
                  </div>
                  {th.urgent && (
                    <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#B14B4B', marginTop: 4, letterSpacing: '0.1em' }}>
                      ⚠ {t ? '需立即跟進' : 'NEEDS FOLLOW-UP'}
                    </div>
                  )}
                  <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginTop: 4 }}>
                    {t ? '由' : 'by'} {th.by}
                  </div>
                </div>
              </button>
            );
          })}
        </div>

        {/* THREAD DETAIL */}
        <div style={{ flex: 1, background: '#FFFFFF', border: '1px solid rgba(20,20,20,0.08)', display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          {sel ? (
            <>
              {/* thread header */}
              <div style={{ padding: '16px 20px', borderBottom: '1px solid rgba(20,20,20,0.08)', display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{
                  width: 40, height: 40, background: '#E8DCC8', flexShrink: 0,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: TL_FONTS.serif, fontSize: 14, fontWeight: 500,
                }}>{sel.name.split(' ').slice(-1)[0].slice(0,2).toUpperCase()}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ fontFamily: TL_FONTS.serif, fontSize: 18, fontWeight: 500 }}>{sel.name}</div>
                    <span style={{ padding: '2px 7px', background: '#FFE003', fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.08em', color: '#141414' }}>WHATSAPP</span>
                  </div>
                  <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: '#6B6B6B', marginTop: 2 }}>
                    {sel.family}
                    {sel.studentId === 's1' && (
                      <button onClick={() => onOpenStudent && onOpenStudent('s1')} style={{
                        marginLeft: 10, background: 'none', border: 'none', padding: 0, cursor: 'pointer',
                        fontFamily: TL_FONTS.mono, fontSize: 10, color: '#141414', textDecoration: 'underline',
                      }}>{t ? '查看學生資料' : 'view student'} →</button>
                    )}
                  </div>
                </div>
                <button style={btnGhost2}><TLIcon name="user" size={12} /> {t ? '聯絡資料' : 'Contact'}</button>
                <button style={btnGhost2}><TLIcon name="cal" size={12} /> {t ? '排堂' : 'Schedule'}</button>
              </div>

              {/* messages */}
              <div style={{ flex: 1, overflow: 'auto', padding: '20px', display: 'flex', flexDirection: 'column', gap: 12 }} className="tl-noscroll">
                {sel.id === 'th1' ? (
                  TL_THREAD_S1_MSGS.map(m => {
                    if (m.from === 'sys') {
                      return (
                        <div key={m.id} style={{ alignSelf: 'center', padding: '6px 14px', background: '#F8F8F8', fontFamily: TL_FONTS.mono, fontSize: 10, color: '#6B6B6B', letterSpacing: '0.06em' }}>
                          {m.text} · {m.when}
                        </div>
                      );
                    }
                    const isYou = m.from === 'you';
                    return (
                      <div key={m.id} style={{
                        alignSelf: isYou ? 'flex-end' : 'flex-start',
                        maxWidth: '70%',
                      }}>
                        <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginBottom: 4, textAlign: isYou ? 'right' : 'left' }}>
                          {m.name} · {m.when}
                        </div>
                        <div style={{
                          padding: '10px 14px',
                          background: isYou ? '#141414' : '#F8F8F8',
                          color: isYou ? '#F8F8F8' : '#141414',
                          fontFamily: TL_FONTS.sans, fontSize: 13, lineHeight: 1.45,
                        }}>{m.text}</div>
                      </div>
                    );
                  })
                ) : (
                  <div style={{ alignSelf: 'flex-start', maxWidth: '70%' }}>
                    <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginBottom: 4 }}>{sel.name} · {sel.when}</div>
                    <div style={{ padding: '10px 14px', background: '#F8F8F8', fontFamily: TL_FONTS.sans, fontSize: 13, lineHeight: 1.45 }}>{sel.lastMsg}</div>
                  </div>
                )}
              </div>

              {/* compose */}
              <div style={{ borderTop: '1px solid rgba(20,20,20,0.08)', padding: 14 }}>
                <textarea placeholder={t ? '輸入回覆…' : 'Reply…'} rows={2} style={{
                  width: '100%', padding: 10, border: '1px solid rgba(20,20,20,0.1)',
                  background: '#F8F8F8', fontFamily: TL_FONTS.sans, fontSize: 12, outline: 'none', resize: 'none',
                }} />
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 10 }}>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button style={btnGhost2}><TLIcon name="paperclip" size={12} /></button>
                    <button style={btnGhost2}>{t ? '範本' : 'Template'} <TLIcon name="chevD" size={11} /></button>
                  </div>
                  <button style={btnYellow}>
                    {t ? '傳送 WhatsApp' : 'Send via WhatsApp'} <TLIcon name="send" size={12} />
                  </button>
                </div>
              </div>
            </>
          ) : (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#6B6B6B', fontFamily: TL_FONTS.sans }}>
              {t ? '選擇對話' : 'Select a thread'}
            </div>
          )}
        </div>
      </div>

      {composeOpen && <BroadcastModal t={t} onClose={() => setComposeOpen(false)} />}
    </div>
  );
}

function BroadcastModal({ t, onClose }) {
  const [scope, setScope] = ibUseState('segment');
  const [tpl, setTpl] = ibUseState('tp1');
  return (
    <div style={{
      position: 'absolute', inset: 0, background: 'rgba(20,20,20,0.6)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 560, background: '#FFFFFF', border: '1px solid #141414',
      }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid rgba(20,20,20,0.08)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#6B6B6B' }}>
              {t ? '群發訊息' : 'Broadcast'}
            </div>
            <div style={{ fontFamily: TL_FONTS.serif, fontSize: 20, fontWeight: 500, marginTop: 2 }}>
              {t ? '發送 WhatsApp 訊息' : 'Send WhatsApp message'}
            </div>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', padding: 4, cursor: 'pointer' }}>
            <TLIcon name="x" size={18} />
          </button>
        </div>
        <div style={{ padding: 20 }}>
          <FieldLabel>{t ? '收件人' : 'Recipients'}</FieldLabel>
          <div style={{ display: 'flex', gap: 6, marginBottom: 14 }}>
            {[
              { id: 'one',     en: 'One parent',      zh: '單一家長' },
              { id: 'segment', en: 'Segment',         zh: '群組篩選' },
              { id: 'all',     en: 'Branch-wide',     zh: '全分行' },
            ].map(o => (
              <button key={o.id} onClick={() => setScope(o.id)} style={{
                padding: '7px 14px',
                background: scope === o.id ? '#141414' : '#FFFFFF',
                color: scope === o.id ? '#F8F8F8' : '#333',
                border: '1px solid ' + (scope === o.id ? '#141414' : 'rgba(20,20,20,0.1)'),
                fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer',
              }}>{t ? o.zh : o.en}</button>
            ))}
          </div>

          {scope === 'segment' && (
            <div style={{ background: '#F8F8F8', padding: 14, marginBottom: 14 }}>
              <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#6B6B6B', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8 }}>
                {t ? '篩選條件' : 'Filters'}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
                <SelectStub label={t ? '科目' : 'Subject'} value="Piano" />
                <SelectStub label={t ? '級別' : 'Level'} value="Grade 5" />
                <SelectStub label={t ? '老師' : 'Teacher'} value={t ? '所有' : 'Any'} />
              </div>
              <div style={{ marginTop: 10, fontFamily: TL_FONTS.mono, fontSize: 10, color: '#141414' }}>
                {t ? '預計收件人：' : 'Will reach: '}<strong>32 {t ? '位家長' : 'parents'}</strong>
              </div>
            </div>
          )}
          {scope === 'all' && (
            <div style={{ background: '#FFE003', padding: 14, marginBottom: 14, fontFamily: TL_FONTS.sans, fontSize: 12, color: '#141414' }}>
              ⚠ {t ? '將發送至尖沙咀分行所有 524 位家長' : 'Will reach all 524 parents at Tsim Sha Tsui branch'}
            </div>
          )}

          <FieldLabel>{t ? '範本' : 'Template'}</FieldLabel>
          <select value={tpl} onChange={e => setTpl(e.target.value)} style={{
            width: '100%', padding: '8px 10px', border: '1px solid rgba(20,20,20,0.15)',
            background: '#FFF', fontFamily: TL_FONTS.sans, fontSize: 12, marginBottom: 14, outline: 'none',
          }}>
            {TL_BROADCAST_TPL.map(b => <option key={b.id} value={b.id}>{b.label}</option>)}
          </select>

          <FieldLabel>{t ? '訊息內容' : 'Message'}</FieldLabel>
          <textarea rows={5} defaultValue={
            scope === 'all'
              ? '通利音樂尖沙咀分行將於 5 月 1 日勞動節休息，5 月 2 日恢復課堂。Branch closed for Labour Day on May 1 — lessons resume May 2.'
              : 'This is a friendly reminder that Term 2 fees of HK$4,800 are now due. Please settle by Apr 30. Thank you.'
          } style={{
            width: '100%', padding: 10, border: '1px solid rgba(20,20,20,0.15)',
            background: '#FFF', fontFamily: TL_FONTS.sans, fontSize: 12, outline: 'none', resize: 'vertical',
          }} />

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 16 }}>
            <span style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: '#6B6B6B' }}>
              {t ? '雙語：英文 + 繁體中文' : 'Bilingual: English + 繁中'}
            </span>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={onClose} style={btnGhost2}>{t ? '取消' : 'Cancel'}</button>
              <button style={btnYellow}>{t ? '預覽並傳送' : 'Preview & send'}</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function FieldLabel({ children }) {
  return <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#6B6B6B', marginBottom: 6 }}>{children}</div>;
}
function SelectStub({ label, value }) {
  return (
    <div>
      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 8, color: '#A0A0A0', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 4 }}>{label}</div>
      <div style={{ padding: '7px 10px', background: '#FFFFFF', border: '1px solid rgba(20,20,20,0.1)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontFamily: TL_FONTS.sans, fontSize: 12 }}>
        {value}
        <TLIcon name="chevD" size={11} color="#A0A0A0" />
      </div>
    </div>
  );
}

const btnGhost2 = { background: 'transparent', border: '1px solid rgba(20,20,20,0.15)', padding: '6px 11px', fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 };
const btnDark2  = { background: '#141414', color: '#F8F8F8', border: 'none', padding: '8px 14px', fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 };
const btnYellow = { background: '#FFE003', color: '#141414', border: 'none', padding: '8px 14px', fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 };

window.AInbox = AInbox;
