'use client';
import Link from 'next/link';
import {useEffect,useMemo,useRef,useState,type CSSProperties} from 'react';
import {ArrowUpLeft,ArrowUpRight,Check,ChevronDown,Clock3,Layers3,Shield,SlidersHorizontal,Sparkles,TrendingUp,Wallet,Users,Link2,LockKeyhole} from 'lucide-react';
import {WallexMark} from './wallex-markets';
import {useWallexMarkets} from './use-wallex-markets';
import {useExchangeRate} from './use-exchange-rate';
import {wallexAssets} from '@/lib/wallex';
import {buildUnifiedInvestmentPlan} from '@/lib/unified-investment';
import {Select,SelectContent,SelectItem,SelectTrigger,SelectValue} from './ui/select';
import {RadioGroup,RadioGroupItem} from './ui/radio-group';
import {Checkbox} from './ui/checkbox';
import {TokenIcon} from './token-market';
import {Collapsible,CollapsibleTrigger,CollapsibleContent} from './ui/collapsible';
import {Tabs,TabsList,TabsTrigger,TabsContent} from './ui/tabs';
import {InvestmentAmountInput} from './investment-amount-input';
import {formatInvestmentAmount,investmentAvailableAmount,investmentAmountPercent,percentageAmount} from '@/lib/investment-amount';
import {useSite} from './site-shell';
import {localized,n,type Catalog} from '@/lib/catalog';
import {projectHref} from '@/lib/market';
import {investableProject,planBudget,riskPresets,type PlanCurrency,type RiskPreference,type AllocationStyle} from '@/lib/smart-investment';
const colors=['#75dcc6','#8dacf7','#bba2ed','#ebc286','#e593a4','#7aaebb'];
const periods=[6,12,24,36];

export function SmartInvestment({catalog,reducedMotion=false}:{catalog:Catalog;reducedMotion?:boolean}){
 const {locale,user,sessionStatus,customer,open}=useSite();
 const say=(fa:string,en:string,ar:string)=>locale==='en'?en:locale==='ar'?ar:fa;
 const projects=useMemo(()=>catalog.projects.filter(investableProject),[catalog.projects]);
 const allAssetIds=useMemo(()=>[...projects.map(p=>p.id),...wallexAssets.map(asset=>asset.symbol)],[projects]);
 const [amount,setAmount]=useState(''),[currency,setCurrency]=useState<PlanCurrency>('TMN'),[months,setMonths]=useState(24),[risk,setRisk]=useState<RiskPreference>('balanced'),[style,setStyle]=useState<AllocationStyle>('diversified'),[selected,setSelected]=useState<string[]>(()=>allAssetIds);
 const [expanded,setExpanded]=useState(false),[copyExpanded,setCopyExpanded]=useState(false);
 const wallex=useWallexMarkets();
 const exchange=useExchangeRate(),rate=exchange.rate;
 const knownAssets=useRef(new Set(allAssetIds));
 useEffect(()=>{const added=allAssetIds.filter(id=>!knownAssets.current.has(id));knownAssets.current=new Set(allAssetIds);setSelected(current=>[...current.filter(id=>allAssetIds.includes(id)),...added])},[allAssetIds]);
 const balanceAmountOwner=useRef<string|null>(null);
 useEffect(()=>{if(balanceAmountOwner.current&&balanceAmountOwner.current!==user?.id){setAmount('');balanceAmountOwner.current=null}},[user?.id]);
 const available=useMemo(()=>user&&sessionStatus==='ready'&&customer.status==='ready'&&customer.data?investmentAvailableAmount(customer.data.positions,currency):null,[user,sessionStatus,customer.status,customer.data,currency]);
 const hasAvailable=available!==null&&/[1-9]/.test(available);
 const walletPercent=available?investmentAmountPercent(amount,available,currency):0;
 const walletLoading=sessionStatus==='loading'||(!!user&&customer.status==='loading');
 function editAmount(value:string){balanceAmountOwner.current=null;setAmount(value)}
 function choosePercent(percent:number){if(!hasAvailable||available===null||!user)return;balanceAmountOwner.current=user.id;setAmount(percentageAmount(available,percent,currency));setFocusedToken(null)}
 const [focusedToken,setFocusedToken]=useState<string|null>(null);
 const plan=useMemo(()=>buildUnifiedInvestmentPlan(catalog.projects,wallex.quotes,{amount,currency,usdtRate:rate,months,risk,style,projectIds:selected}),[wallex.quotes,catalog.projects,amount,currency,rate,months,risk,style,selected]);
 const currencyLabels={TMN:say('تومان','Toman','تومان'),IRR:say('ریال','Rial','ريال'),USDT:say('تتر · USDT','Tether · USDT','تيثر · USDT')};
 const riskLabels={cautious:say('محتاط','Cautious','حذر'),balanced:say('متعادل','Balanced','متوازن'),adventurous:say('جسور','Adventurous','جريء')};
 const policy=riskPresets[risk];
 const inCurrency=(rial:number)=>currency==='TMN'?rial/10:currency==='IRR'?rial:rate&&planBudget('1','USDT',rate).rial?rial/Number(planBudget('1','USDT',rate).rial):0;
 const formatted=(rial:number)=>new Intl.NumberFormat(locale==='fa'?'fa-IR':locale,{maximumFractionDigits:currency==='IRR'?0:currency==='TMN'?1:2}).format(inCurrency(rial));
 const unit=currency==='USDT'?'USDT':currencyLabels[currency];
 const monthLabel=say('ماه','months','أشهر');
 const error=amount&&plan.error?({amount:say('مبلغ معتبر و بیشتر از صفر وارد کنید.','Enter an amount greater than zero.','أدخل مبلغاً صحيحاً أكبر من صفر.'),rate:say('نرخ تبدیل دریافت نشد؛ تازه‌سازی کنید یا تومان را انتخاب کنید.','The conversion rate is unavailable. Refresh or select toman.','سعر تيثر غير متاح. حدّث البيانات أو اختر تومان.'),range:say('مبلغ خارج از محدوده محاسبه است.','The amount is outside the supported range.','المبلغ خارج النطاق المدعوم.'),selection:say('حداقل یک توکن انتخاب کنید.','Select at least one token.','اختر رمزاً واحداً على الأقل.'),settings:say('تنظیمات سبد را بررسی کنید.','Check the portfolio settings.','تحقق من إعدادات المحفظة.')}[plan.error]):'';
 const illustrative=plan.allocations.some(a=>!('wallex' in a.project)&&(catalog.mode==='preview'||a.project.is_demo));
 const marketUnavailable=catalog.mode==='unavailable'&&wallex.unavailable;
 const investedPercent=(1000-plan.cashShareTenths)/10;
 const selectedRow=plan.allocations.find(a=>a.project.id===focusedToken);
 let offset=0;
 const segments=[...plan.allocations.map((a,i)=>({key:a.project.id,share:a.shareTenths,color:colors[i%colors.length],label:a.project.symbol})),{key:'cash',share:plan.cashShareTenths,color:'var(--sp-cash)',label:say('مانده نقدی','Unallocated cash','رصيد نقدي')}].filter(s=>s.share>0).map(s=>{const start=offset;offset+=s.share/10;return {...s,start}});
 function changeCurrency(next:PlanCurrency){
  const current=planBudget(amount,currency,rate);
  if(next!==currency&&current.rial!==null){if(next==='TMN')setAmount(`${current.rial/BigInt(10)}${current.rial%BigInt(10)?'.'+current.rial%BigInt(10):''}`);else if(next==='IRR')setAmount(current.rial.toString());else{const exchange=planBudget('1','USDT',rate);if(exchange.rial){const micros=current.rial*BigInt(1_000_000)/exchange.rial;setAmount(`${micros/BigInt(1_000_000)}.${(micros%BigInt(1_000_000)).toString().padStart(6,'0')}`.replace(/\.?0+$/,''))}else setAmount('')}}
  setCurrency(next);
 }
 function toggle(id:string,checked:boolean){setSelected(ids=>checked?[...new Set([...ids,id])]:ids.filter(x=>x!==id));setFocusedToken(null)}
 const active=plan.allocations.length>0&&!error&&!marketUnavailable;
 return <section id="smart-investment" className="smart-investment" data-reduced-motion={reducedMotion||undefined} aria-labelledby="smart-investment-title">
  <header className="sp-heading"><div><div className="sp-kicker"><span>۰۲</span><Sparkles size={14}/>{say('سرمایه‌گذاری هوشمند','SMART INVESTING','الاستثمار الذكي')}</div><h2 id="smart-investment-title">{say('سرمایهٔ شما،','Your capital,','رأس مالك،')} <span>{say('با چیدمان شما.','your composition.','بتوزيعك.')}</span></h2></div><p>{say('از یک عدد شروع کنید. به یک ترکیب هدفمند برسید.','Start with a number. Shape a considered portfolio.','ابدأ برقم. وصمّم محفظة مدروسة.')}</p></header>
  <Tabs defaultValue="allocation" className="sp-investment-tabs">
   <TabsList className="sp-mode-tabs" aria-label={say('روش سرمایه‌گذاری','Investment approach','طريقة الاستثمار')}>
    <TabsTrigger value="allocation"><Sparkles size={18}/>{say('چیدمان هوشمند سبد','Smart allocation','التوزيع الذكي')}</TabsTrigger>
    <TabsTrigger value="copy"><Users size={18}/>{say('کپی‌تریدرهای برتر','Top copy traders','أفضل متداولي النسخ')}</TabsTrigger>
   </TabsList>
   <TabsContent value="allocation">
    <Collapsible open={expanded} onOpenChange={setExpanded} className="sp-disclosure">
     <div className="sp-entry">
      <div className="sp-entry-label"><span className="sp-entry-icon" aria-hidden="true"><Wallet size={23}/></span><label htmlFor="sp-amount">{say('میزان سرمایه','Investment amount','مبلغ الاستثمار')}<small>{say('از همین‌جا شروع کنید','Start right here','ابدأ من هنا')}</small></label></div>
      <div className="sp-entry-input" onFocusCapture={()=>setExpanded(true)}><InvestmentAmountInput amount={amount} onAmountChange={editAmount} locale={locale} invalid={!!error&&['amount','range'].includes(plan.error||'')} description={expanded&&error?'sp-error':undefined}/><span className="sp-entry-unit">{unit}</span></div>
      <CollapsibleTrigger className="sp-expand-button"><span>{expanded?say('بستن تنظیمات','Collapse settings','طيّ الإعدادات'):say('تنظیم سبد من','Set up my portfolio','إعداد محفظتي')}</span><ChevronDown size={18}/></CollapsibleTrigger>
     </div>
     <CollapsibleContent className="sp-disclosure-panel">
  <div className="sp-workbench">
   <div className="sp-controls">
    <div className="sp-panel-heading"><span><SlidersHorizontal size={17}/>{say('مسیر سرمایه‌گذاری شما','Your investment preferences','تفضيلات استثمارك')}</span><span className="sp-step">PLANCK / SMART</span></div>
    <div className="sp-field sp-currency"><label id="sp-currency-label">{say('ارز مبنا','Currency','العملة')}</label><Select value={currency} onValueChange={value=>{if(value)changeCurrency(value as PlanCurrency)}}><SelectTrigger aria-labelledby="sp-currency-label" className="sp-select"><SelectValue>{currencyLabels[currency]}</SelectValue></SelectTrigger><SelectContent className="sp-select-menu">{Object.entries(currencyLabels).map(([value,label])=><SelectItem key={value} value={value}>{label}</SelectItem>)}</SelectContent></Select></div>
    <div className="sp-wallet-budget">
     <div className="sp-wallet-balance"><span><Wallet size={15}/>{say('موجودی قابل‌استفاده','Available balance','الرصيد المتاح')}</span><strong dir="ltr">{walletLoading?'…':available===null?'—':customer.data?.preferences?.hide_balances?'••••••':formatInvestmentAmount(available,locale)} <small>{unit}</small></strong></div>
     <div className="sp-percent-heading"><label htmlFor="sp-budget-percent">{say('سهمی از موجودی شما','Share of your balance','نسبة من رصيدك')}</label><button type="button" disabled={!hasAvailable} onClick={()=>choosePercent(100)}>{say('همه موجودی','All balance','كامل الرصيد')}</button></div>
     <fieldset className="sp-percent-options" aria-label={say('انتخاب درصد موجودی','Choose balance percentage','اختر نسبة الرصيد')}>{[10,25,75,100].map(percent=><button key={percent} type="button" disabled={!hasAvailable} aria-pressed={hasAvailable&&available!==null&&amount===percentageAmount(available,percent,currency)} onClick={()=>choosePercent(percent)}>{n(percent,locale)}٪</button>)}</fieldset>
     <div className="sp-budget-slider" style={{'--sp-budget-percent':`${walletPercent}%`} as CSSProperties}><input id="sp-budget-percent" type="range" min="0" max="100" step="1" value={walletPercent} onChange={event=>choosePercent(Number(event.target.value))} disabled={!hasAvailable} dir="ltr" aria-valuetext={say(`${n(walletPercent,locale)} درصد از موجودی`,`${walletPercent}% of available balance`,`${n(walletPercent,locale)} بالمئة من الرصيد`)} aria-describedby="sp-balance-note"/><div className="sp-slider-scale"><span>{n(0,locale)}٪</span><output htmlFor="sp-budget-percent">{n(walletPercent,locale)}٪</output><span>{n(100,locale)}٪</span></div></div>
     <p id="sp-balance-note" className="sp-balance-note">{walletLoading?say('در حال دریافت موجودی…','Loading your balance…','جارٍ تحميل الرصيد…'):sessionStatus==='error'?say('دریافت حساب انجام نشد؛ مبلغ دلخواه را وارد کنید.','Account unavailable; enter an amount manually.','تعذّر تحميل الحساب؛ أدخل المبلغ يدوياً.'):!user?<>{say('برای استفاده از موجودی، وارد حساب شوید.','Sign in to use your balance.','سجّل الدخول لاستخدام رصيدك.')} <button type="button" onClick={()=>open('login')}>{say('ورود','Sign in','دخول')}</button></>:customer.status==='error'?<>{say('موجودی دریافت نشد.','Balance unavailable.','تعذّر تحميل الرصيد.')} <button type="button" onClick={()=>void customer.reload()}>{say('تلاش دوباره','Retry','أعد المحاولة')}</button></>:available===null?say('موجودی این ارز در دسترس نیست؛ مبلغ دلخواه را وارد کنید.','Balance for this currency is unavailable; enter an amount manually.','رصيد هذه العملة غير متاح؛ أدخل مبلغاً يدوياً.'):!hasAvailable?say('موجودی قابل‌استفاده ندارید؛ می‌توانید مبلغ دلخواه وارد کنید.','No available balance; you can still enter an amount.','لا يوجد رصيد متاح؛ يمكنك إدخال مبلغ يدوياً.'):say('درصدها از موجودی آزاد همین ارز محاسبه می‌شوند.','Percentages use this currency’s available balance.','تُحسب النسب من الرصيد المتاح لهذه العملة.')}</p>
    </div>
    {currency==='USDT'&&<div className="sp-exchange"><label>{say('نرخ هر تتر','Toman per USDT','سعر تيثر')}</label><div className="wallex-rate-value"><strong>{rate?formatInvestmentAmount(rate,locale):'—'}</strong><small>{say('تومان','TMN','تومان')}</small></div><small>{exchange.loading?say('در حال دریافت نرخ…','Loading rate…','جارٍ تحميل السعر…'):rate?say('با تازه‌شدن نرخ تبدیل، برآورد به‌روز می‌شود.','Estimates update with the conversion rate.','يتم تحديث التقدير مع سعر التحويل.'):say('نرخ در دسترس نیست.','Rate unavailable.','السعر غير متاح.')} <button type="button" disabled={exchange.loading} onClick={()=>void exchange.refresh()}>{say('تازه‌سازی','Refresh','تحديث')}</button></small></div>}
    <fieldset className="sp-fieldset"><legend><Clock3 size={15}/>{say('افق سرمایه‌گذاری','Investment horizon','أفق الاستثمار')}</legend><RadioGroup className="sp-periods" value={months} onValueChange={value=>setMonths(Number(value))} aria-label={say('مدت سرمایه‌گذاری','Investment horizon','مدة الاستثمار')}>{periods.map(period=><label key={period}><RadioGroupItem value={period} aria-label={`${n(period,locale)} ${monthLabel}`}/><span aria-hidden="true">{n(period,locale)} <small>{monthLabel}</small></span></label>)}</RadioGroup></fieldset>
    <fieldset className="sp-fieldset"><legend><Shield size={15}/>{say('ریسک‌پذیری شما','Your risk tolerance','قدرتك على تحمّل المخاطر')}</legend><RadioGroup className="sp-risk-options" value={risk} onValueChange={value=>setRisk(value as RiskPreference)} aria-label={say('ریسک‌پذیری','Risk tolerance','تحمّل المخاطر')}>{(['cautious','balanced','adventurous'] as const).map((key,i)=>{const Icon=[Shield,Layers3,TrendingUp][i];return <label key={key}><RadioGroupItem value={key} aria-label={riskLabels[key]}/><Icon size={16} aria-hidden="true"/><span aria-hidden="true">{riskLabels[key]}</span></label>})}</RadioGroup><p className="sp-control-hint">{say('ذخیره نقدی هدف','Target cash reserve','الاحتياطي النقدي المستهدف')} {n(policy.reservePercent,locale)}٪ <span>·</span> {say('حداکثر سهم هر توکن','Max. per token','الحد الأقصى لكل رمز')} {n(policy.maxTokenPercent,locale)}٪</p></fieldset>
    <fieldset className="sp-fieldset sp-token-fieldset"><legend>{say('دارایی‌های مورد علاقه','Preferred assets','الأصول المفضلة')}<button type="button" onClick={()=>{setSelected(allAssetIds.every(id=>selected.includes(id))?[]:allAssetIds);setFocusedToken(null)}}>{allAssetIds.every(id=>selected.includes(id))?say('پاک کردن انتخاب','Clear selection','مسح الاختيار'):say('انتخاب همه','Select all','اختيار الكل')}</button></legend><div className="sp-token-options">{projects.map(project=><label key={project.id} title={localized(project.title,locale)}><Checkbox checked={selected.includes(project.id)} onCheckedChange={checked=>toggle(project.id,!!checked)} aria-label={`${say('انتخاب','Select','اختيار')} ${project.symbol}`}/><span dir="ltr" aria-hidden="true">{project.symbol}</span></label>)}{wallexAssets.map(asset=><label key={asset.symbol} title={asset.title}><Checkbox checked={selected.includes(asset.symbol)} onCheckedChange={checked=>toggle(asset.symbol,!!checked)} aria-label={`${say('انتخاب','Select','اختيار')} ${asset.title}`}/><span dir="ltr" aria-hidden="true">{asset.base}</span></label>)}</div><p className="sp-control-hint">{wallex.loading?say('در حال به‌روزرسانی قیمت دارایی‌ها…','Refreshing asset prices…','جارٍ تحديث أسعار الأصول…'):wallex.unavailable?say('قیمت بعضی دارایی‌ها دریافت نشد؛ فقط دارایی‌های دارای اطلاعات معتبر در سبد قرار می‌گیرند.','Some quotes are unavailable; only assets with valid data are allocated.','بعض الأسعار غير متاحة؛ تُوزع المحفظة على الأصول ذات البيانات الصالحة فقط.'):say('همه انتخاب‌ها در یک سبد چیده می‌شوند؛ قیمت دارایی‌های بازار به‌روز می‌شود.','All selected assets share one portfolio with up-to-date market quotes.','تُجمع الأصول المختارة في محفظة واحدة مع أسعار السوق الحديثة.')} <button type="button" disabled={wallex.loading} onClick={()=>void wallex.refresh()}>{say('تازه‌سازی','Refresh','تحديث')}</button></p></fieldset>
    <div className="sp-style-row"><label id="sp-style-label">{say('اولویت چیدمان','Allocation priority','أولوية التوزيع')}</label><Select value={style} onValueChange={value=>{if(value)setStyle(value as AllocationStyle)}}><SelectTrigger className="sp-style-select" aria-labelledby="sp-style-label"><SelectValue>{style==='diversified'?say('توزیع متوازن','Balanced allocation','توزيع متوازن'):say('تناسب با مدت انتخابی','Match the horizon','ملاءمة المدة')}</SelectValue></SelectTrigger><SelectContent className="sp-select-menu"><SelectItem value="diversified">{say('توزیع متوازن','Balanced allocation','توزيع متوازن')}</SelectItem><SelectItem value="duration">{say('تناسب با مدت انتخابی','Match the horizon','ملاءمة المدة')}</SelectItem></SelectContent></Select></div>
    <div className="sp-live-note"><Sparkles size={14}/>{say('با هر انتخاب، سبد شما دوباره چیده می‌شود.','Your portfolio updates with every choice.','يتجدد توزيع محفظتك مع كل اختيار.')}</div>
   </div>
   <div className="sp-result" aria-label={say('سبد پیشنهادی','Suggested portfolio','المحفظة المقترحة')}>
    <div className="sp-panel-heading"><span>{say('پیشنهاد برای شما','Your suggested mix','التوزيع المقترح لك')}</span><span className="sp-result-badge">{illustrative?say('چیدمان نمونه','Illustrative mix','توزيع توضيحي'):say('برآورد اولیه','Initial estimate','تقدير أولي')}</span></div>
    <div className="sp-result-content">
    {!amount||error||marketUnavailable?<div className="sp-empty" aria-live="polite"><Wallet size={30}/><h3>{say('از انتخاب‌های شما شروع می‌کنیم','Let’s start with your choices','لنبدأ باختياراتك')}</h3><p id="sp-error">{marketUnavailable?say('اطلاعات بازار دریافت نشد. کمی بعد دوباره تلاش کنید.','Project data is unavailable. Please try again later.','بيانات المشاريع غير متاحة. حاول لاحقاً.'):!amount?say('مبلغ سرمایه را وارد کنید یا درصدی از موجودی خود انتخاب کنید.','Enter an amount or select a percentage of your balance.','أدخل مبلغاً أو اختر نسبة من رصيدك.'):error}</p></div>:<>
     <div className="sp-overview"><div className="sp-donut"><svg viewBox="0 0 160 160" aria-hidden="true"><circle cx="80" cy="80" r="64" fill="none" stroke="var(--sp-cash)" strokeWidth="13"/>{segments.map(s=><circle key={s.key} cx="80" cy="80" r="64" pathLength="100" fill="none" stroke={s.color} strokeWidth={focusedToken===s.key?'17':'13'} strokeDasharray={`${Math.max(0,s.share/10-.9)} 100`} strokeDashoffset={-s.start} transform="rotate(-90 80 80)" className="sp-chart-segment" opacity={focusedToken&&focusedToken!==s.key?'.35':'1'}/>)}</svg><div className="sp-donut-center"><strong>{n(selectedRow?selectedRow.shareTenths/10:investedPercent,locale)}<small>٪</small></strong><span>{selectedRow?selectedRow.project.symbol:say('تخصیص به توکن','in tokens','للرموز')}</span></div></div><div className="sp-total"><span>{say('سرمایه قابل چیدمان','Capital to allocate','رأس المال للتوزيع')}</span><strong>{formatted(plan.budgetRial)} <small>{unit}</small></strong><p><Layers3 size={13}/>{n(plan.allocations.length,locale)} {say('توکن','tokens','رموز')}<span>·</span>{n(months,locale)} {monthLabel}</p></div></div>
     {!active&&<p className="sp-no-match">{plan.eligibleCount?say('بودجه و سقف تمرکز برای کوچک‌ترین مقدار قابل تخصیص کافی نیست.','The budget and concentration limit do not cover the smallest allocatable quantity.','الميزانية وحد التركّز لا يكفيان لأصغر كمية قابلة للتخصيص.'):say('دارایی‌های انتخاب‌شده با اطلاعات و شرایط فعلی قابل تخصیص نیستند. قیمت‌ها، مدت و انتخاب‌ها را بررسی کنید.','Selected assets cannot be allocated with the current data and criteria. Check quotes, horizon and selection.','لا يمكن تخصيص الأصول المختارة وفق البيانات والشروط الحالية. تحقق من الأسعار والمدة والاختيارات.')} {say('فعلاً تمام مبلغ تخصیص‌نیافته می‌ماند.','The full amount remains unallocated.','يبقى المبلغ كاملاً دون تخصيص.')}</p>}
     <ul className="sp-allocation-list">{plan.allocations.map((a,i)=><li key={a.project.id} style={{'--sp-token-color':colors[i%colors.length]} as CSSProperties}><a onMouseEnter={()=>setFocusedToken(a.project.id)} onMouseLeave={()=>setFocusedToken(null)} onFocus={()=>setFocusedToken(a.project.id)} onBlur={()=>setFocusedToken(null)} href={'wallex' in a.project?`/assets/${encodeURIComponent(a.project.id)}`:projectHref(a.project,catalog.mode==='preview')} aria-label={`${say('بررسی دارایی','Review asset','مراجعة الأصل')} ${localized(a.project.title,locale)}`}
><span className="sp-token-identity">{'wallex' in a.project?<WallexMark base={a.project.wallex.base}/>:<TokenIcon project={a.project}/>}<span><b dir="ltr">{a.project.symbol}</b><small>{a.quantity?formatInvestmentAmount(a.quantity,locale):n(a.units,locale)} {say('واحد','units','وحدات')}</small></span></span><span className="sp-allocation-value"><b>{formatted(a.amountRial)} <small>{unit}</small></b><span>{n(a.shareTenths/10,locale)}٪</span></span>{locale==='en'?<ArrowUpRight size={16}/>:<ArrowUpLeft size={16}/>}</a></li>)}<li className="sp-cash-row"><span className="sp-token-identity"><span className="sp-cash-icon"><Wallet size={17}/></span><span><b>{say('مانده نقدی','Unallocated cash','الرصيد النقدي')}</b><small>{say('ذخیره + باقیمانده تخصیص','Reserve + allocation remainder','احتياطي + متبقي التوزيع')}</small></span></span><span className="sp-allocation-value"><b>{formatted(plan.cashRial)} <small>{unit}</small></b><span>{n(plan.cashShareTenths/10,locale)}٪</span></span></li></ul>
    </>}
    </div>
    <div className="sp-result-footer"><Check size={14}/>{say('یک سبد از دارایی‌های انتخابی شما؛ برای بررسی هر دارایی روی آن بزنید. سفارش خرید ثبت نمی‌شود.','One portfolio of your selected assets. Select an asset to review it; no purchase is placed.','محفظة واحدة لأصولك المختارة. اختر أصلاً لمراجعته؛ لا يتم تسجيل طلب شراء.')}</div>
   </div>
  </div>
  <div className="sp-footnote"><p>{say('چیدمان بر اساس ترجیحات شما و اطلاعات ثبت‌شده یا قیمت تازه بازار است؛ پیش‌بینی بازده یا رتبه‌بندی ریسک دارایی‌ها نیست.','Allocation uses your preferences and listed or fresh market prices; it does not predict returns or rate asset risk.','يعتمد التوزيع على تفضيلاتك والأسعار المسجلة أو الحديثة؛ دون توقع عوائد أو تصنيف مخاطر الأصول.')}</p><details><summary>{say('چرا این ترکیب؟','Why this mix?','لماذا هذا التوزيع؟')}<ChevronDown size={14}/></summary><div><p>{say(`همه دارایی‌های انتخابی در یک سبد محاسبه می‌شوند؛ ذخیره نقدی هدف ${n(policy.reservePercent,locale)}٪ و سقف سهم هر دارایی ${n(policy.maxTokenPercent,locale)}٪ از کل سرمایه است.`, `All selected assets share one portfolio: the target cash reserve is ${policy.reservePercent}% and each asset is capped at ${policy.maxTokenPercent}% of your full capital.`, `تُحسب جميع الأصول في محفظة واحدة: الاحتياطي المستهدف ${policy.reservePercent}% وحد كل أصل ${policy.maxTokenPercent}% من إجمالي رأس المال.`)}</p><p>{style==='diversified'?say('بودجه بین دارایی‌های واجد شرایط به‌صورت متوازن تقسیم می‌شود و ظرفیت محدود پروژه‌ها در چیدمان لحاظ می‌شود.','The budget is spread evenly across eligible assets, with project capacity limits applied.','توزع الميزانية بالتوازن بين الأصول المؤهلة مع مراعاة سعة المشاريع.'):say('پروژه‌هایی با مدت نزدیک‌تر به افق شما وزن بیشتری می‌گیرند. دارایی‌های بدون مدت مشخص وزن پایه دارند.','Projects whose terms are closer to your horizon receive more weight. Assets without a fixed term keep a neutral weight.','تحصل المشاريع الأقرب إلى أفقك الزمني على وزن أكبر؛ وتحتفظ الأصول دون مدة محددة بالوزن الأساسي.')}</p><p>{say(`پروژه‌ها با ظرفیت باقی‌مانده، واحد کامل و مدت حداکثر ${n(months,locale)} ماه بررسی می‌شوند. تعداد دارایی‌های بازار با قیمت تازه و دقت تعداد همان بازار رو به پایین گرد می‌شود؛ حجم معاملات ظرفیت قابل خرید نیست. دارایی‌های بازار مدت پروژه ندارند و مدت انتخابی شما برای آن‌ها افق برنامه‌ریزی است.`, `Projects use remaining capacity, whole units and terms up to ${months} months. Market-token quantities round down using fresh prices and market precision; trading volume is not available supply. For assets without a fixed project term, your chosen duration is a planning horizon.`, `تُراجع المشاريع بسعتها المتبقية ووحدات كاملة ومدة حتى ${months} شهراً. تُقرب كميات السوق لأسفل بأسعار حديثة ودقة السوق؛ حجم التداول ليس سعة متاحة. المدة المختارة للأصول دون أجل ثابت هي أفق للتخطيط.`)}</p><p>{say('کارمزد، لغزش قیمت و عمق سفارش‌ها در برآورد لحاظ نشده‌اند. مانده گردکردن و محدودیت ظرفیت، نقدی می‌ماند. مدت پروژه تضمین خروج در آن تاریخ نیست.','Fees, slippage and order-book liquidity are excluded. Rounding and capacity remainders stay in cash. Project terms do not guarantee an exit date.','لا يشمل التقدير الرسوم أو الانزلاق السعري أو سيولة الأوامر. تبقى فروق التقريب والسعة نقداً. مدة المشروع لا تضمن تاريخ الخروج.')}</p>{plan.excludedCount>0&&<p>{n(plan.excludedCount,locale)} {say('انتخاب با شرایط فعلی منطبق نبود.','selection(s) did not fit the current criteria.','اختيارات لم توافق الشروط الحالية.')}</p>}</div></details></div>
     </CollapsibleContent>
    </Collapsible>
   </TabsContent>
   <TabsContent value="copy">
    <Collapsible open={copyExpanded} onOpenChange={setCopyExpanded} className="sp-disclosure sp-copy-disclosure">
     <CollapsibleTrigger className="sp-copy-trigger">
      <span className="sp-copy-icon" aria-hidden="true"><Users size={25}/><span><TrendingUp size={13}/></span></span>
      <span className="sp-copy-title"><strong>{say('با تجربهٔ سرمایه‌گذاران همراه شوید','Follow an investor’s approach','اتبع نهج المستثمرين')}</strong><span>{say('کپی‌تریدرهای برتر و سودآورترین افراد','Top traders and leading performers','أفضل المتداولين وأبرز الأداءات')}</span></span>
      <span className="sp-copy-preview">{say('پیش‌نمایش','Preview','معاينة')}</span><ChevronDown className="sp-copy-chevron" size={20}/>
     </CollapsibleTrigger>
     <CollapsibleContent className="sp-disclosure-panel">
      <div className="sp-copy-content">
       <div className="sp-copy-intro"><h3>{say('یک انتخاب، مسیری مشترک.','One choice. A shared approach.','اختيار واحد، ونهج مشترك.')}</h3><p>{say('تریدر را بررسی کنید، سرمایه و شرایط همکاری را مشخص کنید و پس از اتصال، برنامهٔ معاملاتی او را ببینید.','Review a trader, set your capital and connection terms, then connect to view their trading plan.','راجع المتداول وحدد رأس المال وشروط الاتصال، ثم اتصل لعرض خطته التداولية.')}</p></div>
       <ol className="sp-copy-steps">
        <li><span><Users size={20}/></span><div><strong>{say('انتخاب تریدر','Choose a trader','اختر متداولاً')}</strong><p>{say('شناخت روش، ریسک و سابقهٔ عملکرد','Explore approach, risk and track record','تعرّف على النهج والمخاطر وسجل الأداء')}</p></div></li>
        <li><span><Link2 size={20}/></span><div><strong>{say('اتصال و مشاهدهٔ برنامه','Connect to view the plan','اتصل لعرض الخطة')}</strong><p>{say('سرمایهٔ مشخص، با تنظیمات انتخابی شما','Defined capital, with your own settings','رأس مال محدد وإعداداتك الخاصة')}</p></div></li>
        <li><span><TrendingUp size={20}/></span><div><strong>{say('سهم تریدر از سود','Trader’s profit share','حصة المتداول من الربح')}</strong><p>{say('بر اساس سود خالص محقق‌شده و شرایط توافق','Based on realized net profit and agreed terms','بناءً على صافي الربح المحقق والشروط المتفق عليها')}</p></div></li>
       </ol>
       <div className="sp-copy-bottom"><p><LockKeyhole size={16}/>{say('فعلاً با برنامه‌های نمونه آشنا شوید؛ رتبه‌بندی واقعی و اجرای کپی‌ترید هنوز فعال نیست.','Explore example plans for now. Live rankings and trade copying are not active yet.','استكشف الخطط النموذجية حالياً؛ التصنيف الفعلي ونسخ الصفقات غير مفعّلين بعد.')}</p><Link href="/copy-trading" className="sp-copy-link">{say('ورود به صفحهٔ کپی‌ترید','Explore copy trading','استكشف نسخ التداول')}{locale==='en'?<ArrowUpRight size={18}/>:<ArrowUpLeft size={18}/>}</Link></div>
      </div>
     </CollapsibleContent>
    </Collapsible>
   </TabsContent>
  </Tabs>
 </section>;
}
