'use client';
import {projectCoverImage} from '@/lib/project-cover';
import {useEffect,useId,useState} from 'react';
import {Sun,Building2,Droplets,Smartphone,Shapes,Coins,Triangle,Minus} from 'lucide-react';
import {localized,n,money,type Locale} from '@/lib/catalog';
import {marketHistory} from '@/lib/market';

import {assetQuote,isWallexAsset,type MarketAsset} from '@/lib/market-assets';
import type {WallexDetail,WallexSymbol} from '@/lib/wallex';

export function TokenIcon({project:p}:{project:MarketAsset}) {
 const [failed,setFailed]=useState('');
 const name=(p.slug+' '+p.symbol).toLowerCase();
 const [Icon,tone]=/solar|esol|sun/.test(name)?[Sun,'solar'] as const:/oil/.test(name)?[Droplets,'oil'] as const:/app-store|dapp/.test(name)?[Smartphone,'app'] as const:/nft/.test(name)?[Shapes,'nft'] as const:isWallexAsset(p)?[Coins,'default'] as const:p.category==='tangible'?[Building2,'property'] as const:[Coins,'default'] as const;
 return <span className={`token-icon token-${tone}`} aria-hidden="true">{p.token_icon_url&&failed!==p.token_icon_url?<img src={projectCoverImage(p.token_icon_url)} alt="" onError={()=>setFailed(p.token_icon_url||'')} loading="lazy"/>:<Icon size={24} strokeWidth={1.7}/>}</span>;
}
export function Change24h({project:p,locale,compact=false,amount=false}:{project:MarketAsset;locale:Locale;compact?:boolean;amount?:boolean}) {
 const quote=assetQuote(p);
 const period=locale==='fa'?'۲۴ ساعت':locale==='ar'?'٢٤ ساعة':'24H';
 const unavailable=locale==='fa'?'بدون داده':locale==='ar'?'لا توجد بيانات':'No data';
 return <span className={`token-change change-${quote?.direction||'unavailable'} ${compact?'change-compact':''}`}>
  {!compact&&quote&&(quote.direction==='flat'?<Minus size={12}/>:<Triangle size={10} fill="currentColor" aria-hidden="true"/>)}
  <span dir="ltr">{quote?`${quote.percent>0?'+':quote.percent<0?'−':''}${n(Math.abs(quote.percent),locale)}%`:unavailable}</span>
  {amount&&quote&&quote.deltaRial!==null&&<span className="token-change-amount">({money(Math.abs(quote.deltaRial),locale)} {locale==='fa'?'تومان':locale==='ar'?'تومان':'TMN'})</span>}
  <small>{period}</small>
 </span>;
}
export function TokenHeader({project:p,locale}:{project:MarketAsset;locale:Locale}) {
 return <div className="token-market-header"><TokenIcon project={p}/><div className="token-market-name"><strong dir="ltr">{p.symbol}</strong><span>{localized(p.subtitle,locale)||localized(p.title,locale)}</span></div><div className="token-market-meta"><Change24h project={p} locale={locale}/></div></div>;
}
export function MarketSparkline({project,locale}:{project:MarketAsset;locale:Locale}) {
 const id=useId().replace(/:/g,''),values=isWallexAsset(project)?[]:marketHistory(project),quote=assetQuote(project);
 if(isWallexAsset(project))return <WallexSparkline symbol={project.marketSymbol}/>;
 if(!values.length)return <div className="market-no-chart">{locale==='fa'?'نمودار قیمت در دسترس نیست':locale==='ar'?'مخطط السعر غير متاح':'Price history unavailable'}</div>;
 const low=Math.min(...values),high=Math.max(...values),span=high-low||high*.05||1;
 const coordinates=values.map((value,index)=>`${index/(values.length-1)*400},${high===low?66:110-(value-low)/span*92}`);
 const line='M'+coordinates.join(' L'),area=`${line} L400,128 L0,128 Z`;
 return <svg className={`market-sparkline change-${quote?.direction}`} viewBox="0 0 400 128" preserveAspectRatio="none" role="img" aria-label={locale==='fa'?`نمودار ۲۴ساعته ${project.symbol}${project.is_demo?'، داده نمونه':''}`:`24-hour ${project.symbol} chart${project.is_demo?', sample data':''}`}><defs><linearGradient id={id} x1="0" y1="0" x2="0" y2="1"><stop stopColor="currentColor" stopOpacity=".23"/><stop offset="1" stopColor="currentColor" stopOpacity="0"/></linearGradient></defs><path d={area} fill={`url(#${id})`}/><path d={line} fill="none" stroke="currentColor" strokeWidth="2" vectorEffect="non-scaling-stroke"/></svg>;
}

function WallexSparkline({symbol}:{symbol:WallexSymbol}){
 const [data,setData]=useState<WallexDetail|null>(null),[now,setNow]=useState(Date.now);
 useEffect(()=>{const controller=new AbortController();let pending=false;const load=()=>{if(document.hidden||pending)return;pending=true;fetch(`/api/markets/wallex?symbol=${symbol}`,{cache:'no-store',signal:controller.signal}).then(async r=>{if(!r.ok)throw new Error();const next=await r.json() as WallexDetail;if(next.symbol!==symbol)throw new Error();if(!controller.signal.aborted)setData(next)}).catch(()=>{if(!controller.signal.aborted)setData(null)}).finally(()=>{pending=false})};load();const poll=setInterval(load,60000),clock=setInterval(()=>setNow(Date.now()),10000);document.addEventListener('visibilitychange',load);return()=>{controller.abort();clearInterval(poll);clearInterval(clock);document.removeEventListener('visibilitychange',load)}},[symbol]);
 const values=data&&now-Date.parse(data.receivedAt)<=90000?data.candles.map(c=>Number(c.close)):[];
 if(values.length<2)return <div className="market-no-chart">نمودار قیمت در دسترس نیست</div>;
 const high=Math.max(...values),low=Math.min(...values),span=high-low||1,path=values.map((v,i)=>`${i?'L':'M'}${i/(values.length-1)*400},${high===low?66:110-(v-low)/span*92}`).join(' ');
 return <svg className="market-sparkline" viewBox="0 0 400 128" preserveAspectRatio="none" role="img" aria-label={`نمودار ۲۴ساعته ${symbol}`}><path d={path} fill="none" stroke="currentColor" strokeWidth="2" vectorEffect="non-scaling-stroke"/></svg>;
}
