File size: 9,478 Bytes
24f95f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
'use client';
/**
 * LineChart.tsx β€” Real historical price chart using lightweight-charts v5
 *
 * Fetches from /finance/historical/{symbol} (yfinance β†’ Finnhub β†’ FMP fallback chain)
 * Supports timeframe switching: 1W | 1M | 3M | 6M | 1Y
 * Gracefully degrades to a "no data" state if all sources fail.
 */

import { useEffect, useRef, useState, useCallback } from 'react';
import { getApiBaseUrl } from '@/lib/api';

interface HistoricalPoint {
  date:   string;
  open:   number;
  high:   number;
  low:    number;
  close:  number;
  volume: number;
}

interface Props {
  symbol:      string;
  companyName?: string;
  isPositive?: boolean;
  height?:     number;
}

type Timeframe = '1W' | '1M' | '3M' | '6M' | '1Y';

const TIMEFRAME_DAYS: Record<Timeframe, number> = {
  '1W': 7,
  '1M': 30,
  '3M': 90,
  '6M': 180,
  '1Y': 365,
};

export default function LineChart({ symbol, companyName, isPositive = true, height = 280 }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const chartRef     = useRef<unknown>(null);
  const seriesRef    = useRef<unknown>(null);

  const [allData, setAllData]       = useState<HistoricalPoint[]>([]);
  const [timeframe, setTimeframe]   = useState<Timeframe>('3M');
  const [loading, setLoading]       = useState(true);
  const [error, setError]           = useState<string | null>(null);
  const [currentPrice, setCurrentPrice] = useState<number | null>(null);
  const [priceChange, setPriceChange]   = useState<{ abs: number; pct: number } | null>(null);

  // ── Fetch historical data ──────────────────────────────────────────────
  const fetchData = useCallback(async () => {
    if (!symbol) return;
    setLoading(true);
    setError(null);
    try {
      const apiBase = getApiBaseUrl();
      const ctrl = new AbortController();
      const timer = setTimeout(() => ctrl.abort(), 25_000);
      const res = await fetch(
        `${apiBase}/finance/historical/${symbol.toUpperCase()}?outputsize=full`,
        { signal: ctrl.signal }
      );
      clearTimeout(timer);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      const data: HistoricalPoint[] = json.data ?? [];
      setAllData(data);
      if (data.length > 0) {
        const last  = data[data.length - 1];
        const first = data[data.length - 2] ?? data[0];
        setCurrentPrice(last.close);
        setPriceChange({
          abs: last.close - first.close,
          pct: ((last.close - first.close) / first.close) * 100,
        });
      }
    } catch (e: unknown) {
      const msg = (e as Error).name === 'AbortError'
        ? 'Request timed out'
        : 'Failed to load chart data';
      setError(msg);
    } finally {
      setLoading(false);
    }
  }, [symbol]);

  useEffect(() => { fetchData(); }, [fetchData]);

  // ── Filter by timeframe ────────────────────────────────────────────────
  const filteredData = useCallback((): HistoricalPoint[] => {
    if (!allData.length) return [];
    const days  = TIMEFRAME_DAYS[timeframe];
    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - days);
    const cutoffStr = cutoff.toISOString().split('T')[0];
    return allData.filter(d => d.date >= cutoffStr);
  }, [allData, timeframe]);

  // ── Build/update chart ────────────────────────────────────────────────
  useEffect(() => {
    if (loading || !containerRef.current) return;

    const data = filteredData();

    // Lazy-load lightweight-charts
    import('lightweight-charts').then(({ AreaSeries, LineSeries, LineStyle, createChart }) => {
      // Destroy previous chart
      if (chartRef.current) {
        (chartRef.current as { remove(): void }).remove();
        chartRef.current = null;
        seriesRef.current = null;
      }

      if (!containerRef.current || data.length === 0) return;

      const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

      const chart = createChart(containerRef.current, {
        width:  containerRef.current.clientWidth,
        height,
        layout: {
          background: { color: 'transparent' },
          textColor:  isDark ? '#9ca3af' : '#6b7280',
          fontSize:   11,
        },
        grid: {
          vertLines:  { color: isDark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.04)' },
          horzLines:  { color: isDark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.04)' },
        },
        crosshair: { mode: 1 },
        rightPriceScale: {
          borderColor:    'transparent',
          scaleMargins:   { top: 0.1, bottom: 0.1 },
        },
        timeScale: {
          borderColor:   'transparent',
          timeVisible:   true,
          secondsVisible: false,
        },
        handleScroll: true,
        handleScale:  true,
      });

      const color = isPositive ? '#10b981' : '#ef4444';

      const series = chart.addSeries(LineSeries, {
        color,
        lineWidth:     2,
        crosshairMarkerVisible: true,
        crosshairMarkerRadius:  4,
        lastValueVisible:       true,
        priceLineVisible:       true,
        priceLineStyle:         LineStyle.Dashed,
        priceLineWidth:         1,
        priceLineColor:         color,
      });

      const chartData = data.map(d => ({ time: d.date as string, value: d.close }));
      series.setData(chartData);

      // Area fill
      const areaSeries = chart.addSeries(AreaSeries, {
        topColor:    isPositive ? 'rgba(16,185,129,0.12)' : 'rgba(239,68,68,0.12)',
        bottomColor: 'rgba(0,0,0,0)',
        lineColor:   'transparent',
        lineWidth:   1,
      });
      areaSeries.setData(chartData);

      chart.timeScale().fitContent();

      chartRef.current  = chart;
      seriesRef.current = series;

      // Resize observer
      const ro = new ResizeObserver(() => {
        if (containerRef.current) {
          chart.applyOptions({ width: containerRef.current.clientWidth });
        }
      });
      if (containerRef.current) ro.observe(containerRef.current);
    }).catch(() => {
      setError('Chart library failed to load');
    });

    return () => {
      if (chartRef.current) {
        (chartRef.current as { remove(): void }).remove();
        chartRef.current  = null;
        seriesRef.current = null;
      }
    };
  }, [loading, timeframe, allData, isPositive, height, filteredData]);

  // ── Render ─────────────────────────────────────────────────────────────
  const positiveClass = isPositive ? 'text-emerald-400' : 'text-red-400';

  return (
    <div className="relative w-full">
      {/* Header */}
      <div className="flex items-center justify-between mb-3 px-1">
        <div>
          {currentPrice !== null && (
            <div className="flex items-baseline gap-2">
              <span className="text-xl font-semibold tabular-nums">
                ${currentPrice.toFixed(2)}
              </span>
              {priceChange && (
                <span className={`text-sm ${positiveClass}`}>
                  {priceChange.abs >= 0 ? '+' : ''}{priceChange.abs.toFixed(2)}
                  {' '}({priceChange.pct >= 0 ? '+' : ''}{priceChange.pct.toFixed(2)}%)
                </span>
              )}
            </div>
          )}
        </div>

        {/* Timeframe buttons */}
        <div className="flex gap-1">
          {(Object.keys(TIMEFRAME_DAYS) as Timeframe[]).map(tf => (
            <button
              key={tf}
              onClick={() => setTimeframe(tf)}
              className={`px-2 py-0.5 rounded text-xs font-medium transition-colors
                ${timeframe === tf
                  ? 'bg-white/10 text-white'
                  : 'text-gray-500 hover:text-gray-300'
                }`}
            >
              {tf}
            </button>
          ))}
        </div>
      </div>

      {/* Chart area */}
      <div style={{ height, position: 'relative' }}>
        {loading && (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="flex gap-1">
              {[0,1,2].map(i => (
                <div
                  key={i}
                  className="w-1.5 h-1.5 rounded-full bg-white/30 animate-pulse"
                  style={{ animationDelay: `${i * 150}ms` }}
                />
              ))}
            </div>
          </div>
        )}

        {!loading && error && (
          <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 text-gray-500">
            <span className="text-sm">{error}</span>
            <button
              onClick={fetchData}
              className="text-xs text-blue-400 hover:text-blue-300 underline"
            >
              Retry
            </button>
          </div>
        )}

        {!loading && !error && allData.length === 0 && (
          <div className="absolute inset-0 flex items-center justify-center text-gray-500 text-sm">
            No chart data available for {symbol}
          </div>
        )}

        <div ref={containerRef} className="w-full" style={{ height }} />
      </div>
    </div>
  );
}