'use client';

import {useCallback,useEffect,useRef,useState} from 'react';
import Image from 'next/image';
import Link from 'next/link';
import {ArrowLeft,ArrowRight,BadgeCheck,BriefcaseBusiness,Building2,CarFront,Check,CheckCircle2,ChevronDown,Clock3,CodeXml,Download,Factory,FerrisWheel,FileCheck2,FileText,FlaskConical,FolderOpen,Fuel,Gem,Lightbulb,LockKeyhole,MapPinned,Mountain,Music2,Palette,RefreshCw,Rocket,ShieldCheck,Sparkles,Sprout,Store,Sun,Upload,Wallet,Wind,X,type LucideIcon} from 'lucide-react';
import type {Catalog} from '@/lib/catalog';
import {assetTypes,getAssetType,getAssetFields,categoryLabels,TERMS_VERSION,termsSections,statusLabels,reviewLabels,type TokenizationRequest,type AssetField} from '@/lib/tokenization';
import {formatLocalizedNumberInput} from '@/lib/localized-number-input';
import {persistTokenizationDraft,clearCompletedDraftDocument,latestTokenizationSnapshot,mergeTokenizationSnapshots,type PendingTokenizationDocuments} from '@/lib/tokenization-draft';
import {SiteFrame,useSite} from './site-shell';
import {LocalizedNumberInput} from './localized-number-input';
import {TokenizationStepIcon} from './tokenization-step-icon';
import {TokenizationStageScene} from './tokenization-stage-scene';

const steps=[{title:'انتخاب دارایی',text:'مشهود یا نامشهود',icon:0},{title:'مشخصات دارایی',text:'اطلاعات اختصاصی',icon:0},{title:'اسناد و مدارک',text:'تکمیل پرونده',icon:1},{title:'بررسی و تأیید',text:'حقوقی، مالی و فنی',icon:1},{title:'توکنومیکس و واریز',text:'کیف پول داخلی پلانک',icon:2}];
const fa=(value:string|number)=>formatLocalizedNumberInput(String(value),'fa');
const date=(value?:string|null)=>value&&Number.isFinite(new Date(value).getTime())?new Intl.DateTimeFormat('fa-IR',{dateStyle:'medium',timeStyle:'short'}).format(new Date(value)):'—';
const editable=(request:TokenizationRequest)=>request.status==='draft'||request.status==='changes_requested';
const stageFor=(request:TokenizationRequest)=>editable(request)?request.wizard_step??request.progress?.current_step??1:request.tokenomics?4:3;
const validDocument=(status:TokenizationRequest['documents'][number]['status'])=>status==='uploaded'||status==='approved';
const documentsReady=(request:TokenizationRequest,approved=false)=>!!getAssetType(request.asset_type)?.documents.filter(slot=>slot.required).every(slot=>request.documents.some(doc=>doc.slot===slot.key&&(approved?doc.status==='approved':validDocument(doc.status))));
const proposalReady=(request:TokenizationRequest)=>request.status==='awaiting_acceptance'&&!!request.tokenomics&&request.proposal_version>0&&(['legal','financial','technical'] as const).every(layer=>request.reviews[layer].status==='approved')&&documentsReady(request,true);
const assetIcons:Record<string,LucideIcon>={Sun,Building2,MapPinned,Store,Sprout,Factory,CarFront,Gem,Palette,Fuel,Wind,FerrisWheel,Mountain,Rocket,BriefcaseBusiness,Lightbulb,FlaskConical,BadgeCheck,CodeXml,Music2};
type ApiResult={requests?:TokenizationRequest[];request?:TokenizationRequest;error?:string;message?:string};
async function api(path:string,init?:RequestInit):Promise<ApiResult>{
 const response=await fetch(path,{...init,cache:'no-store'});
 const data=await response.json().catch(()=>({error:'پاسخ سرویس قابل خواندن نیست. دوباره تلاش کنید.'})) as ApiResult;
 if(!response.ok)throw new Error(data.error||data.message||'ارتباط با سرویس برقرار نشد. دوباره تلاش کنید.');
 return data;
}

export function TokenizePage({catalog}:{catalog:Catalog}){
 return <SiteFrame content={catalog.content} mode={catalog.mode} dashboard detail><TokenizeBody/></SiteFrame>;
}
function TokenizeBody(){
 const {user,sessionStatus}=useSite();
 return <main id="dashboard" className="tokenize-page" dir="rtl"><div className="tk-topline"><Link href="/#asset-tokenization"><ArrowRight size={18}/> بازگشت به پلانک</Link><Link href="/docs/tokenization">راهنمای توکنایزیشن <FileText size={17}/></Link></div><TokenizeWorkspace key={user?.id||'guest'} signedIn={!!user} sessionReady={sessionStatus!=='loading'}/></main>;
}
function TokenizeWorkspace({signedIn,sessionReady}:{signedIn:boolean;sessionReady:boolean}){
 const {open}=useSite();
 const [requests,setRequests]=useState<TokenizationRequest[]>([]),[current,setCurrent]=useState<TokenizationRequest|null>(null);
 const [screen,setScreen]=useState<'intro'|'wizard'>('intro'),[step,setStep]=useState(0),[category,setCategory]=useState<'tangible'|'intangible'>('tangible');
 const [type,setType]=useState(''),[fields,setFields]=useState<Record<string,string>>({}),[dirty,setDirty]=useState(false);
 const [pendingDocuments,setPendingDocuments]=useState<PendingTokenizationDocuments>({}),[hasWorkspace,setHasWorkspace]=useState(false);
 const typeDrafts=useRef<Record<string,{fields:Record<string,string>;documents:PendingTokenizationDocuments}>>({});
 const [agreed,setAgreed]=useState(false),[submitConsent,setSubmitConsent]=useState(false),[acceptConsent,setAcceptConsent]=useState(false);
 const [busy,setBusy]=useState(false),[loading,setLoading]=useState(false),[error,setError]=useState(''),[notice,setNotice]=useState('');
 const [fieldError,setFieldError]=useState('');
 const [autosaving,setAutosaving]=useState(false),[autosaveError,setAutosaveError]=useState(''),[draftRevision,setDraftRevision]=useState(0);
 const currentRef=useRef<TokenizationRequest|null>(null),revisionRef=useRef(0),lastAttempt=useRef(-1),persistLatest=useRef<()=>Promise<TokenizationRequest>>(null);
 const heading=useRef<HTMLHeadingElement>(null),mounted=useRef(true),actionLock=useRef(false);
 const markDirty=()=>{revisionRef.current+=1;setDraftRevision(revisionRef.current);setDirty(true);setAutosaveError('');};
 useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
 const fetchRequests=useCallback(async()=>{
  if(!signedIn||actionLock.current)return;
  setLoading(true);
  try{const result=await api('/api/tokenization');if(mounted.current){setRequests(items=>mergeTokenizationSnapshots(items,result.requests||[]));setError('');}}
  catch(e){if(mounted.current)setError((e as Error).message);}
  finally{if(mounted.current)setLoading(false);}
 },[signedIn]);
 useEffect(()=>{const timer=window.setTimeout(()=>void fetchRequests(),0);return()=>window.clearTimeout(timer);},[fetchRequests]);
 useEffect(()=>{if(!dirty)return;const warn=(event:BeforeUnloadEvent)=>{event.preventDefault();};window.addEventListener('beforeunload',warn);return()=>window.removeEventListener('beforeunload',warn);},[dirty]);
 useEffect(()=>{if(screen==='wizard')heading.current?.focus();},[step,screen]);
 const adopt=useCallback((request:TokenizationRequest)=>{
  currentRef.current=request;setAutosaveError('');
  setCurrent(request);setType(request.asset_type);setFields(request.fields);setDirty(false);setFieldError('');
  setPendingDocuments({});typeDrafts.current={};setHasWorkspace(true);
  setCategory(getAssetType(request.asset_type)?.category||'tangible');setSubmitConsent(false);setAcceptConsent(false);
  setRequests(items=>mergeTokenizationSnapshots(items,[request]));
 },[]);
 const run=async(operation:()=>Promise<void>)=>{
  if(actionLock.current)return;actionLock.current=true;setBusy(true);setError('');setNotice('');
  try{await operation();}catch(e){if(mounted.current){setError((e as Error).message);setSubmitConsent(false);setAcceptConsent(false);}}
  finally{actionLock.current=false;if(mounted.current)setBusy(false);}
 };
 const requestMutation=useCallback(async(action:string,request:TokenizationRequest|null,values:Record<string,unknown>={})=>{
  const result=await api('/api/tokenization',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action,...(request?{id:request.id,version:request.version}:{}),...values})});
  if(!result.request)throw new Error('درخواست ذخیره نشد. وضعیت را به‌روزرسانی کنید.');
  return result.request;
 },[]);
 const mutate=async(action:string,values:Record<string,unknown>={})=>{const request=await requestMutation(action,current,values);if(mounted.current)adopt(request);return request;};
 const begin=()=>{
  if(!agreed&&!hasWorkspace)return;
  if(!signedIn){open('login');return;}
  setHasWorkspace(true);setError('');setNotice('');setScreen('wizard');
 };
 const resume=(request:TokenizationRequest)=>{
  if(actionLock.current)return;
  const latest=latestTokenizationSnapshot(request,currentRef.current);
  if(currentRef.current?.id===request.id&&hasWorkspace&&(dirty||latest===currentRef.current)){setScreen('wizard');return;}
  if(dirty&&!window.confirm('با باز کردن پروندهٔ دیگر، اطلاعات موقت پروندهٔ جاری کنار گذاشته می‌شود. ادامه می‌دهید؟'))return;
  adopt(latest);setScreen('wizard');setStep(stageFor(latest));setError('');setNotice('');
 };
 const resetDraft=()=>{
  currentRef.current=null;setAutosaveError('');revisionRef.current+=1;setDraftRevision(revisionRef.current);
  setCurrent(null);setType('');setCategory('tangible');setFields({});setPendingDocuments({});typeDrafts.current={};setDirty(false);setHasWorkspace(false);setStep(0);setAgreed(false);setSubmitConsent(false);setAcceptConsent(false);setFieldError('');setError('');setNotice('');
 };
 const newDraft=()=>{if(actionLock.current)return;if(dirty&&!window.confirm('اطلاعات موقت پروندهٔ جاری کنار گذاشته شود و پروندهٔ جدیدی شروع کنید؟'))return;resetDraft();};
 const goStep=(next:number)=>{if(busy)return;setError('');setNotice('');if(next<0){setScreen('intro');return;}if(next>4||next>0&&!type||next===4&&!current?.tokenomics)return;setStep(next);if(next<=3&&next!==step&&(!current||editable(current)))markDirty();};
 const chooseType=(next:string)=>{
  if(current||actionLock.current||next===type)return;
  if(type)typeDrafts.current[type]={fields,documents:pendingDocuments};
  const cached=typeDrafts.current[next];setType(next);setFields(cached?.fields||{});setPendingDocuments(cached?.documents||{});
  markDirty();setFieldError('');setSubmitConsent(false);setAcceptConsent(false);setError('');setNotice('');
 };
 const persist=useCallback(async(complete:boolean,background=false)=>{
  const revision=revisionRef.current,base=currentRef.current,documentSnapshot=pendingDocuments;
  if(!agreed&&!base)throw new Error('ابتدا شرایط ثبت درخواست را مطالعه و تأیید کنید.');
  try{
   const saved=await persistTokenizationDraft({request:base,assetType:type,fields,documents:documentSnapshot,complete,wizardStep:Math.min(step,3),
    transport:{
     start:assetType=>requestMutation('start',null,{asset_type:assetType,terms_version:TERMS_VERSION,consent:true,wizard_step:Math.min(step,3)}),
     save:(request,normalized,wizardStep)=>requestMutation('save',request,{asset_type:type,fields:normalized,wizard_step:wizardStep}),
     upload:async(request,slot,file)=>{const form=new FormData();form.set('id',request.id);form.set('version',String(request.version));form.set('slot',slot);form.set('file',file);const result=await api('/api/tokenization/documents',{method:'POST',body:form});if(!result.request)throw new Error('ذخیرهٔ مدرک کامل نشد. دوباره تلاش کنید.');return result.request;},
     remove:async(request,documentId)=>{const result=await api('/api/tokenization/documents',{method:'DELETE',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:request.id,version:request.version,document_id:documentId})});if(!result.request)throw new Error('حذف مدرک تأیید نشد. دوباره تلاش کنید.');return result.request;}
    },
    checkpoint:(request,slot)=>{if(!mounted.current)return;currentRef.current=request;setCurrent(request);setRequests(items=>mergeTokenizationSnapshots(items,[request]));if(slot)setPendingDocuments(previous=>clearCompletedDraftDocument(previous,documentSnapshot,slot));}
   });
   if(mounted.current){if(background){if(revisionRef.current===revision)setDirty(false);setAutosaveError('');}else adopt(saved);}return saved;
  }catch(e){const validation=e as Error&{field?:string};if(validation.field&&!background){setStep(1);setFieldError(validation.field);}throw e;}
 },[agreed,type,fields,pendingDocuments,step,requestMutation,adopt]);
 useEffect(()=>{persistLatest.current=()=>persist(false,true);},[persist]);
 useEffect(()=>{
  if(!signedIn||!hasWorkspace||!type||(!current&&step===0)||!dirty||busy||autosaving||(current&&!editable(current))||lastAttempt.current===draftRevision)return;
  const timer=window.setTimeout(async()=>{
   if(actionLock.current)return;
   actionLock.current=true;lastAttempt.current=draftRevision;setAutosaving(true);
   try{await persistLatest.current?.();}
   catch(e){if(mounted.current)setAutosaveError((e as Error).message);}
   finally{actionLock.current=false;if(mounted.current)setAutosaving(false);}
  },1000);
  return()=>window.clearTimeout(timer);
 },[signedIn,hasWorkspace,type,current,step,dirty,busy,autosaving,draftRevision]);
 const saveDraft=()=>void run(async()=>{await persist(false);setNotice('اطلاعات و مدارک شما به‌صورت پیش‌نویس ذخیره شد.');});
 const refresh=()=>void run(async()=>{
  if(dirty&&!window.confirm('با دریافت آخرین وضعیت، تغییرات ذخیره‌نشده کنار گذاشته می‌شود. ادامه می‌دهید؟'))return;
  const result=await api('/api/tokenization');if(!mounted.current)return;setRequests(items=>mergeTokenizationSnapshots(items,result.requests||[]));
  const updated=result.requests?.find(item=>item.id===currentRef.current?.id);
  if(updated){const latest=latestTokenizationSnapshot(updated,currentRef.current);adopt(latest);setStep(stageFor(latest));}
  else if(current){resetDraft();setScreen('intro');throw new Error('این پرونده در فهرست حساب شما موجود نیست. وضعیت حساب و فهرست پرونده‌ها را بررسی کنید.');}
  setNotice('آخرین وضعیت پرونده دریافت شد.');
 });
 const upload=(slot:string,file:File)=>{
  if(busy||autosaving||current&&!editable(current))return;setError('');setNotice('');
  if(!file.size||file.size>10*1024*1024){setError('حجم هر مدرک باید بیشتر از صفر و حداکثر ۱۰ مگابایت باشد.');return;}
  if(!['application/pdf','image/jpeg','image/png'].includes(file.type)){setError('مدرک را به‌صورت PDF، JPG یا PNG انتخاب کنید.');return;}
  setPendingDocuments(previous=>({...previous,[slot]:file}));markDirty();setSubmitConsent(false);setAcceptConsent(false);
 };
 const remove=(slot:string)=>{
  if(busy||autosaving||current&&!editable(current))return;
  setPendingDocuments(previous=>{const next={...previous};if(Object.hasOwn(next,slot))delete next[slot];else next[slot]=null;return next;});
  markDirty();setSubmitConsent(false);setAcceptConsent(false);setNotice('');
 };
 const submit=()=>void run(async()=>{
  if(current&&!editable(current)||!submitConsent||!docsComplete)return;
  const saved=await persist(true);const submitted=await requestMutation('submit',saved,{consent:true});if(mounted.current)adopt(submitted);setStep(3);setNotice('پرونده برای بررسی به مدیریت ارسال شد. وضعیت هر بررسی در همین صفحه نمایش داده می‌شود.');
 });
 const accept=()=>void run(async()=>{if(!current||!proposalReady(current)||!acceptConsent)return;await mutate('accept',{proposal_version:current.proposal_version,consent:true});setNotice('تأیید شما ثبت شد. نتیجهٔ صدور و واریز به کیف پول داخلی در همین صفحه قابل پیگیری است.');});
 const activeType=getAssetType(type),canEdit=!current||editable(current);
 const slotReady=(slot:string)=>Object.hasOwn(pendingDocuments,slot)?!!pendingDocuments[slot]:!!current?.documents.some(doc=>doc.slot===slot&&validDocument(doc.status));
 const docsComplete=!!activeType&&activeType.documents.filter(slot=>slot.required).every(slot=>slotReady(slot.key));
 const hasProposal=!!current?.tokenomics;
 const showError=<>{error&&<div id="tk-validation-error" className="tk-alert tk-alert-error" role="alert"><X size={20}/><div>{error}<button type="button" onClick={current?refresh:()=>void fetchRequests()} disabled={busy||autosaving||loading}>دریافت دوبارهٔ وضعیت <RefreshCw size={14}/></button></div></div>}{notice&&<output className="tk-alert tk-alert-info"><CheckCircle2 size={20}/>{notice}</output>}</>;
 return <>
  {screen==='intro'?<>
   <section className="tk-welcome"><div className="tk-welcome-copy"><span className="tk-eyebrow"><span/> PLANCK TOKENIZATION</span><h1>دارایی شما،<br/><em>فرصتی برای فردا.</em></h1><p>از ملک و نیروگاه تا کسب‌وکار و مالکیت فکری؛ دارایی خود را معرفی کنید، مدارک را ارائه دهید و مسیر تبدیل آن به توکن را با پلانک پیش ببرید.</p><div className="tk-welcome-tags"><span><ShieldCheck size={17}/> بررسی پیش از انتشار</span><span><Wallet size={17}/> کیف پول داخلی پلانک</span></div></div><div className="tk-welcome-art"><div className="tk-art-orbit"/><TokenizationStageScene stage={2}/><div className="tk-art-label"><Image src="/images/plank-symbol.svg" alt="" width="22" height="28"/><span>دارایی واقعی<small>امکانات دیجیتال</small></span><Sparkles size={20}/></div></div></section>
   <div className="tk-intro-steps">{steps.map((item,index)=><div key={item.title}><TokenizationStepIcon stage={item.icon}/><span><small>مرحله {fa(index+1)}</small><strong>{item.title}</strong></span></div>)}</div>
   {signedIn&&<section className="tk-panel tk-my-requests"><div className="tk-section-head"><div><span className="tk-eyebrow">پرونده‌های شما</span><h2>ادامه از همان‌جایی که بودید</h2></div><button className="tk-quiet" onClick={()=>void fetchRequests()} disabled={loading||busy||autosaving}><RefreshCw size={17} className={loading?'tk-spin':''}/> به‌روزرسانی</button></div>{loading&&!requests.length?<p>در حال دریافت پرونده‌ها…</p>:requests.length?<div className="tk-request-list">{requests.map(request=><button key={request.id} disabled={busy||autosaving} onClick={()=>resume(request)}><span className="tk-request-icon"><FolderOpen size={24}/></span><span><strong>{request.fields.title||getAssetType(request.asset_type)?.title||'پروندهٔ دارایی'}</strong><small>{date(request.updated_at)} · شناسه {request.id.slice(0,8)}</small></span><StatusBadge status={request.status}/><ArrowLeft size={18}/></button>)}</div>:!error?<p className="tk-muted">هنوز پرونده‌ای ثبت نکرده‌اید. با مطالعهٔ شرایط زیر، اولین دارایی خود را معرفی کنید.</p>:null}</section>}
   {showError}
   <section className="tk-panel tk-terms" aria-labelledby="tk-terms-heading"><div className="tk-section-head"><div><span className="tk-eyebrow">پیش از شروع</span><h2 id="tk-terms-heading">مسیر روشن، تصمیم آگاهانه</h2><p>شرایط ثبت درخواست و مراحل بررسی دارایی را مطالعه کنید.</p></div><FileCheck2 size={36}/></div><div className="tk-terms-grid">{termsSections.map((section,index)=><article key={section.title}><span>{fa(index+1).padStart(1,'۰')}</span><div><h3>{section.title}</h3><p>{section.text}</p></div></article>)}</div><div className="tk-start-row"><label className="tk-consent"><input type="checkbox" checked={agreed} onChange={event=>setAgreed(event.target.checked)}/><span>شرایط بالا را خوانده‌ام و با ثبت درخواست و بررسی اطلاعات و مدارک دارایی موافقم.<small>نسخهٔ شرایط: <bdi>{TERMS_VERSION}</bdi></small></span></label><button className="tk-primary" onClick={begin} disabled={!hasWorkspace&&!agreed||!sessionReady}>{hasWorkspace?'ادامهٔ پروندهٔ جاری':'شروع توکنایزیشن'} <ArrowLeft size={19}/></button></div></section>
   {hasWorkspace&&<button className="tk-quiet tk-new-draft" disabled={busy||autosaving} onClick={newDraft}>شروع پروندهٔ جدید</button>}
   <div className="tk-help"><span>برای آماده‌کردن پرونده همراهتان هستیم.</span><a href="tel:+982182805404">دریافت مشاوره · <bdi>۰۲۱۸۲۸۰۵۴۰۴</bdi></a></div>
  </>:<>
   <div className="tk-workspace-heading"><div><span className="tk-eyebrow">از دارایی تا توکن</span><h1>پروندهٔ توکنایزیشن شما</h1><p>{current?`${activeType?.title||'دارایی'} · شناسهٔ پیگیری ${current.id.slice(0,8)}`:'دارایی را انتخاب کنید؛ باقی مسیر متناسب با انتخاب شماست.'}</p></div><button className="tk-quiet" disabled={busy} onClick={()=>{setScreen('intro');setError('');setNotice('');}}><FolderOpen size={18}/> همهٔ پرونده‌ها</button></div>
   <div className="tk-wizard-layout"><aside className="tk-sidebar"><div className="tk-sidebar-heading"><span>مسیر دارایی شما</span>{current&&<StatusBadge status={current.status}/>}</div><ol className="tk-step-list">{steps.map((item,index)=>{const accessible=index===0||!!type&&(index<4||hasProposal);return <li key={item.title} className={index===step?'is-active':''}><button onClick={()=>goStep(index)} disabled={!accessible||busy} aria-current={index===step?'step':undefined}><span className="tk-step-illustration"><TokenizationStepIcon stage={item.icon}/></span><span><small>مرحله {fa(index+1)}</small><strong>{item.title}</strong><small>{item.text}</small></span>{index===step&&<span className="tk-current-dot"/>}</button></li>;})}</ol><div className="tk-sidebar-note"><LockKeyhole size={22}/><strong>پروندهٔ شخصی شما</strong><p>مدارک برای بررسی درخواست در اختیار کارشناسان مجاز قرار می‌گیرد.</p><a href="tel:+982182805404">مشاوره: <bdi>۰۲۱۸۲۸۰۵۴۰۴</bdi></a></div></aside>
   <section className="tk-workarea" aria-busy={busy}>{canEdit&&<output className={`tk-autosave-status ${autosaveError?'has-error':''}`}><FileCheck2 size={17}/><span>{autosaving?'در حال ذخیرهٔ خودکار پیش‌نویس…':autosaveError?`ذخیرهٔ خودکار انجام نشد: ${autosaveError}`:dirty?(step===0&&!current?'پس از انتخاب دارایی و رفتن به مرحلهٔ بعد، پیش‌نویس خودکار ذخیره می‌شود.':'تغییرات در انتظار ذخیرهٔ خودکار…'):current?`پیش‌نویس ذخیره شد · ${date(current.updated_at)}`:'پیش‌نویس شما پس از انتخاب دارایی خودکار ذخیره می‌شود.'}<small>اطلاعات و مدارک ذخیره‌شده برای مدیر قابل مشاهده است؛ ارسال نهایی با تأیید شما انجام می‌شود.</small></span>{autosaveError&&<button className="tk-quiet" disabled={busy||autosaving} onClick={saveDraft}>تلاش دوباره</button>}</output>}<div className="tk-progress" aria-hidden="true"><span style={{width:`${(step+1)*20}%`}}/></div>{showError}<div className="tk-panel tk-stage"><header className="tk-stage-heading"><div><span className="tk-eyebrow">مرحله {fa(step+1)} از ۵</span><h2 ref={heading} tabIndex={-1}>{steps[step].title}</h2></div><TokenizationStepIcon stage={steps[step].icon}/></header>
   {step===0&&<><p className="tk-lead">چه دارایی‌ای را می‌خواهید توکن کنید؟</p><div className="tk-category-tabs">{(['tangible','intangible'] as const).map(value=><button key={value} aria-pressed={category===value} className={category===value?'is-active':''} disabled={busy||autosaving||!!current} onClick={()=>{if(value!==category){setCategory(value);chooseType('');}}}><TokenizationStepIcon stage={value==='tangible'?0:2}/><span>{categoryLabels[value]}<small>{value==='tangible'?'دارایی‌های فیزیکی و زیرساخت':'حقوق، کسب‌وکار و ایده‌ها'}</small></span></button>)}</div><fieldset className="tk-asset-picker" disabled={busy||autosaving||!!current}><legend>نوع دقیق دارایی خود را انتخاب کنید</legend>{assetTypes.filter(asset=>asset.category===category).map(asset=><label key={asset.id} className={type===asset.id?'is-selected':''}><input type="radio" name="asset-type" value={asset.id} checked={type===asset.id} onChange={()=>chooseType(asset.id)}/><span className="tk-asset-symbol" aria-hidden="true"><AssetSymbol name={asset.icon}/></span><span><strong>{asset.title}</strong><small>{asset.description}</small></span><span className="tk-radio-mark">{type===asset.id&&<Check size={14}/>}</span></label>)}</fieldset>{activeType&&<div className="tk-selection-note"><FileCheck2 size={20}/><span>{fa(getAssetFields(type).length)} مورد اطلاعات و {fa(activeType.documents.filter(doc=>doc.required).length)} مدرک ضروری برای این دارایی دریافت می‌شود.</span></div>}{current&&<p className="tk-save-note">نوع داراییِ پروندهٔ ذخیره‌شده ثابت است. می‌توانید اطلاعات و مدارک آن را در مراحل بعد مشاهده کنید.</p>}</>}
   {step===1&&activeType&&<form onSubmit={event=>{event.preventDefault();goStep(2);}}><p className="tk-lead">اطلاعات {activeType?.title} را وارد کنید.</p><div className="tk-inline-info"><FileText size={18}/><span>دارایی انتخاب‌شده: <strong>{activeType?.title}</strong> · اطلاعات هنگام رفت‌وبرگشت بین مراحل حفظ می‌شود.</span></div><fieldset disabled={busy||!canEdit} className="tk-fields">{getAssetFields(type).map(field=><AssetInput key={field.key} field={field} value={fields[field.key]||''} invalid={fieldError===field.key} onChange={value=>{setFields(previous=>({...previous,[field.key]:value}));markDirty();setFieldError('');setSubmitConsent(false);setAcceptConsent(false);}}/>)}</fieldset></form>}
   {step===2&&activeType&&<><p className="tk-lead">مدارک متناسب با دارایی شما</p><div className="tk-document-summary"><span><FileCheck2 size={21}/> {fa(activeType.documents.filter(slot=>slot.required&&slotReady(slot.key)).length)} از {fa(activeType.documents.filter(slot=>slot.required).length)} مدرک ضروری</span><small>PDF، JPG یا PNG · هر فایل حداکثر ۱۰ مگابایت</small></div>
    {canEdit&&<p className="tk-muted">فایل‌های انتخاب‌شده خودکار در پیش‌نویس ذخیره و برای مدیر قابل مشاهده می‌شوند. بررسی رسمی پس از ارسال نهایی پرونده آغاز می‌شود.</p>}
    {Array.from(new Set(activeType.documents.map(slot=>slot.group))).map(group=><section className="tk-document-group" key={group}><h3>{group}</h3>{activeType.documents.filter(slot=>slot.group===group).map(slot=>{
     const savedDoc=current?.documents.find(item=>item.slot===slot.key),pending=pendingDocuments[slot.key],pendingRemoval=pending===null;
     const doc=pending?{name:pending.name,size:pending.size,status:'staged',id:''}:pendingRemoval?undefined:savedDoc;
     return <article className="tk-document" key={slot.key}><div className="tk-doc-title"><span className="tk-doc-icon">{doc?<FileCheck2 size={24}/>:<FileText size={24}/>}</span><div><h4>{slot.label}<small>{slot.required?'ضروری':'اختیاری'}</small></h4><p>{slot.description}</p></div></div>
      {doc&&<div className="tk-file-info"><span>{pending?<span className="tk-staged-file"><FileText size={15}/>{doc.name}</span>:<a href={`/api/tokenization/documents?id=${encodeURIComponent(current!.id)}&document=${encodeURIComponent(doc.id)}`} target="_blank" rel="noreferrer"><Download size={15}/>{doc.name}</a>}<small>{fa((doc.size/1024).toFixed(0))} کیلوبایت · {pending?'انتخاب‌شده؛ هنوز ذخیره نشده':doc.status==='approved'?'تأیید شده':doc.status==='changes_requested'?'نیازمند اصلاح':doc.status==='rejected'?'رد شده':'بارگذاری شده؛ در انتظار بررسی'}</small></span>{canEdit&&<button className="tk-quiet" disabled={busy||autosaving} onClick={()=>remove(slot.key)} aria-label={`${pending?'لغو انتخاب':'حذف'} ${slot.label}`}><X size={17}/></button>}</div>}
      {pendingRemoval&&savedDoc&&<div className="tk-file-info"><span>حذف «{savedDoc.name}» هنگام ذخیره انجام می‌شود.</span><button className="tk-quiet" onClick={()=>remove(slot.key)} disabled={busy||autosaving}>انصراف از حذف</button></div>}
      {!pending&&!pendingRemoval&&savedDoc?.message&&<p className={`tk-doc-message ${!validDocument(savedDoc.status)?'needs-changes':''}`}>{savedDoc.message}</p>}
      {canEdit&&<label className={`tk-upload ${busy||autosaving?'is-disabled':''}`}><Upload size={17}/>{doc?'انتخاب مدرک جایگزین':'انتخاب مدرک'}<input type="file" accept="application/pdf,image/jpeg,image/png" disabled={busy||autosaving} aria-label={`بارگذاری ${slot.label}`} onChange={event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(file)upload(slot.key,file);}}/></label>}
     </article>;
    })}</section>)}
   </>}
   {step===3&&canEdit&&activeType&&<>
    <p className="tk-lead">مرور و ارسال پرونده</p><p className="tk-muted">اطلاعات و مدارک را مرور کنید. می‌توانید با دکمهٔ مرحله قبل برگردید و آن‌ها را تکمیل کنید؛ بررسی کارشناسان پس از ارسال شروع می‌شود.</p>
    <div className="tk-application-summary tk-draft-summary"><h3>{fields.title||activeType.title}</h3><dl>{getAssetFields(type).map(field=><div key={field.key}><dt>{field.label}</dt><dd>{!fields[field.key]?'تکمیل نشده':field.type==='number'?fa(fields[field.key]):field.options?.find(option=>option.value===fields[field.key])?.label||fields[field.key]}</dd></div>)}</dl><h3>مدارک پرونده</h3><ul className="tk-draft-documents">{activeType.documents.map(slot=><li key={slot.key}><span>{slot.label}{slot.required?' · ضروری':''}</span><span>{pendingDocuments[slot.key]?.name||(pendingDocuments[slot.key]!==null?current?.documents.find(doc=>doc.slot===slot.key)?.name:'')||'انتخاب نشده'}</span></li>)}</ul></div>
    {current?.status==='changes_requested'&&<><StatusBadge status={current.status}/><ReviewCards request={current}/></>}
    {current?.message&&<output className="tk-alert tk-alert-info"><FileText size={20}/>{current.message}</output>}
    <div className="tk-submit-box"><h3>آمادهٔ ارسال برای بررسی</h3><p>با ارسال، اطلاعات و مدارک ذخیره و پرونده برای ارزیابی حقوقی، مالی و فنی به مدیریت ارسال می‌شود.</p><label className="tk-consent"><input type="checkbox" checked={submitConsent} disabled={busy} onChange={event=>setSubmitConsent(event.target.checked)}/><span>درستی اطلاعات و مدارک ارائه‌شده و اختیار قانونی خود برای ثبت این دارایی را تأیید می‌کنم.</span></label><button className="tk-primary" disabled={busy||autosaving||!docsComplete||!submitConsent} onClick={submit}>{busy?'در حال ذخیره و ارسال…':'ذخیره و ارسال پرونده'}<ArrowLeft size={18}/></button></div>
    {!docsComplete&&<p className="tk-save-note">پیش از ارسال، مدارک ضروری را تکمیل و مدارک ردشده یا نیازمند اصلاح را جایگزین کنید.</p>}
   </>}
   {step===3&&current&&!canEdit&&<><p className="tk-lead">وضعیت فعلی پرونده</p><div className="tk-review-overview"><StatusBadge status={current.status}/><span>آخرین تغییر: {date(current.updated_at)}</span><button className="tk-quiet" onClick={refresh} disabled={busy}><RefreshCw size={17}/> به‌روزرسانی</button></div>{current.message&&<output className="tk-alert tk-alert-info"><FileText size={20}/>{current.message}</output>}<ReviewCards request={current}/>{current.documents.some(doc=>!validDocument(doc.status))&&<div className="tk-corrections"><h3>مدارک ردشده یا نیازمند اصلاح</h3>{current.documents.filter(doc=>!validDocument(doc.status)).map(doc=><p key={doc.id}><strong>{activeType?.documents.find(slot=>slot.key===doc.slot)?.label||doc.name}:</strong> {doc.message||'نسخهٔ اصلاح‌شدهٔ مدرک را بارگذاری کنید.'}</p>)}</div>}<details className="tk-application-summary"><summary>مشاهدهٔ اطلاعات و مدارک ثبت‌شده <ChevronDown size={18}/></summary><dl>{getAssetFields(type).filter(field=>current.fields[field.key]).map(field=><div key={field.key}><dt>{field.label}</dt><dd>{field.type==='number'?fa(current.fields[field.key]):field.options?.find(option=>option.value===current.fields[field.key])?.label||current.fields[field.key]}</dd></div>)}</dl><div className="tk-summary-files">{current.documents.map(doc=><a key={doc.id} href={`/api/tokenization/documents?id=${encodeURIComponent(current.id)}&document=${encodeURIComponent(doc.id)}`} target="_blank" rel="noreferrer"><Download size={15}/>{doc.name}</a>)}</div></details></>}
   {step===4&&current&&current.tokenomics&&<TokenomicsView request={current} consent={acceptConsent} setConsent={setAcceptConsent} busy={busy} accept={accept} refresh={refresh}/>}
   <div className="tk-wizard-controls">
    {canEdit&&<div className="tk-draft-bar"><p className={dirty?'tk-save-note':'tk-muted'}>{dirty?'تغییرات در حال نگهداری هستند؛ پیش از بستن صفحه، وضعیت ذخیره را بررسی کنید.':current?'آخرین اطلاعات در حساب شما ذخیره شده است.':'با جابه‌جایی بین مراحل، اطلاعات حفظ می‌شوند. با رفتن به مرحلهٔ بعد، پیش‌نویس خودکار ذخیره می‌شود.'}</p><button type="button" className="tk-secondary" onClick={saveDraft} disabled={busy||autosaving||!type}>{busy?'در حال ذخیره…':'ذخیرهٔ پیش‌نویس'}<FileCheck2 size={17}/></button></div>}
    <nav className="tk-stage-actions tk-stage-navigation" aria-label="جابه‌جایی مراحل توکنایزیشن"><button type="button" className="tk-secondary" onClick={()=>goStep(step-1)} disabled={busy}><ArrowRight size={18}/> مرحله قبل</button><span className="tk-muted">{fa(step+1)} از ۵</span><button type="button" className="tk-primary" onClick={()=>goStep(step+1)} disabled={busy||step===4||step===0&&!type||step===3&&!hasProposal}>مرحله بعد <ArrowLeft size={18}/></button></nav>
    {step===3&&!hasProposal&&<p className="tk-navigation-note">مرحلهٔ بعد پس از بررسی مدیریت و آماده‌شدن توکنومیکس فعال می‌شود.</p>}
    {step===4&&<p className="tk-navigation-note">این آخرین مرحله است؛ نتیجهٔ تأیید و صدور در همین صفحه نمایش داده می‌شود.</p>}
   </div></div><div className="tk-bottom-note"><ShieldCheck size={16}/><span>درخواست صدور پس از تأییدهای لازم و تأیید نهایی شما ثبت می‌شود؛ نتیجه پس از صدور واقعی و بررسی رسید نمایش داده خواهد شد.</span></div></section></div>
  </>}
 </>;
}

function ReviewCards({request}:{request:TokenizationRequest}){return <div className="tk-review-cards">{(['legal','financial','technical'] as const).map((layer,index)=>{const review=request.reviews[layer];return <article className={`tk-review-card tk-review-${review.status}`} key={layer}><TokenizationStepIcon stage={index===0?1:index===1?2:4}/><div><h3>{layer==='legal'?'بررسی حقوقی و مالکیت':layer==='financial'?'ارزیابی مالی و ارزش‌گذاری':'بررسی فنی و شرایط انتشار'}</h3><span className="tk-review-state">{review.status==='approved'?<CheckCircle2 size={17}/>:<Clock3 size={17}/>} {reviewLabels[review.status]}</span><p>{review.message|| (request.status==='draft'?'پس از تکمیل و ارسال پرونده بررسی می‌شود.':'نتیجهٔ بررسی این بخش پس از ثبت نظر کارشناس نمایش داده می‌شود.')}</p>{review.updated_at&&<small>{date(review.updated_at)}</small>}</div></article>;})}</div>;}

function StatusBadge({status}:{status:TokenizationRequest['status']}){return <span className={`tk-status tk-status-${status}`}><i/>{statusLabels[status]}</span>;}
function AssetSymbol({name}:{name:string}){const Icon=assetIcons[name]||Building2;return <Icon size={28}/>;}
function AssetInput({field,value,onChange,invalid}:{field:AssetField;value:string;onChange:(value:string)=>void;invalid:boolean}){
 const id=`tk-field-${field.key}`;
 const props={id,required:field.required,'aria-invalid':invalid,'aria-describedby':[field.unit?`${id}-unit`:'',invalid?'tk-validation-error':''].filter(Boolean).join(' ')||undefined};
 return <label className={`tk-field ${field.type==='textarea'?'tk-field-wide':''}`} htmlFor={id}><span>{field.label}{field.required&&<b aria-label="ضروری">*</b>}</span>{field.type==='number'?<LocalizedNumberInput {...props} value={value} onValueChange={onChange} inputMode={field.integer?'numeric':'decimal'} maxLength={(field.maxIntegerDigits??30)+(field.integer?0:1+(field.maxFractionDigits??18))}/>:field.type==='select'?<select {...props} value={value} onChange={event=>onChange(event.target.value)}><option value="">انتخاب کنید…</option>{field.options?.map(option=><option key={option.value} value={option.value}>{option.label}</option>)}</select>:field.type==='textarea'?<textarea {...props} value={value} rows={4} maxLength={field.maxLength??500} onChange={event=>onChange(event.target.value)}/>:<input {...props} type={field.type==='date'?'date':'text'} value={value} maxLength={field.maxLength??500} onChange={event=>onChange(event.target.value)}/>} {field.unit&&<small id={`${id}-unit`}>{field.unit}</small>}</label>;
}
function TokenomicsView({request,consent,setConsent,busy,accept,refresh}:{request:TokenizationRequest;consent:boolean;setConsent:(value:boolean)=>void;busy:boolean;accept:()=>void;refresh:()=>void}){
 const token=request.tokenomics!;
 const ready=proposalReady(request);
 const confirmed=request.status==='issued'&&request.issuance?.status==='confirmed'&&request.accepted_proposal_version===request.proposal_version;
 const accepted=(request.status==='issuance_pending'||request.status==='issued')&&request.accepted_proposal_version===request.proposal_version;
 const failed=accepted&&request.issuance?.status==='failed';
 const issuanceTitle=confirmed?'توکن به کیف پول داخلی شما واریز شد':failed?'صدور به پیگیری نیاز دارد':accepted?'تأیید شما ثبت شد؛ صدور در حال پیگیری است':'این پیشنهاد هنوز آمادهٔ تأیید نهایی نیست';
 const issuanceText=confirmed?'ثبت واریز تأیید شده است. موجودی را در کیف پول پلانک مشاهده کنید.':accepted?'پس از تکمیل صدور و دریافت تأیید معتبر، نتیجه و موجودی توکن در حساب شما نمایش داده می‌شود.':'آخرین وضعیت پرونده و توضیحات بررسی‌ها را مطالعه کنید. پذیرش پس از تکمیل بررسی‌ها و ارائهٔ نسخهٔ معتبر پیشنهاد در دسترس است.';
 const download=()=>{
  const text=['توکنومیکس دارایی — پلانک',`پرونده: ${request.id}`,`نسخهٔ پیشنهاد: ${request.proposal_version}`,`دارایی: ${request.fields.title||''}`,`نام توکن: ${token.name}`,`نماد: ${token.symbol}`,`تعداد کل: ${token.total_supply}`,`اعشار: ${token.decimals}`,`قیمت هر توکن (ریال): ${token.unit_price_rial}`,`شبکه: ${token.network} (${token.chain_id})`,'مقصد: کیف پول داخلی پلانک؛ موجودی پس از صدور تا اجرای شرایط آزادسازی قفل است.','استاندارد قرارداد: ERC-20','تخصیص اولیه: همهٔ توکن‌ها تا فعال‌سازی فرایند آزادسازی در کیف پول داخلی قفل می‌مانند.',`حقوق دارنده: ${token.rights}`,`شرایط انتقال: ${token.transfer_policy}`,`شرایط بازخرید: ${token.redemption_policy}`,`ریسک‌ها: ${token.risk_disclosure}`,'تخصیص توکن‌ها:',...token.allocations.map(item=>`${item.label}: ${item.percent}% — قفل ${item.lock_months} ماه`)].join('\n\n');
  const url=URL.createObjectURL(new Blob(['\uFEFF',text],{type:'text/plain;charset=utf-8'}));const link=document.createElement('a');link.href=url;link.download=`planck-tokenomics-${request.id}-v${request.proposal_version}.txt`;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
 };
 return <><div className="tk-token-hero"><div><span className="tk-eyebrow">پیشنهاد توکنومیکس · نسخهٔ {fa(request.proposal_version)}</span><h3>{token.name}</h3><bdi>{token.symbol}</bdi></div><TokenizationStageScene stage={2}/></div><div className="tk-token-metrics"><div><span>تعداد کل توکن</span><strong>{fa(token.total_supply)}</strong></div><div><span>قیمت هر توکن</span><strong>{fa(token.unit_price_rial)}<small> ریال</small></strong></div><div><span>شبکهٔ انتشار</span><strong>{token.network}</strong><small>شناسه {fa(token.chain_id)} · اعشار {fa(token.decimals)} · ERC-20</small></div></div><div className="tk-wallet-destination"><Wallet size={24}/><span><strong>کیف پول داخلی پلانک شما</strong><small>پس از تأیید صدور واقعی، کل تعداد توکن به‌صورت قفل‌شده ثبت می‌شود؛ آزادسازی و امکان استفاده به فعال‌شدن فرایند مربوط وابسته است.</small></span></div><section className="tk-allocation"><h3>چیدمان و شرایط تخصیص</h3><p className="tk-muted">این جدول برنامهٔ تخصیص است. پس از صدور، توکن‌ها ابتدا در کیف پول داخلی شما قفل می‌شوند؛ عرضه، انتقال و آزادسازی آن‌ها نیازمند اجرای شرایط تأییدشدهٔ همین پرونده است.</p><div className="tk-allocation-bar" aria-hidden="true">{token.allocations.map((allocation,index)=><i key={index} style={{width:`${allocation.percent}%`,background:['#38cbb6','#9297f3','#e8b166','#6bb4eb','#d68fc5'][index%5]}}/>)}</div><div className="tk-table-wrap"><table><thead><tr><th>بخش</th><th>سهم</th><th>دورهٔ قفل پیشنهادی</th></tr></thead><tbody>{token.allocations.map((allocation,index)=><tr key={index}><td><i style={{background:['#38cbb6','#9297f3','#e8b166','#6bb4eb','#d68fc5'][index%5]}}/>{allocation.label}</td><td>{fa(allocation.percent)}٪</td><td>{allocation.lock_months?`${fa(allocation.lock_months)} ماه`:'بدون دورهٔ قفل'}</td></tr>)}</tbody></table></div></section><div className="tk-proposal-conditions">{[{title:'حقوق دارندهٔ توکن',text:token.rights},{title:'شرایط انتقال و عرضه',text:token.transfer_policy},{title:'شرایط بازخرید',text:token.redemption_policy},{title:'ریسک‌ها و تعهدات',text:token.risk_disclosure}].map(item=><article key={item.title}><h3>{item.title}</h3><p>{item.text}</p></article>)}</div><button className="tk-secondary tk-download-proposal" onClick={download}><Download size={18}/> دریافت متن کامل این توکنومیکس</button>
 {ready?<section className="tk-submit-box"><h3>تأیید نهایی صاحب دارایی</h3><p>با تأیید این نسخه، درخواست صدور بر اساس مشخصات بالا ثبت می‌شود. پس از تأیید صدور واقعی، همهٔ توکن‌ها ابتدا در کیف پول داخلی قفل می‌مانند. پیش از تأیید، تعداد توکن، حقوق، تخصیص‌ها و شرایط آزادسازی و عرضه را بررسی کنید.</p><label className="tk-consent"><input type="checkbox" checked={consent} onChange={event=>setConsent(event.target.checked)} disabled={busy}/><span>توکنومیکس نسخهٔ {fa(request.proposal_version)} و شرایط آن را مطالعه کرده‌ام و صدور توکن و واریز به کیف پول داخلی پلانک خود را تأیید می‌کنم.</span></label><button className="tk-primary" onClick={accept} disabled={!consent||busy}>{busy?'در حال ثبت تأیید…':'تأیید توکنومیکس و درخواست صدور'}<ShieldCheck size={18}/></button></section>:<section className={`tk-issuance tk-issuance-${request.status}`}><div className="tk-issuance-icon">{confirmed?<CheckCircle2 size={34}/>:<Clock3 size={34}/>}</div><h3>{issuanceTitle}</h3><p>{request.issuance?.message||request.message||issuanceText}</p>{request.accepted_proposal_version&&<small>نسخهٔ تأییدشدهٔ شما: {fa(request.accepted_proposal_version)}</small>}{confirmed&&request.issuance&&<dl>{request.issuance.amount&&<div><dt>تعداد واریزشده</dt><dd>{fa(request.issuance.amount)}</dd></div>}{request.issuance.confirmed_at&&<div><dt>زمان تأیید</dt><dd>{date(request.issuance.confirmed_at)}</dd></div>}{request.issuance.transaction_hash&&<div><dt>شناسهٔ تراکنش</dt><dd className="tk-hash" dir="ltr">{request.issuance.transaction_hash}</dd></div>}</dl>}<div className="tk-issuance-actions">{confirmed&&<Link className="tk-primary" href="/wallet">مشاهدهٔ کیف پول <Wallet size={18}/></Link>}<button className="tk-secondary" onClick={refresh} disabled={busy}><RefreshCw size={17}/> دریافت آخرین وضعیت</button></div></section>}
 </>;
}
