File size: 6,095 Bytes
bf4ba2a
 
0feab1a
bf4ba2a
 
 
 
 
 
 
 
0feab1a
bf4ba2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e09ddfb
 
bf4ba2a
 
 
 
e09ddfb
 
bf4ba2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
006e994
bf4ba2a
 
006e994
bf4ba2a
0feab1a
 
 
 
 
bf4ba2a
 
 
0feab1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf4ba2a
 
 
006e994
bf4ba2a
 
 
006e994
 
 
 
 
bf4ba2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0feab1a
bf4ba2a
 
 
 
 
 
 
 
 
006e994
 
 
 
 
0feab1a
 
 
 
 
 
 
 
bf4ba2a
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import React, { useEffect, useState } from 'react'
import { Loader2, TrendingUp, TrendingDown, Minus } from 'lucide-react'
import { fetchBatchPredictions, fetchStockInfo, BatchPredictionItem, StockInfo } from '../api/stockApi'

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface WatchlistEntry {
  code: string
  info: StockInfo | null
  prediction: BatchPredictionItem | null
  error: string | null
}

interface Props {
  onSelect: (code: string) => void
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const DEFAULT_WATCHLIST = ['2330', '2317', '2454', '0050', '006208']

const SIGNAL_EMOJI: Record<string, string> = {
  BUY: '📈',
  SELL: '📉',
  HOLD: '➡️',
}

const SIGNAL_TEXT_CLASS: Record<string, string> = {
  BUY: 'text-red-400',
  SELL: 'text-green-400',
  HOLD: 'text-yellow-400',
}

const BUY_PROB_BG = (prob: number): string => {
  if (prob >= 0.6) return 'bg-red-600'
  if (prob <= 0.35) return 'bg-green-600'
  return 'bg-yellow-600'
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export const WatchlistPanel: React.FC<Props> = ({ onSelect }) => {
  const [entries, setEntries] = useState<WatchlistEntry[]>(
    DEFAULT_WATCHLIST.map((code) => ({ code, info: null, prediction: null, error: null }))
  )
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    let firstLoad = true

    const loadAll = async () => {
      if (firstLoad && !cancelled) setLoading(true)

      // Fetch info and batch predictions in parallel (single batch request instead of 5 individual ones)
      const [infoResults, batchResult] = await Promise.allSettled([
        Promise.allSettled(DEFAULT_WATCHLIST.map((code) => fetchStockInfo(code))),
        fetchBatchPredictions(DEFAULT_WATCHLIST),
      ])

      if (cancelled) return

      const infos = infoResults.status === 'fulfilled' ? infoResults.value : []
      const batchItems = batchResult.status === 'fulfilled' ? batchResult.value : []

      // Build a lookup map from batch results
      const predMap = new Map<string, BatchPredictionItem>()
      for (const item of batchItems) {
        predMap.set(item.code, item)
      }

      const resolved: WatchlistEntry[] = DEFAULT_WATCHLIST.map((code, i) => {
        const infoSettled = infos[i]
        const info = infoSettled?.status === 'fulfilled' ? infoSettled.value : null
        const batchItem = predMap.get(code) ?? null
        return {
          code,
          info,
          prediction: batchItem && !batchItem.error ? batchItem : null,
          error: batchItem?.error ?? null,
        }
      })

      setEntries(resolved)
      setLoading(false)
      firstLoad = false
    }

    loadAll()
    const id = setInterval(loadAll, 30_000)
    return () => {
      cancelled = true
      clearInterval(id)
    }
  }, [])

  return (
    <div className="bg-slate-900 border border-slate-700 rounded-xl p-4 space-y-3">
      <div className="flex items-center gap-2 mb-1">
        <TrendingUp size={16} className="text-blue-400" />
        <h3 className="text-sm font-bold text-slate-200">觀察清單</h3>
        <span className="text-xs text-slate-500 ml-auto">Watchlist</span>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-6 gap-2 text-slate-400">
          <Loader2 size={18} className="animate-spin" />
          <span className="text-sm">載入中...</span>
        </div>
      ) : (
        <ul className="space-y-1.5">
          {entries.map(({ code, info, prediction, error }) => (
            <li key={code}>
              <button
                onClick={() => onSelect(code)}
                className="w-full flex items-center gap-2 rounded-lg px-3 py-2 text-left bg-slate-800/60 hover:bg-slate-700/60 transition-colors group"
              >
                {/* Code + Name */}
                <div className="flex-1 min-w-0">
                  <span className="text-xs font-bold text-slate-100 group-hover:text-white">
                    {code}
                  </span>
                  {info?.name && info.name !== code && (
                    <span className="ml-1.5 text-xs text-slate-400 truncate">
                      {info.name}
                    </span>
                  )}
                </div>

                {/* Signal emoji */}
                {prediction && prediction.signal && !error ? (
                  <>
                    <span
                      className={`text-sm ${SIGNAL_TEXT_CLASS[prediction.signal] ?? 'text-slate-300'}`}
                      title={prediction.signal}
                    >
                      {SIGNAL_EMOJI[prediction.signal] ?? prediction.signal}
                    </span>

                    {/* Buy probability badge */}
                    {prediction.optimized === false ? (
                      <span className="text-[10px] font-semibold text-yellow-200 bg-yellow-700/70 rounded px-1.5 py-0.5">
                        計算中
                      </span>
                    ) : prediction.buy_prob != null && (
                      <span
                        className={`text-xs font-semibold text-white rounded px-1.5 py-0.5 ${BUY_PROB_BG(
                          prediction.buy_prob
                        )}`}
                      >
                        {Math.round(prediction.buy_prob * 100)}%
                      </span>
                    )}
                  </>
                ) : error ? (
                  <span className="text-xs text-red-400"></span>
                ) : (
                  <Loader2 size={12} className="animate-spin text-slate-500" />
                )}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}