// Research module — School tender monitoring.
// List of detected tenders + pipeline + detail panel + stakeholder routing.

const { useState: rtUseState } = React;

function RTenders({ lang }) {
  const [selectedId, setSelectedId] = rtUseState(TL_TENDERS[0].id);
  const [statusFilter, setStatusFilter] = rtUseState('all');
  const tender = TL_TENDERS.find(t => t.id === selectedId);

  const statusFilters = [
    { id: 'all',       en: 'All',       zh: '全部',   count: TL_TENDERS.length },
    { id: 'new',       en: 'New',       zh: '新',     count: TL_TENDER_PIPELINE.new },
    { id: 'reviewing', en: 'Reviewing', zh: '審視中', count: TL_TENDER_PIPELINE.reviewing },
    { id: 'submitted', en: 'Submitted', zh: '已投標', count: TL_TENDER_PIPELINE.submitted },
    { id: 'declined',  en: 'Declined',  zh: '已棄標', count: TL_TENDER_PIPELINE.declined },
  ];

  const items = statusFilter === 'all' ? TL_TENDERS : TL_TENDERS.filter(t => t.status === statusFilter);

  return (
    <div style={{ height: '100%', display: 'flex', overflow: 'hidden' }}>
      {/* Left: tender list */}
      <div style={{ width: 420, borderRight: '1px solid rgba(20,20,20,0.08)', background: '#FAFAFA', display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
        <div style={{ padding: '20px 20px 14px', borderBottom: '1px solid rgba(20,20,20,0.08)' }}>
          <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#A0A0A0' }}>
            {lang === 'zh' ? '招標漏斗' : 'Tender pipeline'}
          </div>
          <h2 style={{ fontFamily: TL_FONTS.serif, fontSize: 22, fontWeight: 500, margin: '4px 0 12px', letterSpacing: '-0.02em' }}>
            {TL_TENDERS.length} <span style={{ color: '#A0A0A0' }}>{lang === 'zh' ? '個機會' : 'opportunities'}</span>
          </h2>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
            {statusFilters.map(f => (
              <button key={f.id} onClick={() => setStatusFilter(f.id)} style={{
                padding: '5px 9px', cursor: 'pointer', border: '1px solid rgba(20,20,20,0.12)',
                background: statusFilter === f.id ? '#141414' : 'transparent',
                color: statusFilter === f.id ? '#FFE003' : '#333',
                fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.08em', textTransform: 'uppercase',
              }}>{lang === 'zh' ? f.zh : f.en} <span style={{ opacity: 0.7, marginLeft: 3 }}>{f.count}</span></button>
            ))}
          </div>
        </div>

        <div style={{ flex: 1, overflow: 'auto' }}>
          {items.map(t => {
            const active = t.id === selectedId;
            return (
              <button key={t.id} onClick={() => setSelectedId(t.id)} style={{
                display: 'block', width: '100%', textAlign: 'left',
                padding: '14px 20px', cursor: 'pointer', border: 'none',
                background: active ? '#FFFFFF' : 'transparent',
                borderLeft: active ? '3px solid #141414' : (t.priority === 'high' ? '3px solid #FFE003' : '3px solid transparent'),
                borderBottom: '1px solid rgba(20,20,20,0.06)',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
                  <RPill tone={t.priority === 'high' ? 'critical' : t.priority === 'med' ? 'warning' : 'neutral'}>
                    {lang === 'zh' ? (t.priority === 'high' ? '高' : t.priority === 'med' ? '中' : '低') : t.priority}
                  </RPill>
                  <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, color: '#A0A0A0', letterSpacing: '0.08em' }}>{t.category}</span>
                  <span style={{ flex: 1 }} />
                  <span style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: '#141414', fontWeight: 600 }}>{t.estValueLabel}</span>
                </div>
                <div style={{ fontFamily: TL_FONTS.serif, fontSize: 14, color: '#141414', fontWeight: active ? 500 : 400 }}>
                  {lang === 'zh' ? t.schoolZh : t.school}
                </div>
                <div style={{ fontFamily: TL_FONTS.sans, fontSize: 11.5, color: '#6B6B6B', marginTop: 2, lineHeight: 1.4, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                  {lang === 'zh' ? t.titleZh : t.title}
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontFamily: TL_FONTS.mono, fontSize: 9.5, color: '#A0A0A0', letterSpacing: '0.06em' }}>
                  <span>{t.district}</span>
                  <span>{lang === 'zh' ? '截止' : 'DUE'} {t.deadline}</span>
                  <span style={{ color: t.fitScore >= 0.85 ? '#1B5E20' : '#A0A0A0', fontWeight: 600 }}>
                    {Math.round(t.fitScore*100)}% {lang === 'zh' ? '匹配' : 'fit'}
                  </span>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Right: detail */}
      <div style={{ flex: 1, overflow: 'auto', padding: '24px 32px 32px' }}>
        <div style={{ marginBottom: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <RPill tone={tender.priority === 'high' ? 'critical' : tender.priority === 'med' ? 'warning' : 'neutral'}>
              {lang === 'zh'
                ? (tender.priority === 'high' ? '優先級 · 高' : tender.priority === 'med' ? '優先級 · 中' : '優先級 · 低')
                : `Priority · ${tender.priority}`}
            </RPill>
            <RPill tone="neutral">{tender.category}</RPill>
            <RPill tone={tender.status === 'new' ? 'critical' : tender.status === 'submitted' ? 'ok' : tender.status === 'declined' ? 'grey' : 'info'}>
              {lang === 'zh'
                ? ({ new: '新', reviewing: '審視中', submitted: '已投標', declined: '已棄標' })[tender.status]
                : tender.status}
            </RPill>
          </div>
          <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#A0A0A0', marginBottom: 4 }}>
            {tender.district} · {lang === 'zh' ? '發布' : 'Published'} {tender.publishedAt}
          </div>
          <h1 style={{ fontFamily: TL_FONTS.serif, fontSize: 28, fontWeight: 500, margin: 0, letterSpacing: '-0.02em', lineHeight: 1.15 }}>
            {lang === 'zh' ? tender.schoolZh : tender.school}
          </h1>
          <div style={{ fontFamily: TL_FONTS.serif, fontSize: 18, fontStyle: 'italic', color: '#333', marginTop: 6, lineHeight: 1.35 }}>
            {lang === 'zh' ? tender.titleZh : tender.title}
          </div>
        </div>

        {/* KPI strip */}
        <div style={{ display: 'flex', gap: 0, margin: '20px 0 24px', border: '1px solid rgba(20,20,20,0.08)' }}>
          {[
            { label: lang === 'zh' ? '預算' : 'Est. value', value: tender.estValueLabel, accent: true },
            { label: lang === 'zh' ? '截止日期' : 'Deadline', value: tender.deadline, sub: deadlineDays(tender.deadline) + (lang === 'zh' ? ' 日後' : ' days') },
            { label: lang === 'zh' ? '匹配度' : 'Fit score', value: `${Math.round(tender.fitScore*100)}%`, sub: lang === 'zh' ? 'AI 評估' : 'AI assessed' },
            { label: lang === 'zh' ? '來源' : 'Source', value: lang === 'zh' ? '官方網站' : 'Official site', sub: tender.sourceUrl, mono: true },
          ].map((k, i) => (
            <div key={i} style={{ flex: 1, padding: '14px 16px', borderRight: i < 3 ? '1px solid rgba(20,20,20,0.08)' : 'none', background: k.accent ? '#FFE003' : '#FFFFFF' }}>
              <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.16em', color: k.accent ? '#5A4A00' : '#A0A0A0', textTransform: 'uppercase' }}>{k.label}</div>
              <div style={{ fontFamily: k.mono ? TL_FONTS.mono : TL_FONTS.serif, fontSize: k.mono ? 13 : 22, fontWeight: 500, marginTop: 4, color: '#141414', letterSpacing: '-0.01em' }}>{k.value}</div>
              {k.sub && <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, color: k.accent ? '#5A4A00' : '#6B6B6B', marginTop: 2 }}>{k.sub}</div>}
            </div>
          ))}
        </div>

        {/* AI summary */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 20 }}>
          <div>
            <RSectionHead no="01" title={lang === 'zh' ? 'AI 摘要與分類' : 'AI summary & classification'} />
            <div style={{ padding: '16px 18px', background: '#141414', color: '#F8F8F8', marginBottom: 14 }}>
              <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, color: '#FFE003', letterSpacing: '0.16em', marginBottom: 8 }}>SUMMARY</div>
              <p style={{ fontFamily: TL_FONTS.serif, fontSize: 14, fontStyle: 'italic', margin: 0, lineHeight: 1.5 }}>
                {lang === 'zh' ? tender.summaryZh : tender.summary}
              </p>
            </div>

            <div style={{ marginBottom: 14 }}>
              <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, color: '#A0A0A0', letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 8 }}>
                {lang === 'zh' ? '識別關鍵字' : 'Detected keywords'}
              </div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {tender.keywords.map((k, i) => (
                  <span key={i} style={{
                    padding: '5px 10px', background: '#F8F8F8', border: '1px solid rgba(20,20,20,0.08)',
                    fontFamily: TL_FONTS.mono, fontSize: 11, color: '#141414',
                  }}>{k}</span>
                ))}
              </div>
            </div>

            <div style={{ display: 'flex', gap: 10 }}>
              <button style={{
                flex: 1, padding: '14px', background: '#141414', color: '#F8F8F8', border: 'none',
                fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              }}>
                <TLIcon name="check" size={13} color="#FFE003" /> {lang === 'zh' ? '指派負責人' : 'Assign owner'}
              </button>
              <button style={{
                padding: '14px 18px', background: 'transparent', color: '#141414', border: '1px solid #141414',
                fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer',
              }}>
                {lang === 'zh' ? '匯出' : 'Export'}
              </button>
              <button style={{
                padding: '14px 18px', background: 'transparent', color: '#6B6B6B', border: '1px solid rgba(20,20,20,0.2)',
                fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer',
              }}>
                {lang === 'zh' ? '棄標' : 'Decline'}
              </button>
            </div>
          </div>

          {/* Routing */}
          <div>
            <RSectionHead no="02" title={lang === 'zh' ? '通知對象' : 'Notify stakeholders'} />
            <div style={{ background: '#FFFFFF', border: '1px solid rgba(20,20,20,0.08)' }}>
              {TL_STAKEHOLDERS.filter(s => ['edu','piano','exec'].includes(s.id)).map((s, i, arr) => (
                <div key={s.id} style={{
                  padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10,
                  borderBottom: i < arr.length - 1 ? '1px solid rgba(20,20,20,0.06)' : 'none',
                }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: '50%', background: '#141414', color: '#FFE003',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: TL_FONTS.mono, fontSize: 9, fontWeight: 600,
                  }}>{s.lead.split(' ').map(p => p[0]).join('')}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: TL_FONTS.sans, fontSize: 12.5, color: '#141414' }}>{s.name}</div>
                    <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, color: '#A0A0A0', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.lead} · {s.email}</div>
                  </div>
                  <input type="checkbox" defaultChecked={s.id === 'edu' || s.id === 'piano'} style={{ accentColor: '#141414' }} />
                </div>
              ))}
            </div>

            <div style={{ marginTop: 16, padding: 14, background: '#F8F8F8', border: '1px solid rgba(20,20,20,0.08)' }}>
              <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, color: '#A0A0A0', letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 6 }}>
                {lang === 'zh' ? '通知方式' : 'Channels'}
              </div>
              {[
                { label: lang === 'zh' ? '電郵' : 'Email',    on: true },
                { label: 'Microsoft Teams',                    on: true },
                { label: 'WhatsApp Business',                  on: true },
                { label: 'SMS',                                on: false },
              ].map((c, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0', fontFamily: TL_FONTS.sans, fontSize: 12, color: c.on ? '#141414' : '#A0A0A0' }}>
                  <span style={{ width: 10, height: 10, background: c.on ? '#141414' : 'transparent', border: c.on ? 'none' : '1px solid #C8C8C8' }} />
                  {c.label}
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Pipeline visual */}
        <div style={{ marginTop: 28 }}>
          <RSectionHead no="03" title={lang === 'zh' ? '招標漏斗總覽' : 'Pipeline overview'} subtitle={lang === 'zh' ? '本月所有偵測到的招標' : 'All tenders detected this month'} />
          <div style={{ display: 'flex', gap: 4, height: 64 }}>
            {[
              { id: 'new', count: TL_TENDER_PIPELINE.new, color: '#141414', label: lang === 'zh' ? '新' : 'New' },
              { id: 'rev', count: TL_TENDER_PIPELINE.reviewing, color: '#6B6B6B', label: lang === 'zh' ? '審視中' : 'Reviewing' },
              { id: 'sub', count: TL_TENDER_PIPELINE.submitted, color: '#FFE003', label: lang === 'zh' ? '已投標' : 'Submitted' },
              { id: 'dec', count: TL_TENDER_PIPELINE.declined, color: '#C8C8C8', label: lang === 'zh' ? '已棄標' : 'Declined' },
            ].map(s => (
              <div key={s.id} style={{
                flex: Math.max(s.count, 0.3), background: s.color,
                color: s.id === 'sub' ? '#141414' : s.id === 'dec' ? '#141414' : '#F8F8F8',
                padding: '12px 14px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
              }}>
                <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.8 }}>{s.label}</div>
                <div style={{ fontFamily: TL_FONTS.serif, fontSize: 24, fontWeight: 500, lineHeight: 1 }}>{s.count}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function deadlineDays(dateStr) {
  const d = new Date(dateStr);
  const today = new Date('2026-04-29');
  return Math.round((d - today) / (1000 * 60 * 60 * 24));
}

window.RTenders = RTenders;
