// Research module — SKU price monitoring.
// Master/detail layout: SKU list (left) + comparison table + sparkline (right).

const { useState: rpUseState } = React;

function RPrices({ lang }) {
  const [selectedId, setSelectedId] = rpUseState(TL_TRACKED_SKUS[0].id);
  const sku = TL_TRACKED_SKUS.find(s => s.id === selectedId);

  const critical = TL_TRACKED_SKUS.filter(s => s.alert === 'critical').length;
  const warning  = TL_TRACKED_SKUS.filter(s => s.alert === 'warning').length;
  const ok       = TL_TRACKED_SKUS.filter(s => s.alert === 'ok').length;

  return (
    <div style={{ height: '100%', display: 'flex', overflow: 'hidden' }}>
      {/* Left: SKU list */}
      <div style={{ width: 360, borderRight: '1px solid rgba(20,20,20,0.08)', background: '#FAFAFA', overflow: 'auto', flexShrink: 0 }}>
        <div style={{ padding: '20px 20px 14px', borderBottom: '1px solid rgba(20,20,20,0.08)', position: 'sticky', top: 0, background: '#FAFAFA', zIndex: 1 }}>
          <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#A0A0A0' }}>
            {lang === 'zh' ? '追蹤 SKU' : 'Tracked SKUs'}
          </div>
          <h2 style={{ fontFamily: TL_FONTS.serif, fontSize: 22, fontWeight: 500, margin: '4px 0 12px', letterSpacing: '-0.02em' }}>
            {TL_TRACKED_SKUS.length} <span style={{ color: '#A0A0A0' }}>{lang === 'zh' ? '項' : 'items'}</span>
          </h2>
          <div style={{ display: 'flex', gap: 6 }}>
            <RPill tone="critical">{critical} {lang === 'zh' ? '嚴重' : 'crit'}</RPill>
            <RPill tone="warning">{warning} {lang === 'zh' ? '警告' : 'warn'}</RPill>
            <RPill tone="ok">{ok} {lang === 'zh' ? '正常' : 'ok'}</RPill>
          </div>
        </div>

        {TL_TRACKED_SKUS.map(s => {
          const active = s.id === selectedId;
          const diff = s.lowestNonGrey.price - s.ourPrice;
          return (
            <button key={s.id} onClick={() => setSelectedId(s.id)} style={{
              display: 'block', width: '100%', textAlign: 'left',
              padding: '14px 20px', cursor: 'pointer', border: 'none',
              background: active ? '#FFFFFF' : 'transparent',
              borderLeft: active ? '3px solid #141414' : '3px solid transparent',
              borderBottom: '1px solid rgba(20,20,20,0.06)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ fontSize: 24, lineHeight: 1 }}>{s.image}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, color: '#A0A0A0', letterSpacing: '0.08em' }}>{s.sku}</div>
                  <div style={{ fontFamily: TL_FONTS.sans, fontSize: 12.5, color: '#141414', marginTop: 2, fontWeight: active ? 500 : 400, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {lang === 'zh' ? s.nameZh : s.name}
                  </div>
                </div>
                <RDot tone={s.alert} />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontFamily: TL_FONTS.mono, fontSize: 10 }}>
                <span style={{ color: '#141414' }}>{s.ourPriceLabel}</span>
                <span style={{ color: diff < 0 ? '#D81E1E' : diff > 0 ? '#1B5E20' : '#A0A0A0' }}>
                  {diff < 0 ? '↓' : diff > 0 ? '↑' : '='} HK${Math.abs(diff).toLocaleString()}
                </span>
              </div>
            </button>
          );
        })}
      </div>

      {/* Right: detail */}
      <div style={{ flex: 1, overflow: 'auto', padding: '24px 32px 32px' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 8 }}>
          <div style={{ fontSize: 56, lineHeight: 1 }}>{sku.image}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#A0A0A0' }}>
              {sku.sku} · {sku.category}
            </div>
            <h1 style={{ fontFamily: TL_FONTS.serif, fontSize: 30, fontWeight: 500, margin: '4px 0 0', letterSpacing: '-0.02em', lineHeight: 1.1 }}>
              {lang === 'zh' ? sku.nameZh : sku.name}
            </h1>
          </div>
          <button style={{
            padding: '10px 16px', background: '#141414', color: '#F8F8F8', border: 'none',
            fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <TLIcon name="send" size={12} color="#FFE003" />
            {lang === 'zh' ? '通知部門' : 'Alert dept'}
          </button>
          <button style={{
            padding: '10px 16px', 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>
        </div>

        {/* Alert banner */}
        <div style={{
          marginTop: 16, padding: '12px 16px',
          background: sku.alert === 'critical' ? '#141414' : sku.alert === 'warning' ? 'rgba(255,224,3,0.18)' : 'rgba(46,125,50,0.08)',
          color: sku.alert === 'critical' ? '#F8F8F8' : '#141414',
          borderLeft: `3px solid ${sku.alert === 'critical' ? '#FFE003' : sku.alert === 'warning' ? '#E6A800' : '#1B5E20'}`,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <RDot tone={sku.alert} />
          <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: sku.alert === 'critical' ? '#FFE003' : '#6B6B6B' }}>
            {sku.alert === 'critical' ? (lang === 'zh' ? '嚴重訊號' : 'Critical') : sku.alert === 'warning' ? (lang === 'zh' ? '需注意' : 'Watch') : (lang === 'zh' ? '正常' : 'Healthy')}
          </span>
          <span style={{ fontFamily: TL_FONTS.sans, fontSize: 13 }}>
            {lang === 'zh' ? sku.alertReasonZh : sku.alertReason}
          </span>
        </div>

        {/* Price breakdown */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 20, marginTop: 24 }}>
          <div>
            <RSectionHead no="01" title={lang === 'zh' ? '渠道比價' : 'Channel comparison'} subtitle={lang === 'zh' ? '今早 09:14 抓取' : 'Crawled today 09:14'} />
            <div style={{ background: '#FFFFFF' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: TL_FONTS.sans, fontSize: 12.5 }}>
                <thead>
                  <tr style={{ borderBottom: '1px solid rgba(20,20,20,0.12)' }}>
                    <th style={{ textAlign: 'left', padding: '8px 0', fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#A0A0A0', fontWeight: 400 }}>{lang === 'zh' ? '渠道' : 'Channel'}</th>
                    <th style={{ textAlign: 'right', padding: '8px 0', fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#A0A0A0', fontWeight: 400 }}>{lang === 'zh' ? '價格' : 'Price'}</th>
                    <th style={{ textAlign: 'right', padding: '8px 0', fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#A0A0A0', fontWeight: 400 }}>{lang === 'zh' ? '差距' : 'Δ vs ours'}</th>
                  </tr>
                </thead>
                <tbody>
                  {sku.competitors.map((c, i) => (
                    <tr key={i} style={{ borderBottom: '1px solid rgba(20,20,20,0.06)', background: c.ours ? '#FFE003' : 'transparent' }}>
                      <td style={{ padding: '12px 0' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          {c.ours && <RPill tone="critical">{lang === 'zh' ? '我方' : 'OURS'}</RPill>}
                          {c.grey && <RPill tone="grey">{lang === 'zh' ? '水貨' : 'GREY'}</RPill>}
                          <div>
                            <div style={{ color: '#141414', fontWeight: c.ours ? 500 : 400 }}>{c.site}</div>
                            <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, color: c.ours ? '#5A4A00' : '#A0A0A0' }}>{c.url}</div>
                          </div>
                        </div>
                      </td>
                      <td style={{ textAlign: 'right', padding: '12px 0', fontFamily: TL_FONTS.mono, fontSize: 13, color: '#141414', fontWeight: c.ours ? 600 : 400 }}>
                        HK${c.price.toLocaleString()}
                      </td>
                      <td style={{ textAlign: 'right', padding: '12px 0', fontFamily: TL_FONTS.mono, fontSize: 11 }}>
                        {c.ours ? <span style={{ color: '#5A4A00' }}>—</span> :
                          c.delta < 0 ? <span style={{ color: '#D81E1E', fontWeight: 500 }}>−HK${Math.abs(c.delta).toLocaleString()}</span> :
                          c.delta > 0 ? <span style={{ color: '#1B5E20' }}>+HK${c.delta.toLocaleString()}</span> :
                          <span style={{ color: '#A0A0A0' }}>= HK$0</span>}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          <div>
            <RSectionHead no="02" title={lang === 'zh' ? '12 週走勢' : '12-week trend'} subtitle={lang === 'zh' ? '我方 vs 最低競爭對手' : 'Ours vs lowest competitor'} />
            <div style={{ padding: 20, background: '#F8F8F8', border: '1px solid rgba(20,20,20,0.08)' }}>
              <PriceTrendChart ours={sku.history} comp={sku.competitorHistory} ourPrice={sku.ourPrice} compName={sku.lowestNonGrey.site} lang={lang} />
            </div>

            <div style={{ marginTop: 16, padding: '14px 16px', background: '#141414', color: '#F8F8F8' }}>
              <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.16em', color: '#FFE003' }}>
                {lang === 'zh' ? 'AI 建議' : 'AI RECOMMENDATION'}
              </div>
              <div style={{ fontFamily: TL_FONTS.serif, fontSize: 14, fontStyle: 'italic', marginTop: 6, lineHeight: 1.45 }}>
                {sku.alert === 'critical'
                  ? (lang === 'zh' ? '建議價格匹配或減 HK$200。本月已有兩個競爭對手降價。' : 'Match price or undercut by HK$200. Two competitors have dropped this month.')
                  : sku.alert === 'warning'
                  ? (lang === 'zh' ? '保持監察。HKTVMall 屬數位渠道，本店仍具服務優勢。' : 'Monitor only. HKTVMall is digital — our service margin holds.')
                  : (lang === 'zh' ? '無需行動。我方為市場最低。' : 'Hold. We are the local market floor.')}
              </div>
            </div>
          </div>
        </div>

        {/* Recent alerts log */}
        <div style={{ marginTop: 28 }}>
          <RSectionHead no="03" title={lang === 'zh' ? '近期警報記錄' : 'Recent alerts log'} subtitle={lang === 'zh' ? '可匯出 CSV / Excel' : 'Exportable to CSV / Excel'} right={
            <div style={{ display: 'flex', gap: 8 }}>
              <button style={{ padding: '6px 12px', border: '1px solid rgba(20,20,20,0.2)', background: 'transparent', fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer' }}>CSV</button>
              <button style={{ padding: '6px 12px', border: '1px solid rgba(20,20,20,0.2)', background: 'transparent', fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer' }}>XLSX</button>
            </div>
          } />
          <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: TL_FONTS.sans, fontSize: 12 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid rgba(20,20,20,0.12)' }}>
                {[lang==='zh'?'時間':'Time', 'SKU', lang==='zh'?'訊息':'Message', lang==='zh'?'部門':'Department', lang==='zh'?'狀態':'Status'].map((h,i) => (
                  <th key={i} style={{ textAlign: 'left', padding: '8px 12px 8px 0', fontFamily: TL_FONTS.mono, fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#A0A0A0', fontWeight: 400 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {TL_PRICE_ALERTS_LOG.map(a => (
                <tr key={a.id} style={{ borderBottom: '1px solid rgba(20,20,20,0.06)' }}>
                  <td style={{ padding: '10px 12px 10px 0', fontFamily: TL_FONTS.mono, fontSize: 10.5, color: '#6B6B6B' }}>{a.ts}</td>
                  <td style={{ padding: '10px 12px 10px 0', fontFamily: TL_FONTS.mono, fontSize: 10.5, color: '#141414' }}>{a.sku}</td>
                  <td style={{ padding: '10px 12px 10px 0', color: '#141414' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                      <RDot tone={a.severity} /> {a.msg}
                    </span>
                  </td>
                  <td style={{ padding: '10px 12px 10px 0', color: '#6B6B6B' }}>{a.dept}</td>
                  <td style={{ padding: '10px 12px 10px 0' }}>
                    <RPill tone={a.ack ? 'ok' : a.severity}>
                      {a.ack ? (lang === 'zh' ? '已確認' : 'Acknowledged') : (lang === 'zh' ? '待處理' : 'Pending')}
                    </RPill>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Sources */}
        <div style={{ marginTop: 28 }}>
          <RSectionHead no="04" title={lang === 'zh' ? '抓取來源' : 'Crawl sources'} subtitle={lang === 'zh' ? '12 個渠道 · 點擊切換' : '12 channels · click to toggle'} />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {TL_PRICE_SOURCES.map(s => (
              <div key={s.id} style={{
                padding: '12px 14px', background: s.enabled ? '#FFFFFF' : '#FAFAFA',
                border: '1px solid rgba(20,20,20,0.08)',
                opacity: s.enabled ? 1 : 0.5,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                  <RDot tone={s.status === 'ok' ? 'ok' : s.status === 'grey' ? 'neutral' : 'neutral'} />
                  <span style={{ fontFamily: TL_FONTS.sans, fontSize: 12, color: '#141414', fontWeight: 500, flex: 1 }}>{s.name}</span>
                  <RPill tone="grey">{s.region}</RPill>
                </div>
                <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9.5, color: '#A0A0A0' }}>{s.domain}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontFamily: TL_FONTS.mono, fontSize: 9.5, color: '#6B6B6B' }}>
                  <span>{s.skus} {lang === 'zh' ? 'SKU' : 'SKUs'}</span>
                  <span>{lang === 'zh' ? '上次' : 'Last'} {s.lastRun}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function PriceTrendChart({ ours, comp, ourPrice, compName, lang }) {
  const w = 360, h = 140;
  const all = [...ours, ...comp];
  const max = Math.max(...all);
  const min = Math.min(...all);
  const range = max - min || 1;
  const pad = range * 0.1;
  const ymax = max + pad, ymin = min - pad, yr = ymax - ymin;
  const xs = (i, len) => (i / (len-1)) * w;
  const ys = v => h - ((v - ymin) / yr) * h;
  const pathOf = arr => arr.map((v, i) => (i ? 'L' : 'M') + xs(i, arr.length).toFixed(1) + ',' + ys(v).toFixed(1)).join(' ');
  return (
    <div>
      <svg width={w} height={h + 20} style={{ display: 'block', overflow: 'visible' }}>
        <line x1="0" y1={h} x2={w} y2={h} stroke="rgba(20,20,20,0.1)" strokeWidth="1" />
        <path d={pathOf(comp)} stroke="#A0A0A0" strokeWidth="1.5" fill="none" strokeDasharray="3 3" />
        <path d={pathOf(ours)} stroke="#141414" strokeWidth="2" fill="none" />
        <circle cx={xs(ours.length-1, ours.length)} cy={ys(ours[ours.length-1])} r="3.5" fill="#FFE003" stroke="#141414" strokeWidth="1.5" />
        <circle cx={xs(comp.length-1, comp.length)} cy={ys(comp[comp.length-1])} r="3" fill="#A0A0A0" />
      </svg>
      <div style={{ display: 'flex', gap: 16, marginTop: 8, fontFamily: TL_FONTS.mono, fontSize: 10 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 14, height: 2, background: '#141414' }} />
          <span style={{ color: '#141414' }}>{lang === 'zh' ? '我方' : 'Ours'}</span>
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 14, height: 0, borderTop: '2px dashed #A0A0A0' }} />
          <span style={{ color: '#6B6B6B' }}>{compName}</span>
        </span>
      </div>
    </div>
  );
}

window.RPrices = RPrices;
