'use client';

import type {CSSProperties} from 'react';
import Image from 'next/image';
import {ArrowRight, BarChart3, RefreshCw} from 'lucide-react';
import {SiteFrame, FAQ, useSite} from './site-shell';
import {AssetOrderBook} from './asset-order-book';
import {MarketAssetTrade} from './market-asset-trade';
import {WallexMark} from './wallex-markets';
import {useWallexMarkets} from './use-wallex-markets';
import {useWallexMarketDetail} from './use-wallex-market-detail';
import {formatInvestmentAmount} from '@/lib/investment-amount';
import {wallexAssets, wallexFresh, type WallexSymbol} from '@/lib/wallex';
import {localized, categoryNames, type Catalog} from '@/lib/catalog';

const covers: Record<string, string> = {XAUT: '/images/gold.jpg', USOON: '/images/digital-oil-daylight.png', COPXON: '/images/copper-token.svg'};
const copyByLocale = {
  fa: {market: 'مارکت‌پلیس', quoteMarket: 'بازار تومان', intro: 'اطلاعات این دارایی، قیمت بازار و سفارش‌های خریداران و فروشندگان را در یک صفحه بررسی کنید. برای محاسبه مقدار خرید یا فروش، از پنل معامله استفاده کنید.', price: 'قیمت هر توکن', unit: 'تومان', high: 'بیشترین قیمت ۲۴ ساعت', low: 'کمترین قیمت ۲۴ ساعت', volume: 'حجم معاملات ۲۴ ساعت', value: 'ارزش معاملات ۲۴ ساعت', chart: 'نمودار قیمت', chartHint: 'قیمت پایانی کندل‌های یک‌ساعته · ۲۴ ساعت', loading: 'در حال دریافت نمودار…', noChart: 'نمودار این بازار در دسترس نیست.', updated: 'آخرین دریافت قیمت', missing: 'قیمت به‌روز در دسترس نیست.', refresh: 'به‌روزرسانی اطلاعات بازار', change: 'تغییرات ۲۴ ساعت', chartAlt: 'نمودار قیمت بازار به تومان'},
  en: {market: 'Marketplace', quoteMarket: 'Toman market', intro: 'Review this asset, its market price and the reported buy and sell orders in one place. Use the trading panel to calculate a buy or sell amount.', price: 'Price per token', unit: 'TMN', high: '24-hour high', low: '24-hour low', volume: '24-hour volume', value: '24-hour turnover', chart: 'Price chart', chartHint: 'Hourly closing prices · 24 hours', loading: 'Loading chart…', noChart: 'This market chart is unavailable.', updated: 'Price last received', missing: 'A current price is unavailable.', refresh: 'Refresh market data', change: '24-hour change', chartAlt: 'Market price chart in TMN'},
  ar: {market: 'السوق', quoteMarket: 'سوق التومان', intro: 'راجع معلومات الأصل وسعر السوق وأوامر الشراء والبيع في صفحة واحدة. استخدم لوحة التداول لحساب كمية الشراء أو البيع.', price: 'سعر الرمز', unit: 'تومان', high: 'أعلى سعر خلال ٢٤ ساعة', low: 'أدنى سعر خلال ٢٤ ساعة', volume: 'حجم التداول خلال ٢٤ ساعة', value: 'قيمة التداول خلال ٢٤ ساعة', chart: 'مخطط السعر', chartHint: 'أسعار إغلاق الشموع الساعية · ٢٤ ساعة', loading: 'جارٍ تحميل المخطط…', noChart: 'مخطط السوق غير متاح.', updated: 'آخر تحديث للسعر', missing: 'السعر الحالي غير متاح.', refresh: 'تحديث بيانات السوق', change: 'التغير خلال ٢٤ ساعة', chartAlt: 'مخطط سعر السوق بالتومان'},
};

export function MarketAssetPage({symbol, catalog}: {symbol: WallexSymbol; catalog: Catalog}) {
  return <SiteFrame content={catalog.content} mode={catalog.mode} detail><AssetDetail key={symbol} symbol={symbol} catalog={catalog}/></SiteFrame>;
}

function AssetDetail({symbol, catalog}: {symbol: WallexSymbol; catalog: Catalog}) {
  const {locale, open} = useSite();
  const copy = copyByLocale[locale];
  const asset = wallexAssets.find(item => item.symbol === symbol)!;
  const feed = useWallexMarkets();
  const {detail, loading, now, refresh} = useWallexMarketDetail(symbol);
  const incomingQuote = feed.quotes.find(item => item.symbol === symbol);
  const quote = wallexFresh(incomingQuote, now) ? incomingQuote : undefined;
  const title = locale === 'en' ? asset.description : asset.title;
  const number = (value: string | null | undefined) => value == null ? '—' : formatInvestmentAmount(value, locale);
  const values = detail?.historyAvailable ? detail.candles.map(point => Number(point.close)) : [];
  const low = Math.min(...values), high = Math.max(...values), span = high - low || 1;
  const chart = values.map((value, index) => `${index ? 'L' : 'M'}${index / Math.max(1, values.length - 1) * 600},${high === low ? 90 : 170 - (value - low) / span * 150}`).join(' ');
  const change = quote?.change24h == null ? null : Number(quote.change24h);
  const updated = quote ? new Date(quote.receivedAt) : null;
  const refreshAll = () => {void refresh(); void feed.refresh();};

  return <main id="asset" className="project-page asset-detail-page" dir={locale === 'en' ? 'ltr' : 'rtl'} style={{'--asset-tone': asset.tone} as CSSProperties}>
    <div className="project-breadcrumb"><a href={catalog.mode === 'preview' ? '/market?preview=design' : '/market'}><ArrowRight size={15}/>{copy.market}</a><span>/</span><span>{title}</span></div>
    <div className="project-layout">
      <article className="project-story">
        <div className="project-heading"><span className="small-pill">{localized(categoryNames[asset.key === 'tether' ? 'investment' : 'tangible'], locale)}</span><span dir="ltr" className="project-symbol">{asset.base} <span>•</span> PLANCK</span></div>
        <h1>{title}</h1>
        <p className="project-location">{copy.quoteMarket} <span aria-hidden="true">·</span> <bdi>{asset.base} / TMN</bdi></p>
        <p className="project-intro">{copy.intro}</p>
        <div className={`project-photo asset-detail-photo${covers[asset.base] ? '' : ' asset-detail-illustration'}`}>
          {covers[asset.base] ? <Image src={covers[asset.base]} alt={title} fill sizes="(max-width: 950px) 100vw, 65vw" priority/> : <div className="asset-detail-emblem" style={{'--wallex-tone': asset.tone} as CSSProperties}><i aria-hidden="true"/><i aria-hidden="true"/><WallexMark base={asset.base}/><strong>{asset.base}</strong></div>}
          <span className="image-caption">{asset.description}</span>
        </div>
        <section className="asset-detail-market-data" aria-label={copy.price}>
          <div className="asset-detail-price-row"><div><span>{copy.price}</span><strong><bdi>{number(quote?.price)}</bdi><small>{copy.unit}</small></strong></div><div className={`asset-detail-change ${change == null ? '' : change < 0 ? 'is-negative' : 'is-positive'}`}><span>{copy.change}</span><bdi dir="ltr">{change == null ? '—' : `${change < 0 ? '−' : change > 0 ? '+' : ''}${number(quote?.change24h?.replace(/^-/, ''))}%`}</bdi></div></div>
          <dl className="wallex-facts asset-detail-facts">{[
            [copy.high, quote?.high24h, copy.unit], [copy.low, quote?.low24h, copy.unit],
            [copy.volume, quote?.volume24h, asset.base], [copy.value, quote?.quoteVolume24h, copy.unit],
          ].map(([label, value, unit]) => <div key={label}><dt>{label}</dt><dd><bdi>{number(value)}</bdi> <small>{unit}</small></dd></div>)}</dl>
          <p className="asset-detail-timestamp">{updated ? <>{copy.updated}: <time dateTime={updated.toISOString()}>{updated.toLocaleTimeString(locale === 'fa' ? 'fa-IR' : locale === 'ar' ? 'ar' : 'en-GB')}</time></> : copy.missing}</p>
        </section>
        <section className="asset-detail-chart" aria-labelledby="asset-detail-chart-title">
          <header><div><h2 id="asset-detail-chart-title"><BarChart3 size={20}/>{copy.chart}</h2><p>{copy.chartHint}</p></div><button type="button" aria-label={copy.refresh} title={copy.refresh} disabled={loading || feed.loading} onClick={refreshAll}><RefreshCw size={17}/></button></header>
          {detail?.historyAvailable && values.length > 1 ? <svg viewBox="0 0 600 190" aria-label={copy.chartAlt} preserveAspectRatio="none"><title>{copy.chartAlt}</title><path className="asset-detail-chart-fill" d={`${chart} L600,190 L0,190 Z`}/><path className="asset-detail-chart-line" d={chart} vectorEffect="non-scaling-stroke"/></svg> : <p className="asset-detail-chart-empty" role={loading ? 'status' : undefined}>{loading ? copy.loading : copy.noChart}</p>}
        </section>
      </article>
      <MarketAssetTrade symbol={symbol} quote={quote} now={now} icon={<WallexMark base={asset.base}/>} onLogin={() => open('login')}/>
    </div>
    <AssetOrderBook symbol={asset.base} locale={locale} bids={detail?.bids} asks={detail?.asks} available={detail?.depthAvailable} loading={loading} updatedAt={detail?.receivedAt} onRefresh={() => {void refresh();}}/>
    <FAQ content={catalog.content}/>
  </main>;
}
