'use client';

import Link from 'next/link';
import {useRef,useState,type CSSProperties} from 'react';
import {ArrowLeft,ArrowRight,ArrowUpLeft,Check,ChevronLeft,Clock3,Copy,Layers3,Link2,LockKeyhole,Pause,ShieldCheck,SlidersHorizontal,Sparkles,Unplug,Users,Wallet,Zap} from 'lucide-react';
import {SiteFrame,useSite} from './site-shell';
import {LocalizedNumberInput} from './localized-number-input';
import {localized,n,type Catalog,type Locale,type Localized} from '@/lib/catalog';
import {formatInvestmentAmount} from '@/lib/investment-amount';
import {previewAllocations,previewCapitalUnits} from '@/lib/copy-trading';

type Strategy={id:string;title:Localized;subtitle:Localized;description:Localized;style:'steady'|'balanced'|'dynamic';color:string;icon:typeof ShieldCheck;weights:readonly number[];buckets:Localized[];rules:Localized[]};
const text=(fa:string,en:string,ar:string):Localized=>({fa,en,ar});
const strategies:Strategy[]=[
 {id:'steady',title:text('ثبات و تنوع','Steady & diversified','الثبات والتنويع'),subtitle:text('الگوی محافظه‌کارانه','Conservative model','نموذج محافظ'),description:text('نمونه‌ای با سهم بیشتر ذخیره و تصمیم‌های مرحله‌ای؛ برای آشنایی با کنترل سرمایه در کپی‌ترید.','A model with a larger reserve and gradual decisions, illustrating capital controls in copy trading.','نموذج باحتياطي أكبر وقرارات تدريجية للتعرف على إدارة رأس المال.'),style:'steady',color:'#75d7c2',icon:ShieldCheck,weights:[60,25,15],buckets:[text('ذخیرهٔ نقدی','Cash reserve','احتياطي نقدي'),text('سبد اصلی','Core basket','السلة الأساسية'),text('فرصت‌های تکمیلی','Additional opportunities','فرص إضافية')],rules:[text('ورود در چند مرحله، به‌جای تخصیص یک‌باره','Gradual entries instead of a single allocation','الدخول على مراحل بدلاً من التخصيص مرة واحدة'),text('بررسی دوره‌ای نسبت ذخیره به سبد','Periodic review of the reserve ratio','مراجعة دورية لنسبة الاحتياطي'),text('نیاز به تأیید دوباره هنگام تغییر برنامه','Renewed approval when the plan changes','الموافقة مجدداً عند تغيير الخطة')]},
 {id:'balanced',title:text('تعادل هوشمند','Balanced approach','نهج متوازن'),subtitle:text('الگوی متعادل','Balanced model','نموذج متوازن'),description:text('نمونه‌ای از تقسیم سرمایه بین ذخیره، سبد اصلی و فرصت‌ها؛ با حدودی که خودتان تعیین می‌کنید.','A model dividing capital between reserves, a core basket and opportunities, with your own limits.','نموذج لتوزيع رأس المال بين الاحتياطي والسلة الأساسية والفرص بحدود تختارها.'),style:'balanced',color:'#a5b1ff',icon:Layers3,weights:[30,45,25],buckets:[text('ذخیرهٔ نقدی','Cash reserve','احتياطي نقدي'),text('سبد اصلی','Core basket','السلة الأساسية'),text('فرصت‌های تکمیلی','Additional opportunities','فرص إضافية')],rules:[text('تقسیم بودجه میان چند بخش مستقل','Split the budget across separate buckets','توزيع الميزانية على أقسام مستقلة'),text('بازبینی تخصیص‌ها پیش از هر دوره','Review allocations before each period','مراجعة التخصيصات قبل كل فترة'),text('توقف برنامه برای بررسی تغییرات مهم','Pause to review material changes','إيقاف الخطة لمراجعة التغييرات المهمة')]},
 {id:'dynamic',title:text('فرصت‌های پویا','Dynamic opportunities','فرص ديناميكية'),subtitle:text('الگوی فعال','Active model','نموذج نشط'),description:text('نمونه‌ای با سهم بیشتر فرصت‌ها و بازبینی مکرر؛ برای بررسی نحوهٔ تنظیم محدودیت‌های دقیق‌تر.','A model with a larger opportunity bucket and frequent reviews, illustrating more detailed limits.','نموذج بحصة أكبر للفرص ومراجعات متكررة لاستكشاف إعداد حدود أدق.'),style:'dynamic',color:'#f5bb86',icon:Zap,weights:[20,35,45],buckets:[text('ذخیرهٔ نقدی','Cash reserve','احتياطي نقدي'),text('سبد اصلی','Core basket','السلة الأساسية'),text('فرصت‌های تکمیلی','Additional opportunities','فرص إضافية')],rules:[text('بررسی هر فرصت پیش از اضافه‌شدن به سبد','Review each opportunity before including it','مراجعة كل فرصة قبل إضافتها للسلة'),text('پایش مکرر میزان سرمایهٔ درگیر','Frequently review allocated capital','المراجعة المتكررة لرأس المال المخصص'),text('بازبینی برنامه پس از رسیدن به حد انتخابی','Review the plan when the selected limit is reached','مراجعة الخطة عند بلوغ الحد المختار')]},
];

export function CopyTradingPage({catalog,initialTrader}:{catalog:Catalog;initialTrader:string}) {
 return <SiteFrame content={catalog.content} mode={catalog.mode} dashboard detail><CopyTradingBody initialTrader={initialTrader}/></SiteFrame>;
}

function CopyTradingBody({initialTrader}:{initialTrader:string}) {
 const {locale}=useSite();
 const say=(fa:string,en:string,ar:string)=>localized(text(fa,en,ar),locale);
 const [filter,setFilter]=useState('all');
 const selected=strategies.find(strategy=>strategy.id===initialTrader);
 const shown=strategies.filter(strategy=>filter==='all'||strategy.style===filter);
 const DirectionArrow=locale==='en'?ArrowRight:ArrowLeft;
 return <main className="ct-page" id="dashboard" dir={locale==='en'?'ltr':'rtl'}>
  <Link className="ct-back" href={selected?'/copy-trading':'/#smart-investment'}><DirectionArrow size={17}/>{selected?say('همهٔ الگوها','All models','جميع النماذج'):say('بازگشت به سرمایه‌گذاری هوشمند','Back to smart investing','العودة إلى الاستثمار الذكي')}</Link>
  <section className={`ct-hero ${selected?'ct-hero-detail':''}`}>
   <div className="ct-hero-copy">
    <span className="ct-preview"><i/>{say('پیش‌نمایش کپی‌ترید','Copy trading preview','معاينة نسخ التداول')}</span>
    <p className="ct-eyebrow">PLANCK / COPY TRADING</p>
    <h1>{selected?localized(selected.title,locale):say('تجربهٔ دیگران،','Others’ experience,','خبرة الآخرين،')}<br/>{!selected&&<span>{say('انتخاب هوشمندانهٔ شما.','your informed choice.','اختيارك المدروس.')}</span>}</h1>
    <p>{selected?localized(selected.description,locale):say('برنامهٔ تریدر را بشناسید، سهم سرمایهٔ خود را مشخص کنید و مسیر او را با حدودی که انتخاب می‌کنید دنبال کنید.','Explore a trader’s plan, choose your allocation and follow their approach within limits you select.','استكشف خطة المتداول وحدد رأس مالك واتبع نهجه ضمن حدود تختارها.')}</p>
    <div className="ct-hero-pills"><span><SlidersHorizontal size={16}/>{say('کنترل سرمایه','Capital controls','التحكم برأس المال')}</span><span><Link2 size={16}/>{say('دسترسی با اتصال','Connect to access','الاتصال للوصول')}</span><span><Users size={16}/>{say('مشارکت در سود','Profit sharing','المشاركة في الأرباح')}</span></div>
   </div>
   <div className="ct-network-art" aria-hidden="true"><div className="ct-art-orbit"/><div className="ct-art-orbit ct-art-orbit-two"/><div className="ct-art-hub"><Copy size={46}/><i/><b>P</b></div><div className="ct-art-node ct-art-node-one"><ShieldCheck size={28}/></div><div className="ct-art-node ct-art-node-two"><Layers3 size={28}/></div><div className="ct-art-node ct-art-node-three"><Zap size={27}/></div><div className="ct-art-caption"><span/><span/><span/></div></div>
  </section>
  <div className="ct-service-note"><Sparkles size={19}/><p>{say('این نسخه برای آشنایی با کپی‌ترید است. الگوهای زیر نمایشی‌اند؛ فهرست تریدرهای واقعی و رتبه‌بندی سودآوری هنوز متصل نشده است. اتصال آزمایشی هیچ معامله، انتقال وجه یا کارمزدی ایجاد نمی‌کند.','This version previews copy trading. The models below are illustrative; real trader profiles and profitability rankings are not connected yet. A trial connection creates no trades, transfers or fees.','هذه نسخة لمعاينة نسخ التداول. النماذج أدناه توضيحية؛ لم يتم ربط المتداولين الحقيقيين وترتيب الربحية بعد. الاتصال التجريبي لا ينشئ تداولات أو تحويلات أو رسوماً.')}</p></div>
  {selected?<StrategyDetail key={selected.id} strategy={selected} locale={locale}/>:<>
   <section className="ct-directory" aria-labelledby="ct-directory-title">
    <header className="ct-section-heading"><div><span className="ct-eyebrow">EXPLORE THE EXPERIENCE</span><h2 id="ct-directory-title">{say('یک سبک را تجربه کنید','Explore an approach','استكشف نهجاً')}</h2></div><span>{say('الگوهای نمایشی','Illustrative models','نماذج توضيحية')}</span></header>
    <fieldset className="ct-filters"><legend className="sr-only">{say('سبک برنامه','Plan style','نمط الخطة')}</legend>{[{id:'all',label:say('همهٔ سبک‌ها','All styles','جميع الأنماط')},...strategies.map(strategy=>({id:strategy.style,label:localized(strategy.subtitle,locale)}))].map(item=><button type="button" key={item.id} aria-pressed={filter===item.id} onClick={()=>setFilter(item.id)}>{item.label}</button>)}</fieldset>
    <div className="ct-strategy-grid">{shown.map(strategy=><StrategyCard key={strategy.id} strategy={strategy} locale={locale}/>)}</div>
   </section>
   <section className="ct-how" aria-labelledby="ct-how-title"><h2 id="ct-how-title">{say('از انتخاب تا همراهی','From choice to connection','من الاختيار إلى المتابعة')}</h2><div>{[{icon:Users,title:say('بررسی تریدر','Review the trader','مراجعة المتداول'),body:say('در نسخهٔ نهایی، سابقهٔ واقعی، ریسک و شرایط برنامه را مقایسه کنید.','In the final service, compare real track records, risk and plan terms.','في الخدمة النهائية، قارن السجل الفعلي والمخاطر وشروط الخطة.')},{icon:Link2,title:say('اتصال با انتخاب شما','Connect on your terms','اتصل بشروطك'),body:say('مبلغ، محدودیت‌ها و سهم سود را پیش از اتصال بررسی کنید.','Review the amount, limits and profit share before connecting.','راجع المبلغ والحدود وحصة الربح قبل الاتصال.')},{icon:Wallet,title:say('برنامه زیر نظر شما','Keep oversight','الخطة تحت إشرافك'),body:say('برنامه را مشاهده کنید و کنترل ادامه یا توقف آن را در اختیار داشته باشید.','View the plan and control whether to continue or stop.','اطّلع على الخطة وتحكّم في استمرارها أو إيقافها.')}].map((item,index)=><article key={index}><span className="ct-how-number">{n(index+1,locale)}</span><item.icon size={24}/><h3>{item.title}</h3><p>{item.body}</p></article>)}</div></section>
  </>}
  <div className="ct-bottom-link"><span>PLANCK COPY</span><Link href="/#smart-investment">{say('ساخت سبد شخصی خودتان','Build your own portfolio','أنشئ محفظتك الخاصة')}<DirectionArrow size={17}/></Link></div>
 </main>;
}

function StrategyCard({strategy,locale}:{strategy:Strategy;locale:Locale}) {
 const Icon=strategy.icon;
 const say=(fa:string,en:string,ar:string)=>localized(text(fa,en,ar),locale);
 return <article className="ct-strategy-card" style={{'--ct-strategy':strategy.color} as CSSProperties}>
  <div className="ct-card-top"><span className="ct-card-emblem"><Icon size={31}/></span><span className="ct-model-tag">{say('الگوی نمایشی','Demo model','نموذج توضيحي')}</span></div>
  <span className="ct-style-label">{localized(strategy.subtitle,locale)}</span><h3>{localized(strategy.title,locale)}</h3><p>{localized(strategy.description,locale)}</p>
  <dl className="ct-card-facts"><div><dt>{say('سابقهٔ معاملاتی','Trading history','سجل التداول')}</dt><dd>{say('هنوز متصل نیست','Not connected','غير متصل بعد')}</dd></div><div><dt>{say('عملکرد واقعی','Real performance','الأداء الفعلي')}</dt><dd>—</dd></div></dl>
  <div className="ct-locked-caption"><LockKeyhole size={15}/>{say('جزئیات برنامه پس از اتصال آزمایشی','Plan details after trial connection','تفاصيل الخطة بعد الاتصال التجريبي')}</div>
  <Link className="ct-card-action" href={`/copy-trading?trader=${strategy.id}`}>{say('بررسی برنامه و اتصال','Explore & connect','استكشاف واتصال')}<ArrowUpLeft size={18}/></Link>
 </article>;
}

function StrategyDetail({strategy,locale}:{strategy:Strategy;locale:Locale}) {
 const say=(fa:string,en:string,ar:string)=>localized(text(fa,en,ar),locale);
 const [amount,setAmount]=useState('');
 const [limit,setLimit]=useState(10);
 const [period,setPeriod]=useState('90');
 const [accepted,setAccepted]=useState(false);
 const [connected,setConnected]=useState(false);
 const [error,setError]=useState('');
 const input=useRef<HTMLInputElement>(null);
 const allocations=connected?previewAllocations(amount,strategy.weights):null;
 const Icon=strategy.icon;
 return <section className="ct-detail" style={{'--ct-strategy':strategy.color} as CSSProperties} aria-label={say('تنظیم اتصال به برنامه','Configure plan connection','إعداد الاتصال بالخطة')}>
  <form className="ct-connection" onSubmit={event=>{event.preventDefault();if(previewCapitalUnits(amount)===null){setError(say('مبلغی بزرگ‌تر از صفر، با حداکثر یک رقم اعشار وارد کنید.','Enter an amount above zero, with at most one decimal place.','أدخل مبلغاً أكبر من صفر بمنزلة عشرية واحدة كحد أقصى.'));input.current?.focus();return;}if(!accepted)return;setError('');setConnected(true);}}>
   <div className="ct-detail-title"><span className="ct-card-emblem"><Icon size={27}/></span><div><span>{say('تنظیمات همراهی شما','Your connection settings','إعدادات اتصالك')}</span><h2>{localized(strategy.title,locale)}</h2></div></div>
   <label className="ct-field" htmlFor="ct-capital"><span><Wallet size={17}/>{say('میزان سرمایهٔ آزمایشی','Trial capital','رأس المال التجريبي')}</span><div className="ct-amount-wrap"><LocalizedNumberInput ref={input} id="ct-capital" value={amount} onValueChange={value=>{setAmount(value);setError('');}} locale={locale} disabled={connected} aria-invalid={!!error} aria-describedby={error?'ct-capital-error':'ct-capital-hint'} maxLength={17}/><span>{say('تومان','TMN','تومان')}</span></div></label>
   <p className="ct-field-hint" id="ct-capital-hint">{say('برای بررسی نمونه؛ مبلغی از موجودی شما کسر یا رزرو نمی‌شود.','For this preview only; no funds are deducted or reserved.','للمعاينة فقط؛ لا يتم خصم أو حجز أي مبلغ.')}</p>
   {error&&<p id="ct-capital-error" className="ct-error" role="alert">{error}</p>}
   <div className="ct-limit"><label htmlFor="ct-risk-limit">{say('حد افت انتخابی در نمونه','Sample loss threshold','حد الانخفاض في النموذج')}<strong>{n(limit,locale)}٪</strong></label><input id="ct-risk-limit" type="range" min="5" max="30" step="1" value={limit} disabled={connected} onChange={event=>setLimit(Number(event.target.value))} aria-valuetext={`${n(limit,locale)} ${say('درصد','percent','بالمئة')}`}/><span>{say('این حد در پیش‌نمایش ثبت نمایشی دارد و سفارش توقف ایجاد نمی‌کند.','This preview setting does not place a stop order.','هذا الإعداد التجريبي لا ينشئ أمر إيقاف.')}</span></div>
   <fieldset className="ct-period" disabled={connected}><legend><Clock3 size={16}/>{say('بازهٔ بررسی نمونه','Sample review period','فترة مراجعة النموذج')}</legend>{['30','90','180'].map(value=><label key={value}><input type="radio" name="ct-period" value={value} checked={period===value} onChange={()=>setPeriod(value)}/><span>{n(Number(value),locale)} {say('روز','days','يوماً')}</span></label>)}</fieldset>
   <div className="ct-share-summary"><span><Users size={17}/>{say('سهم سود تریدر در این مثال','Trader share in this example','حصة المتداول في هذا المثال')}</span><strong>{n(20,locale)}٪</strong><p>{say('صرفاً نمونهٔ طراحی؛ نرخ واقعی باید در شرایط هر تریدر تعیین شود.','An illustrative rate; actual terms must define each trader’s rate.','نسبة توضيحية؛ تحدد الشروط الفعلية نسبة كل متداول.')}</p></div>
   {!connected?<><label className="ct-consent"><input type="checkbox" checked={accepted} onChange={event=>setAccepted(event.target.checked)}/><span>{say('می‌دانم این اتصال آزمایشی است و هیچ معامله یا پرداختی انجام نمی‌شود.','I understand this is a trial connection with no trades or payments.','أفهم أن هذا اتصال تجريبي بلا تداولات أو مدفوعات.')}</span></label><button className="ct-primary" type="submit" disabled={!accepted}><Link2 size={18}/>{say('اتصال آزمایشی و نمایش برنامه','Trial connection & view plan','اتصال تجريبي وعرض الخطة')}</button></>:<div className="ct-connected-actions"><p aria-live="polite"><Check size={18}/>{say('نمایش برنامه در حالت آزمایشی فعال است','The trial plan is visible','الخطة التجريبية متاحة الآن')}</p><button type="button" className="ct-secondary" onClick={()=>{setConnected(false);setAccepted(false);}}><Unplug size={17}/>{say('قطع اتصال آزمایشی','Disconnect trial','قطع الاتصال التجريبي')}</button></div>}
   <p className="ct-local-note">{say('این اتصال فقط در همین صفحه است و با بارگذاری مجدد پاک می‌شود.','This connection exists only on this page and resets on reload.','هذا الاتصال خاص بهذه الصفحة ويزول عند إعادة تحميلها.')}</p>
  </form>
  <div className="ct-plan-column">
   <section className={`ct-plan ${connected?'is-connected':''}`} aria-labelledby="ct-plan-title"><header><div><span className="ct-eyebrow">STRATEGY ROOM</span><h2 id="ct-plan-title">{say('برنامهٔ اختصاصی','The strategy plan','الخطة الخاصة')}</h2></div>{connected?<span className="ct-open-badge"><Check size={15}/>{say('اتصال آزمایشی','Trial connection','اتصال تجريبي')}</span>:<LockKeyhole size={22}/>}</header>
    {connected&&allocations?<div className="ct-plan-content"><p className="ct-plan-intro">{say('تخصیص زیر صرفاً الگوی نمایش برنامه است؛ دارایی یا سفارش واقعی انتخاب نشده است.','This allocation illustrates a plan; no actual assets or orders have been selected.','هذا التخصيص يوضح الخطة فقط؛ لم يتم اختيار أصول أو أوامر فعلية.')}</p><div className="ct-allocation-bar" aria-hidden="true">{strategy.weights.map((weight,index)=><span key={index} style={{width:`${weight}%`}}/>)}</div><ul className="ct-allocations">{strategy.buckets.map((bucket,index)=><li key={index}><span><i/>{localized(bucket,locale)}</span><strong>{formatInvestmentAmount(allocations[index],locale)} <small>{say('تومان','TMN','تومان')}</small></strong><b>{n(strategy.weights[index],locale)}٪</b></li>)}</ul><h3>{say('منطق الگوی نمایشی','Illustrative plan rules','قواعد الخطة التوضيحية')}</h3><ul className="ct-plan-rules">{strategy.rules.map((rule,index)=><li key={index}><Check size={17}/>{localized(rule,locale)}</li>)}</ul><div className="ct-plan-limit"><Pause size={18}/><p>{say(`بازهٔ بررسی: ${n(Number(period),locale)} روز · حد افت انتخابی: ${n(limit,locale)}٪. اجرای خودکار در این نسخه فعال نیست.`,`Review period: ${period} days · selected loss threshold: ${limit}%. Automatic execution is not active in this version.`,`فترة المراجعة: ${n(Number(period),locale)} يوماً · حد الانخفاض: ${n(limit,locale)}٪. التنفيذ التلقائي غير نشط في هذه النسخة.`)}</p></div></div>:<div className="ct-plan-locked"><div className="ct-lock-art" aria-hidden="true"><i/><i/><LockKeyhole size={37}/></div><h3>{say('ابتدا به برنامه متصل شوید','Connect to reveal the plan','اتصل أولاً لعرض الخطة')}</h3><p>{say('مبلغ و حدود نمونه را انتخاب کنید. پس از اتصال آزمایشی، ترکیب سرمایه و منطق برنامه در این قسمت نمایش داده می‌شود.','Choose your sample amount and limits. After a trial connection, the allocation and plan rules appear here.','اختر المبلغ والحدود التجريبية. بعد الاتصال التجريبي يظهر توزيع رأس المال وقواعد الخطة هنا.')}</p><span><Link2 size={15}/>{say('دسترسی با اتصال آزمایشی','Access via a trial connection','الوصول باتصال تجريبي')}</span></div>}
   </section>
   <section className="ct-profit-model"><div><Users size={21}/><h2>{say('سهم سود، شفاف از ابتدا','Profit sharing, clear from the start','حصة الربح واضحة من البداية')}</h2><span>{say('مثال','Example','مثال')}</span></div><p>{say('مدل پیشنهادی سهم سود فقط از سود خالصِ تحقق‌یافتهٔ مثبت محاسبه می‌شود؛ نه از اصل سرمایه. در این پیش‌نمایش هیچ سود یا کارمزدی محاسبه و تسویه نمی‌شود.','The proposed model shares only positive realized net profit, never the initial capital. This preview does not calculate or settle actual profit or fees.','يقترح النموذج مشاركة صافي الربح المحقق الموجب فقط، دون رأس المال الأصلي. لا تحسب هذه المعاينة أرباحاً أو رسوماً فعلية ولا تسويها.')}</p><div className="ct-profit-split"><div><span>{say('سهم شما در مثال','Your example share','حصتك في المثال')}</span><strong>{n(80,locale)}٪</strong></div><div><span>{say('سهم تریدر در مثال','Trader’s example share','حصة المتداول في المثال')}</span><strong>{n(20,locale)}٪</strong></div></div><p className="ct-profit-conditions">{say('شرایط جبران زیان قبلی، دورهٔ تسویه و کارمزدها پیش از فعال‌شدن اتصال واقعی باید مشخص و تأیید شوند.','Loss-recovery rules, settlement periods and fees must be defined and accepted before live connections are available.','يجب تحديد وقبول قواعد تعويض الخسائر وفترات التسوية والرسوم قبل إتاحة الاتصال الفعلي.')}</p></section>
   <Link className="ct-other-models" href="/copy-trading">{say('بررسی الگوهای دیگر','Explore other models','استكشاف نماذج أخرى')}<ChevronLeft size={17}/></Link>
  </div>
 </section>;
}
