'use client';

import '@/app/account-mobile-tabs.css';
import {useState,type ReactNode} from 'react';
import {DashboardCatalogContext} from './dashboard-catalog-context';
import Link from './account-link';
import {usePathname} from 'next/navigation';
import {UserRound,Wallet,LayoutGrid,ShieldCheck,CreditCard,Settings2,BellRing,Gift,Code2,ArrowUpRight,History,Coins,HandCoins,Headphones,LogOut,ChevronLeft,Inbox,LockKeyhole,ArrowLeft,ArrowDownLeft,ChartNoAxesCombined,RefreshCw,Ticket} from 'lucide-react';
import {SiteFrame,useSite} from './site-shell';
import {UserAvatar} from './user-avatar';
import {IdentityVerification} from './identity-verification';
import {AccountLoadingLine,DashboardLoading} from './dashboard-loading';
import {Sidebar,SidebarProvider,SidebarContent,SidebarHeader,SidebarMenu,SidebarMenuItem,SidebarMenuButton,SidebarFooter} from './ui/sidebar';
import {dashboardNumber,type DashboardArea} from '@/lib/dashboard';
import {dashboardLabel} from '@/lib/dashboard-copy';
import type {Catalog} from '@/lib/catalog';

const icons={profile:UserRound,banks:CreditCard,security:ShieldCheck,settings:Settings2,alerts:BellRing,referrals:Gift,api:Code2,notifications:Inbox,tickets:Ticket,overview:LayoutGrid,assets:Wallet,deposit:ArrowDownLeft,withdraw:ArrowUpRight,transactions:History,orders:ChartNoAxesCombined,credit:ArrowUpRight,staking:Coins,'instant-credit':HandCoins};
const menu={account:['profile','banks','security','settings','alerts','referrals','api','notifications','tickets'],wallet:['assets','deposit','withdraw','transactions','orders','credit','staking','instant-credit']};

// The member layout persists while navigating between profile and wallet pages.
export function CustomerDashboardLayout({catalog,children}:{catalog:Catalog;children:ReactNode}){
 return <DashboardCatalogContext.Provider value={catalog}><SiteFrame content={catalog.content} mode={catalog.mode} dashboard detail><DashboardShell>{children}</DashboardShell></SiteFrame></DashboardCatalogContext.Provider>;
}

function DashboardShell({children}:{children:ReactNode}){
 const pathname=usePathname()||'/account';
 const area:DashboardArea=pathname.startsWith('/wallet')?'wallet':'account';
 const routeSection=pathname.split('/')[2];
 const section=area==='wallet'&&(!routeSection||routeSection==='overview')?'assets':routeSection||'profile';
 const {user,sessionStatus,customer,open,locale,logout}=useSite();
 const [signingOut,setSigningOut]=useState(false),[error,setError]=useState('');
 const t=(key:string)=>dashboardLabel(key,locale);
 const data=customer.data,title=t(section),Icon=icons[section as keyof typeof icons]||UserRound;
 const fullName=[data?.account.first_name,data?.account.last_name].filter(Boolean).join(' ')||user?.name||user?.username||t('personal');
 const waiting=!user&&sessionStatus==='loading';
 async function signOut(){setSigningOut(true);setError('');try{await logout()}catch(e){setError((e as Error).message)}finally{setSigningOut(false)}}
 return <main id="dashboard" className="customer-dashboard" dir={locale==='en'?'ltr':'rtl'}>
  <div className="dash-breadcrumb"><Link href="/">پلانک</Link><ChevronLeft size={13}/><Link href={`/${area}`}>{t(area)}</Link><ChevronLeft size={13}/><span>{title}</span></div>
  <SidebarProvider className="dashboard-layout" defaultOpen>
   <Sidebar collapsible="none" className="dashboard-sidebar">
    <SidebarHeader>
     <Link href="/account" scroll={false} className="dash-sidebar-user">{user?<UserAvatar name={fullName} userId={user.id} path={data?.account.avatar_path}/>:<span className={waiting?'skeleton-orb':''}><UserRound size={21}/></span>}<div><strong>{waiting?<span className="dashboard-name-placeholder"/>:fullName}</strong><small>{t('personal')}</small></div></Link>
     <div className="dash-area-switch"><Link href="/account" scroll={false} aria-current={area==='account'?'page':undefined}>{t('account')}</Link><Link href="/wallet" scroll={false} aria-current={area==='wallet'?'page':undefined}>{t('wallet')}</Link></div>
    </SidebarHeader>
    <SidebarContent><nav aria-label={t(area)}><SidebarMenu className="dash-section-links" data-area={area}>{menu[area].map(key=>{const ItemIcon=icons[key as keyof typeof icons];return <SidebarMenuItem key={key}><SidebarMenuButton className="dash-section-link" isActive={section===key} aria-label={t(key)} title={t(key)} render={<Link href={`/${area}/${key}`} scroll={false} aria-current={section===key?'page':undefined}/>}><ItemIcon size={19} aria-hidden="true"/><span className="dash-section-label">{t(key)}</span>{key==='notifications'&&!!data?.unread_count&&<small>{dashboardNumber(data.unread_count,locale,0)}</small>}</SidebarMenuButton></SidebarMenuItem>})}</SidebarMenu></nav></SidebarContent>
    <SidebarFooter><Link href="/#faq"><Headphones size={18}/>{t('support')}</Link><Link href="/#market"><ArrowLeft size={18}/>{t('market')}</Link>{user&&<button onClick={()=>void signOut()} disabled={signingOut}><LogOut size={18}/>{t('logout')}</button>}</SidebarFooter>
   </Sidebar>
   <div className="dashboard-main">
    <header className="dash-page-heading"><div><span className="dash-eyebrow">PLANCK / {area==='wallet'?'WALLET':'ACCOUNT'}</span><h1><Icon size={26}/>{title}</h1></div><span className="dash-personal-label"><LockKeyhole size={13}/>{t('personal')}</span><AccountLoadingLine locale={locale} active={waiting||!!user&&customer.refreshing}/></header>
    {error&&<p role="alert" className="dash-error">{error}</p>}
    {area==='account'&&section==='tickets'?children:user?<><IdentityVerification key={user.id} userId={user.id} onChanged={customer.reload}/>{children}</>:waiting?<><div className="identity-entry dashboard-identity-placeholder" aria-hidden="true"><i className="skeleton-orb"/><i/></div><DashboardLoading locale={locale}/></>:<section className="dash-card dashboard-sign-in"><LockKeyhole size={30}/><h2>{sessionStatus==='error'?'ارتباط با حساب برقرار نشد':'به داشبورد پلانک وارد شوید'}</h2><p>پروفایل، کیف پول و فعالیت‌های حساب شما در یک مکان.</p>{sessionStatus==='error'?<button className="dash-primary" onClick={()=>window.dispatchEvent(new Event('planck:session-refresh'))}><RefreshCw size={17}/>{t('retry')}</button>:<button className="dash-primary" onClick={()=>open('login')}>ورود | ثبت‌نام<ArrowLeft size={18}/></button>}</section>}
   </div>
  </SidebarProvider>
 </main>;
}
