import { useEffect, useState } from 'react';
import { marketPrices as fallbackPrices } from '@/data/market';
import type { MarketPrice, PriceTrend } from '@/data/market';

const PANEL_API =
  (import.meta as ImportMeta & { env?: Record<string, string> }).env
    ?.VITE_PANEL_API || 'http://localhost:3001';

type ApiPrice = {
  symbol: string;
  name: string;
  value: number | null;
  unit: string | null;
  changeValue: number | null;
  changePct: number | null;
  sourceUrl: string | null;
};

function defaultUnitFor(sourceUrl: string | null): string {
  if (!sourceUrl) return '';
  if (sourceUrl.includes('gold-global')) return 'دلار/اونس';
  if (sourceUrl.includes('basemetal')) return 'دلار/تن';
  return '';
}

function apiToMarketPrices(items: ApiPrice[]): MarketPrice[] {
  return items
    .filter((p) => typeof p.value === 'number' && p.value > 0)
    .map((p): MarketPrice => {
      const pct = p.changePct ?? 0;
      const trend: PriceTrend = pct > 0 ? 'up' : pct < 0 ? 'down' : 'flat';
      return {
        id: p.symbol,
        name: p.name,
        value: p.value as number,
        unit: p.unit || defaultUnitFor(p.sourceUrl),
        change: p.changeValue ?? 0,
        changePercent: pct,
        trend,
      };
    });
}

function formatValue(item: MarketPrice): string {
  return item.value.toLocaleString('fa-IR');
}

function formatChange(item: MarketPrice): string {
  const abs = Math.abs(item.change).toLocaleString('fa-IR');
  return `${abs} (${Math.abs(item.changePercent).toFixed(1)}٪)`;
}

function TickerItem({ item }: { item: MarketPrice }) {
  const changeColor =
    item.trend === 'up'
      ? '#7dbf8a'
      : item.trend === 'down'
      ? '#e07070'
      : 'rgba(255,255,255,0.5)';

  const arrow =
    item.trend === 'up' ? '↑' : item.trend === 'down' ? '↓' : '—';

  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: '10px',
        padding: '0 24px',
        borderRight: '1px solid rgba(255,255,255,0.1)',
        flexShrink: 0,
        height: '40px',
      }}
    >
      <span
        style={{
          color: 'rgba(255,255,255,0.5)',
          fontSize: '11px',
          fontWeight: 400,
        }}
      >
        {item.name}
      </span>
      <span
        style={{
          fontWeight: 700,
          fontSize: '12px',
          color: '#fff',
          fontVariantNumeric: 'tabular-nums',
        }}
      >
        {formatValue(item)}{' '}
        <span style={{ fontSize: '10px', color: 'rgba(255,255,255,0.4)', fontWeight: 400 }}>
          {item.unit}
        </span>
      </span>
      <span
        style={{
          fontSize: '11px',
          fontWeight: 600,
          color: changeColor,
          fontVariantNumeric: 'tabular-nums',
        }}
      >
        {arrow} {formatChange(item)}
      </span>
    </span>
  );
}

export function MarketStrip() {
  const [marketPrices, setMarketPrices] = useState<MarketPrice[]>(fallbackPrices);

  useEffect(() => {
    let cancelled = false;
    const load = () => {
      fetch(`${PANEL_API}/api/prices`)
        .then((r) => (r.ok ? r.json() : null))
        .then((data: ApiPrice[] | null) => {
          if (cancelled || !Array.isArray(data) || data.length === 0) return;
          const mapped = apiToMarketPrices(data);
          if (mapped.length > 0) setMarketPrices(mapped);
        })
        .catch(() => { /* keep fallback */ });
    };
    load();
    const id = setInterval(load, 2 * 60 * 1000);
    return () => { cancelled = true; clearInterval(id); };
  }, []);

  return (
    <div
      dir="ltr"
      style={{
        width: '100%',
        backgroundColor: 'var(--ink)',
        color: 'var(--paper)',
        height: '40px',
        display: 'flex',
        alignItems: 'stretch',
        overflow: 'hidden',
      }}
    >
      {/* Live tag */}
      <div
        style={{
          backgroundColor: 'var(--red)',
          color: 'var(--paper)',
          fontSize: '9px',
          fontWeight: 700,
          letterSpacing: '2.5px',
          textTransform: 'uppercase',
          padding: '0 20px',
          display: 'flex',
          alignItems: 'center',
          flexShrink: 0,
          whiteSpace: 'nowrap',
        }}
      >
        بازار زنده
      </div>

      {/* Ticker area */}
      <div
        style={{
          flex: 1,
          overflow: 'hidden',
          display: 'flex',
          alignItems: 'center',
          position: 'relative',
        }}
      >
        <div
          className="ticker-track"
          style={{
            display: 'flex',
            alignItems: 'center',
            whiteSpace: 'nowrap',
          }}
        >
          {/* Original set */}
          {marketPrices.map((item, i) => (
            <TickerItem key={`a-${i}`} item={item} />
          ))}
          {/* Duplicate for seamless loop */}
          {marketPrices.map((item, i) => (
            <TickerItem key={`b-${i}`} item={item} />
          ))}
        </div>
      </div>
    </div>
  );
}
