Files
2026-09-15 20:37:49 +03:30

21 lines
2.2 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use client';
import { useEffect, useRef, useState } from 'react';
import { ChevronDown, LogOut, Settings, UserRound } from 'lucide-react';
import { apiUrl, BUSINESS_URL, CUSTOMER_URL } from '../lib/meshkee-api';
function readCookie(name) {
const entries = Object.fromEntries(document.cookie.split(';').flatMap((part) => { const index=part.indexOf('='); return index<0?[]:[[part.slice(0,index).trim(),part.slice(index+1)]]; }));
if (entries[name]) return decodeURIComponent(entries[name]);
const count = Number(entries[`${name}_n`]);
if (!Number.isFinite(count) || count < 1) return '';
return decodeURIComponent(Array.from({length:count},(_,index)=>entries[`${name}_${index}`]||'').join(''));
}
export default function AccountMenu() {
const [user,setUser]=useState(null); const [open,setOpen]=useState(false); const root=useRef(null);
useEffect(()=>{const token=readCookie('meshkee_customer_access_token');if(!token)return;fetch(apiUrl('/auth/me'),{headers:{Authorization:`Bearer ${token}`,Accept:'application/json'}}).then(response=>response.ok?response.json():null).then(data=>setUser(data?.user||null)).catch(()=>{});},[]);
useEffect(()=>{if(!open)return;const close=(event)=>{if(!root.current?.contains(event.target))setOpen(false)};document.addEventListener('pointerdown',close);return()=>document.removeEventListener('pointerdown',close)},[open]);
const name=user?.firstName||user?.name||user?.displayName; const roles=[user?.role,...(Array.isArray(user?.roles)?user.roles:[])].filter(Boolean).map(String); const admin=Boolean(user?.isAdmin||roles.some(role=>/admin|owner|manager/i.test(role)));
if(!user)return <a className="account-trigger" href={CUSTOMER_URL} aria-label="ورود یا حساب کاربری"><UserRound/></a>;
return <div className="account-menu" ref={root}><button className="account-trigger account-user" onClick={()=>setOpen(value=>!value)} aria-expanded={open}><UserRound/><span>{name||'کاربر'} عزیز</span><ChevronDown size={15}/></button>{open&&<div className="account-dropdown"><a href={CUSTOMER_URL}><UserRound/>پروفایل من</a>{admin&&<a href={BUSINESS_URL}><Settings/>مدیریت وب‌سایت</a>}<a href={`${CUSTOMER_URL}/logout`}><LogOut/>خروج</a></div>}</div>;
}