// profiling.jsx — Shahdad identity center and role-based profiling prototype.
// Test-stage persistence is intentionally local. Replace with authenticated APIs later.

const SH_PROFILE_KEY = "shahdad_profile_v31_81";

const SH_ROLE_TYPES = [
  { id:"natural", icon:"user", fa:"شخص حقیقی", en:"Individual", hintFa:"هویت پایه و مشترک همه نقش‌ها", hintEn:"Shared core identity" },
  { id:"company", icon:"building", fa:"شرکت خصوصی", en:"Private company", hintFa:"مدیرعامل یا رئیس هیئت‌مدیره", hintEn:"Director-led organization" },
  { id:"public", icon:"building", fa:"نهاد عمومی", en:"Public entity", hintFa:"سازمان، وزارتخانه یا شهرداری", hintEn:"Government or public body" },
  { id:"charity", icon:"heart", fa:"نهاد حمایتی", en:"Supporting institution", hintFa:"مؤسسه عام‌المنفعه یا حمایتی", hintEn:"Public-benefit organization" },
  { id:"lawyer", icon:"scale", fa:"وکیل یا کارآموز", en:"Lawyer / trainee", hintFa:"پروفایل حرفه‌ای و پروانه", hintEn:"Professional legal profile" },
  { id:"expert", icon:"microscope", fa:"کارشناس", en:"Expert", hintFa:"رسمی یا متخصص تأییدشده", hintEn:"Official or approved expert" },
  { id:"judge", icon:"gavel", fa:"قاضی", en:"Judge", hintFa:"شاغل یا بازنشسته", hintEn:"Serving or retired judge" },
  { id:"arbitrator", icon:"handshake", fa:"داور", en:"Arbitrator", hintFa:"نقش مستقل با تأیید ادمین ریشه", hintEn:"Root-approved independent role" },
];

const SH_STATUS = {
  incomplete: { fa:"ناقص", en:"Incomplete", tone:"warn" },
  correction: { fa:"نیازمند اصلاح", en:"Needs correction", tone:"danger" },
  pending: { fa:"در انتظار اعتبارسنجی", en:"Under review", tone:"info" },
  verified: { fa:"تأییدشده", en:"Verified", tone:"ok" },
  limited: { fa:"دسترسی محدود", en:"Limited", tone:"warn" },
};

const shDefaultProfile = () => ({
  identity: {
    firstName:"", lastName:"", nationalId:"", birthDate:"", mobile:"", email:"",
    province:"", city:"", address:"", locked:false,
  },
  activeRole:"natural",
  roles:[{ id:"natural", status:"incomplete", completion:28, filing:"SH-NAT-DRAFT", wallet:0 }],
  details:{ natural:{}, lawyer:{ license:"", authority:"bar", supervisor:"" }, expert:{ license:"", specialty:"" }, company:{ legalName:"", nationalCode:"", registrationNo:"" } },
  savedAt:null,
});

const shLoadProfile = () => {
  try {
    const raw = localStorage.getItem(SH_PROFILE_KEY);
    if (raw) return { ...shDefaultProfile(), ...JSON.parse(raw) };
  } catch (e) {}
  return shDefaultProfile();
};

const shMaskId = (value) => value ? `${value.slice(0,3)}••••${value.slice(-3)}` : "ثبت نشده";
const shLatinDigits = (value="") => String(value).replace(/[۰-۹]/g,(d)=>"۰۱۲۳۴۵۶۷۸۹".indexOf(d)).replace(/[٠-٩]/g,(d)=>"٠١٢٣٤٥٦٧٨٩".indexOf(d));
const shOnlyDigits = (value="",maxLength=30) => shLatinDigits(value).replace(/\D/g,"").slice(0,maxLength);
const shDateInput = (value="") => shLatinDigits(value).replace(/[^\d/]/g,"").slice(0,10);
const shValidNationalId = (value="") => {
  const digits = shOnlyDigits(value,10);
  if (!/^\d{10}$/.test(digits) || /^(\d)\1{9}$/.test(digits)) return false;
  const sum = digits.slice(0,9).split("").reduce((total,digit,index)=>total+(Number(digit)*(10-index)),0);
  const remainder = sum % 11;
  return Number(digits[9]) === (remainder < 2 ? remainder : 11-remainder);
};
const shValidBirthDate = (value="") => {
  const match = shDateInput(value).match(/^(13\d{2}|14\d{2})\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/);
  if (!match) return false;
  const year = Number(match[1]);
  const month = Number(match[2]);
  const day = Number(match[3]);
  return day <= shPersianMonthLength(year,month);
};

const shPad2 = (value) => String(value).padStart(2,"0");
const shPersianFormatter = new Intl.DateTimeFormat("en-US-u-ca-persian",{timeZone:"Asia/Tehran",year:"numeric",month:"numeric",day:"numeric"});
const shPersianDateParts = (date) => Object.fromEntries(shPersianFormatter.formatToParts(date).filter((part)=>["year","month","day"].includes(part.type)).map((part)=>[part.type,Number(part.value)]));
const shPersianDateCache = new Map();
const shPersianToGregorian = (year,month,day) => {
  const key = `${year}/${month}/${day}`;
  if (shPersianDateCache.has(key)) return new Date(shPersianDateCache.get(key));
  const cursor = new Date(Date.UTC(year+621,1,15,12));
  for (let i=0;i<430;i+=1) {
    const parts = shPersianDateParts(cursor);
    if (parts.year===year && parts.month===month && parts.day===day) {
      shPersianDateCache.set(key,cursor.toISOString());
      return new Date(cursor);
    }
    cursor.setUTCDate(cursor.getUTCDate()+1);
  }
  return null;
};
const shPersianMonthLength = (year,month) => month<=6 ? 31 : month<=11 ? 30 : (shPersianToGregorian(year,12,30) ? 30 : 29);
const shParsePersianDate = (value="") => {
  const match = shDateInput(value).match(/^(13\d{2}|14\d{2})\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/);
  return match ? {year:Number(match[1]),month:Number(match[2]),day:Number(match[3])} : null;
};

const ProfileIdentityField = ({ id,label,type="text",inputMode,placeholder,optional=false,autoComplete,maxLength,numeric=false,date=false,helper,draft,setDraft,errors,setErrors,validateIdentity,lang }) => {
  const locked = draft.identity.locked && ["firstName","lastName","nationalId","birthDate"].includes(id);
  const commitValue = (value) => {
    setDraft((current)=>({...current,identity:{...current.identity,[id]:value}}));
    if (errors[id]) setErrors((old)=>{const next={...old};delete next[id];return next;});
  };
  const input = <input id={`pf-${id}`} type={type} inputMode={inputMode} autoComplete={autoComplete} value={draft.identity[id]||""}
    placeholder={placeholder||""} maxLength={maxLength} readOnly={locked}
    aria-invalid={!!errors[id]} aria-describedby={(errors[id]||helper)?`pf-${id}-help`:undefined}
    onChange={(e)=>commitValue(numeric?shOnlyDigits(e.target.value,maxLength):date?shDateInput(e.target.value):e.target.value)}
    onBlur={()=>{const fieldError=validateIdentity()[id];setErrors((old)=>{const next={...old};if(fieldError)next[id]=fieldError;else delete next[id];return next;});}}/>;
  return <div className={"pf-field"+(errors[id]?" has-error":"")}>
    <label htmlFor={`pf-${id}`}>{label}{!optional&&<i>*</i>}</label>
    {date?<div className="pf-date-control">{input}<PersianBirthDatePicker value={draft.identity[id]||""} onSelect={commitValue} lang={lang} disabled={locked}/></div>:input}
    {errors[id]&&<small id={`pf-${id}-help`} role="alert">{errors[id]}</small>}
    {!errors[id]&&helper&&<small id={`pf-${id}-help`} className="pf-helper">{helper}</small>}
  </div>;
};

const PersianBirthDatePicker = ({ value,onSelect,lang,disabled }) => {
  const fa = lang!=="en";
  const rootRef = React.useRef(null);
  const today = React.useMemo(()=>shPersianDateParts(new Date()),[]);
  const initial = shParsePersianDate(value) || today;
  const [open,setOpen] = React.useState(false);
  const [viewYear,setViewYear] = React.useState(initial.year);
  const [viewMonth,setViewMonth] = React.useState(initial.month);
  const selected = shParsePersianDate(value);
  const monthsFa = ["فروردین","اردیبهشت","خرداد","تیر","مرداد","شهریور","مهر","آبان","آذر","دی","بهمن","اسفند"];
  const monthsEn = ["Farvardin","Ordibehesht","Khordad","Tir","Mordad","Shahrivar","Mehr","Aban","Azar","Dey","Bahman","Esfand"];
  const weekdays = fa?["ش","ی","د","س","چ","پ","ج"]:["Sa","Su","Mo","Tu","We","Th","Fr"];
  const years = React.useMemo(()=>Array.from({length:today.year-1299},(_,index)=>today.year-index),[today.year]);
  const firstDate = shPersianToGregorian(viewYear,viewMonth,1);
  const offset = firstDate ? (firstDate.getUTCDay()+1)%7 : 0;
  const dayCount = shPersianMonthLength(viewYear,viewMonth);
  React.useEffect(()=>{
    if (!open) return undefined;
    const closeOutside = (event)=>{if(rootRef.current&&!rootRef.current.contains(event.target))setOpen(false);};
    document.addEventListener("pointerdown",closeOutside);
    return ()=>document.removeEventListener("pointerdown",closeOutside);
  },[open]);
  const moveMonth = (delta) => {
    let nextMonth=viewMonth+delta;
    let nextYear=viewYear;
    if(nextMonth===0){nextMonth=12;nextYear-=1;}
    if(nextMonth===13){nextMonth=1;nextYear+=1;}
    if(nextYear>=1300&&nextYear<=today.year){setViewMonth(nextMonth);setViewYear(nextYear);}
  };
  return <div className="pf-calendar-root" ref={rootRef} onKeyDown={(event)=>{if(event.key==="Escape")setOpen(false);}}>
    <button id="pf-birthDate-calendar" className="pf-date-trigger" type="button" disabled={disabled} aria-haspopup="dialog" aria-expanded={open} aria-controls="pf-birthDate-popover" aria-label={fa?"انتخاب تاریخ تولد از تقویم":"Choose birth date from calendar"} onClick={()=>setOpen((current)=>{if(!current){const typed=shParsePersianDate(value);if(typed){setViewYear(typed.year);setViewMonth(typed.month);}}return !current;})}><Ic.cal size={18}/></button>
    {open&&<div id="pf-birthDate-popover" className="pf-calendar" role="dialog" aria-label={fa?"تقویم انتخاب تاریخ تولد":"Birth date calendar"}>
      <div className="pf-calendar-head"><button type="button" onClick={()=>moveMonth(-1)} aria-label={fa?"ماه قبل":"Previous month"}><Ic.chevR size={15}/></button><strong>{fa?"انتخاب تاریخ تولد":"Select birth date"}</strong><button type="button" onClick={()=>moveMonth(1)} disabled={viewYear===today.year&&viewMonth===today.month} aria-label={fa?"ماه بعد":"Next month"}><Ic.chevL size={15}/></button></div>
      <div className="pf-calendar-selects"><select aria-label={fa?"ماه":"Month"} value={viewMonth} onChange={(event)=>setViewMonth(Number(event.target.value))}>{(fa?monthsFa:monthsEn).map((name,index)=><option key={name} value={index+1}>{name}</option>)}</select><select aria-label={fa?"سال":"Year"} value={viewYear} onChange={(event)=>setViewYear(Number(event.target.value))}>{years.map((year)=><option key={year} value={year}>{year}</option>)}</select></div>
      <div className="pf-calendar-weekdays" aria-hidden="true">{weekdays.map((day)=><span key={day}>{day}</span>)}</div>
      <div className="pf-calendar-days">{Array.from({length:offset},(_,index)=><span key={`blank-${index}`}></span>)}{Array.from({length:dayCount},(_,index)=>index+1).map((day)=>{const dateValue=`${viewYear}/${shPad2(viewMonth)}/${shPad2(day)}`;const isSelected=selected&&selected.year===viewYear&&selected.month===viewMonth&&selected.day===day;const isToday=today.year===viewYear&&today.month===viewMonth&&today.day===day;return <button key={day} type="button" data-date={dateValue} className={(isSelected?"selected ":"")+(isToday?"today":"")} aria-pressed={!!isSelected} aria-label={dateValue} onClick={()=>{onSelect(dateValue);setOpen(false);}}>{day}</button>})}</div>
    </div>}
  </div>;
};

const ProfilingView = ({ lang }) => {
  const session = useSession();
  const fa = lang !== "en";
  const T = (a,b) => fa ? a : b;
  const [profile,setProfile] = React.useState(shLoadProfile);
  const [wizard,setWizard] = React.useState(null);
  const [step,setStep] = React.useState(0);
  const [draft,setDraft] = React.useState(null);
  const [errors,setErrors] = React.useState({});
  const [savedFlash,setSavedFlash] = React.useState(false);
  const [consent,setConsent] = React.useState(false);

  React.useEffect(() => {
    try { localStorage.setItem(SH_PROFILE_KEY, JSON.stringify(profile)); } catch (e) {}
  }, [profile]);

  const role = SH_ROLE_TYPES.find((x)=>x.id===profile.activeRole) || SH_ROLE_TYPES[0];
  const roleState = profile.roles.find((x)=>x.id===role.id) || profile.roles[0];
  const status = SH_STATUS[roleState.status] || SH_STATUS.incomplete;
  const identity = profile.identity;
  const fullName = [identity.firstName,identity.lastName].filter(Boolean).join(" ") || session?.displayName || T("کاربر شهداد","Shahdad member");
  const initials = fullName.split(/\s+/).slice(0,2).map((x)=>x[0]).join("") || "ش";

  const setActiveRole = (id) => {
    setProfile((p)=>({ ...p, activeRole:id }));
    if (session?.setRole) session.setRole(id === "natural" ? "user" : id);
  };

  const beginWizard = (roleId=null) => {
    const isAdd = roleId === "__add__";
    const firstAvailable = SH_ROLE_TYPES.find((x)=>!profile.roles.some((r)=>r.id===x.id));
    const chosen = isAdd ? (firstAvailable?.id || profile.activeRole) : (roleId || profile.activeRole);
    setWizard(isAdd ? "add" : "edit");
    setStep(isAdd ? 0 : 1);
    setErrors({});
    setConsent(false);
    setDraft({ roleId:chosen, identity:{...profile.identity}, details:{...(profile.details[chosen]||{})} });
  };

  const validateIdentity = () => {
    const nextErrors = {};
    const firstName = String(draft.identity.firstName||"").trim();
    const lastName = String(draft.identity.lastName||"").trim();
    if (firstName.length < 2) nextErrors.firstName=T("نام باید حداقل ۲ حرف باشد.","First name must contain at least 2 characters.");
    else if (/\d/.test(shLatinDigits(firstName))) nextErrors.firstName=T("نام نباید شامل عدد باشد.","First name cannot contain numbers.");
    if (lastName.length < 2) nextErrors.lastName=T("نام خانوادگی باید حداقل ۲ حرف باشد.","Last name must contain at least 2 characters.");
    else if (/\d/.test(shLatinDigits(lastName))) nextErrors.lastName=T("نام خانوادگی نباید شامل عدد باشد.","Last name cannot contain numbers.");
    if (!shValidNationalId(draft.identity.nationalId)) nextErrors.nationalId=T("کد ملی ۱۰ رقمی معتبر وارد کنید.","Enter a valid 10-digit national ID.");
    if (!shValidBirthDate(draft.identity.birthDate)) nextErrors.birthDate=T("تاریخ را به‌صورت ۱۳۷۰/۰۱/۰۱ وارد کنید.","Enter the date as 1370/01/01.");
    if (!/^09\d{9}$/.test(shOnlyDigits(draft.identity.mobile,11))) nextErrors.mobile=T("شماره موبایل باید ۱۱ رقم و با ۰۹ شروع شود.","Mobile must be 11 digits and start with 09.");
    if (draft.identity.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(draft.identity.email).trim())) nextErrors.email=T("ایمیل معتبر وارد کنید.","Enter a valid email address.");
    return nextErrors;
  };

  const validateRoleDetails = () => {
    const nextErrors = {};
    const details = draft.details || {};
    if (draft.roleId==="lawyer" && !/^\d{3,12}$/.test(shOnlyDigits(details.license,12))) nextErrors.license=T("شماره پروانه باید بین ۳ تا ۱۲ رقم باشد.","License number must contain 3 to 12 digits.");
    if (draft.roleId==="expert") {
      if (String(details.specialty||"").trim().length < 2) nextErrors.specialty=T("رشته تخصصی را کامل وارد کنید.","Enter the full specialty.");
      if (details.license && !/^\d{3,12}$/.test(shOnlyDigits(details.license,12))) nextErrors.license=T("شماره پروانه باید بین ۳ تا ۱۲ رقم باشد.","License number must contain 3 to 12 digits.");
    }
    if (["company","public","charity"].includes(draft.roleId)) {
      if (String(details.legalName||"").trim().length < 2) nextErrors.legalName=T("نام شخص حقوقی را کامل وارد کنید.","Enter the full legal entity name.");
      if (!/^\d{11}$/.test(shOnlyDigits(details.nationalCode,11))) nextErrors.nationalCode=T("شناسه ملی شخص حقوقی باید ۱۱ رقم باشد.","Legal entity national code must contain 11 digits.");
      if (details.registrationNo && !/^\d{3,20}$/.test(shOnlyDigits(details.registrationNo,20))) nextErrors.registrationNo=T("شماره ثبت باید بین ۳ تا ۲۰ رقم باشد.","Registration number must contain 3 to 20 digits.");
    }
    return nextErrors;
  };

  const showErrors = (nextErrors,targetStep=step) => {
    setErrors(nextErrors);
    if (targetStep!==step) setStep(targetStep);
    const firstKey = Object.keys(nextErrors)[0];
    if (firstKey) setTimeout(()=>document.getElementById(`pf-${firstKey}`)?.focus(),0);
  };

  const validateStep = () => {
    let nextErrors = {};
    if (step===0 && !draft.roleId) nextErrors.roleId = T("یک نقش را انتخاب کنید.","Choose a role.");
    if (step===1) nextErrors = validateIdentity();
    if (step===2) nextErrors = validateRoleDetails();
    showErrors(nextErrors);
    return Object.keys(nextErrors).length===0;
  };

  const next = () => { if (validateStep()) setStep((s)=>Math.min(3,s+1)); };
  const finish = () => {
    const identityErrors = validateIdentity();
    if (Object.keys(identityErrors).length) { showErrors(identityErrors,1); return; }
    const roleErrors = validateRoleDetails();
    if (Object.keys(roleErrors).length) { showErrors(roleErrors,2); return; }
    if (!consent) { setErrors({consent:T("پذیرش قوانین و تأیید صحت اطلاعات الزامی است.","You must confirm the information and accept the terms.")}); return; }
    const existing = profile.roles.find((x)=>x.id===draft.roleId);
    const isNatural = draft.roleId==="natural";
    const nextRole = {
      id:draft.roleId,
      status:isNatural ? "verified" : "pending",
      completion:isNatural ? 100 : 76,
      filing:existing?.filing || `SH-${draft.roleId.toUpperCase().slice(0,3)}-${Date.now().toString().slice(-5)}`,
      wallet:existing?.wallet || 0,
    };
    const roles = existing ? profile.roles.map((x)=>x.id===draft.roleId?nextRole:x) : [...profile.roles,nextRole];
    setProfile((p)=>({
      ...p,
      identity:{...draft.identity,locked:true},
      details:{...p.details,[draft.roleId]:draft.details},
      roles,
      activeRole:draft.roleId,
      savedAt:new Date().toISOString(),
    }));
    if (session?.setRole) session.setRole(isNatural?"user":draft.roleId);
    setWizard(null); setSavedFlash(true); setTimeout(()=>setSavedFlash(false),2600);
  };

  const identityFieldProps = { draft,setDraft,errors,setErrors,validateIdentity,lang };

  if (wizard && draft) {
    const wizardRole = SH_ROLE_TYPES.find((x)=>x.id===draft.roleId) || SH_ROLE_TYPES[0];
    const WIcon = Ic[wizardRole.icon] || Ic.user;
    const steps=[T("انتخاب نقش","Role"),T("هویت پایه","Identity"),T("اطلاعات نقش","Role details"),T("بازبینی","Review")];
    return <section className="pf-shell pf-wizard" aria-label={T("تکمیل پروفایل شهداد","Complete Shahdad profile")}>
      <header className="pf-wizard-head">
        <button className="pf-back" onClick={()=>setWizard(null)} aria-label={T("بازگشت به پروفایل","Back to profile")}><Ic.close size={16}/></button>
        <div><span>{T("مرکز هویت شهداد","Shahdad Identity Center")}</span><h2>{T("ساخت پروفایل دقیق، قدم‌به‌قدم","A precise profile, step by step")}</h2><p>{T("هر نقش فایلینگ، دسترسی و کیف پول مستقل خود را دارد.","Each role keeps its own filing, access and wallet.")}</p></div>
        <div className="pf-secure"><Ic.shieldCheck size={17}/><span>{T("اطلاعات رمزنگاری‌شده","Encrypted information")}</span></div>
      </header>
      <div className="pf-stepper" aria-label={T("مراحل تکمیل پروفایل","Profile steps")}>
        {steps.map((label,i)=><div key={label} className={(i===step?"active ":"")+(i<step?"done":"")}><b>{i<step?<Ic.shieldCheck size={14}/>:fmt(i+1,lang)}</b><span>{label}</span></div>)}
      </div>
      <div className="pf-wizard-card">
        {step===0&&<div className="pf-step-content"><div className="pf-section-title"><span>{T("نقش جدید","New role")}</span><h3>{T("در شهداد با چه هویتی فعالیت می‌کنید؟","How will you operate in Shahdad?")}</h3><p>{T("بعداً می‌توانید نقش‌های بیشتری به همین هویت اضافه کنید.","You can add more roles to this identity later.")}</p></div><div className="pf-role-picker">{SH_ROLE_TYPES.filter((x)=>!profile.roles.some((r)=>r.id===x.id)).map((x)=>{const Icon=Ic[x.icon]||Ic.user;return <button key={x.id} className={draft.roleId===x.id?"selected":""} onClick={()=>setDraft((d)=>({...d,roleId:x.id,details:{...(profile.details[x.id]||{})}}))}><Icon size={20}/><b>{fa?x.fa:x.en}</b><small>{fa?x.hintFa:x.hintEn}</small><i><Ic.shieldCheck size={13}/></i></button>})}</div>{errors.roleId&&<p className="pf-form-error">{errors.roleId}</p>}</div>}
        {step===1&&<div className="pf-step-content"><div className="pf-section-title"><span>{T("هویت مرکزی","Core identity")}</span><h3>{T("اطلاعات پایه و مشترک","Shared identity information")}</h3><p>{draft.identity.locked?T("اطلاعات هویتی تأییدشده فقط از طریق تیکت قابل اصلاح است.","Verified identity fields can only be changed through support."):T("این اطلاعات پس از تأیید هویت میان همه نقش‌ها مشترک خواهد بود.","These details will be shared across all verified roles.")}</p></div><div className="pf-form-grid"><ProfileIdentityField {...identityFieldProps} id="firstName" label={T("نام","First name")} autoComplete="given-name" maxLength={50}/><ProfileIdentityField {...identityFieldProps} id="lastName" label={T("نام خانوادگی","Last name")} autoComplete="family-name" maxLength={70}/><ProfileIdentityField {...identityFieldProps} id="nationalId" label={T("کد ملی","National ID")} inputMode="numeric" numeric maxLength={10} placeholder="۰۰۱۲۳۴۵۶۷۸" helper={T("دقیقاً ۱۰ رقم؛ ارقام فارسی و انگلیسی پذیرفته می‌شود.","Exactly 10 digits; Persian and Latin digits are accepted.")}/><ProfileIdentityField {...identityFieldProps} id="birthDate" label={T("تاریخ تولد","Birth date")} inputMode="numeric" date maxLength={10} placeholder="۱۳۷۰/۰۱/۰۱" helper={T("فرمت: سال/ماه/روز","Format: year/month/day")}/><ProfileIdentityField {...identityFieldProps} id="mobile" label={T("شماره موبایل","Mobile")} inputMode="tel" numeric maxLength={11} autoComplete="tel" placeholder="09xxxxxxxxx" helper={T("۱۱ رقم و با ۰۹ شروع شود.","11 digits, starting with 09.")}/><ProfileIdentityField {...identityFieldProps} id="email" label={T("ایمیل","Email")} type="email" autoComplete="email" maxLength={120} optional/></div></div>}
        {step===2&&<div className="pf-step-content"><div className="pf-section-title"><span>{fa?wizardRole.fa:wizardRole.en}</span><h3>{T("اطلاعات اختصاصی نقش","Role-specific information")}</h3><p>{T("فقط اطلاعات لازم برای اعتبارسنجی همین نقش دریافت می‌شود.","Only information needed to validate this role is requested.")}</p></div>
          {draft.roleId==="natural"&&<div className="pf-info-note"><Ic.shieldCheck size={20}/><div><b>{T("برای شخص حقیقی مدرک حرفه‌ای لازم نیست.","No professional document is required.")}</b><span>{T("پس از تأیید موبایل یا ایمیل، حساب فعال می‌شود.","The account activates after mobile or email verification.")}</span></div></div>}
          {draft.roleId==="lawyer"&&<div className="pf-form-grid"><label className={"pf-field"+(errors.license?" has-error":"")}><span>{T("شماره پروانه","License number")}<i>*</i></span><input id="pf-license" inputMode="numeric" maxLength={12} aria-invalid={!!errors.license} value={draft.details.license||""} onChange={(e)=>setDraft((d)=>({...d,details:{...d.details,license:shOnlyDigits(e.target.value,12)}}))}/>{errors.license?<small role="alert">{errors.license}</small>:<small className="pf-helper">{T("بین ۳ تا ۱۲ رقم","3 to 12 digits")}</small>}</label><label className="pf-field"><span>{T("مرجع صدور","Issuing authority")}</span><select value={draft.details.authority||"bar"} onChange={(e)=>setDraft((d)=>({...d,details:{...d.details,authority:e.target.value}}))}><option value="bar">{T("کانون وکلای دادگستری","Bar Association")}</option><option value="center">{T("مرکز وکلا و مشاوران","Judiciary Center")}</option></select></label><label className="pf-upload"><Ic.doc size={22}/><b>{T("بارگذاری تصویر پروانه","Upload license image")}</b><span>{T("PDF، JPG یا PNG — حداکثر ۱۰ مگابایت","PDF, JPG or PNG — max 10 MB")}</span><input type="file" accept=".pdf,.jpg,.jpeg,.png"/></label></div>}
          {draft.roleId==="expert"&&<div className="pf-form-grid"><label className={"pf-field"+(errors.specialty?" has-error":"")}><span>{T("رشته تخصصی","Specialty")}<i>*</i></span><input id="pf-specialty" maxLength={100} aria-invalid={!!errors.specialty} value={draft.details.specialty||""} onChange={(e)=>setDraft((d)=>({...d,details:{...d.details,specialty:e.target.value}}))}/>{errors.specialty&&<small role="alert">{errors.specialty}</small>}</label><label className={"pf-field"+(errors.license?" has-error":"")}><span>{T("شماره پروانه","License number")}</span><input id="pf-license" inputMode="numeric" maxLength={12} aria-invalid={!!errors.license} value={draft.details.license||""} onChange={(e)=>setDraft((d)=>({...d,details:{...d.details,license:shOnlyDigits(e.target.value,12)}}))}/>{errors.license?<small role="alert">{errors.license}</small>:<small className="pf-helper">{T("در صورت درج، بین ۳ تا ۱۲ رقم","If provided, 3 to 12 digits")}</small>}</label><label className="pf-upload"><Ic.doc size={22}/><b>{T("مدارک تخصصی","Professional documents")}</b><span>{T("پروانه، تحصیلات یا سابقه حرفه‌ای","License, education or experience")}</span><input type="file" multiple/></label></div>}
          {["company","public","charity"].includes(draft.roleId)&&<div className="pf-form-grid"><label className={"pf-field"+(errors.legalName?" has-error":"")}><span>{T("نام شخص حقوقی","Legal entity name")}<i>*</i></span><input id="pf-legalName" maxLength={150} aria-invalid={!!errors.legalName} value={draft.details.legalName||""} onChange={(e)=>setDraft((d)=>({...d,details:{...d.details,legalName:e.target.value}}))}/>{errors.legalName&&<small role="alert">{errors.legalName}</small>}</label><label className={"pf-field"+(errors.nationalCode?" has-error":"")}><span>{T("شناسه ملی","National code")}<i>*</i></span><input id="pf-nationalCode" inputMode="numeric" maxLength={11} aria-invalid={!!errors.nationalCode} value={draft.details.nationalCode||""} onChange={(e)=>setDraft((d)=>({...d,details:{...d.details,nationalCode:shOnlyDigits(e.target.value,11)}}))}/>{errors.nationalCode?<small role="alert">{errors.nationalCode}</small>:<small className="pf-helper">{T("دقیقاً ۱۱ رقم","Exactly 11 digits")}</small>}</label><label className={"pf-field"+(errors.registrationNo?" has-error":"")}><span>{T("شماره ثبت","Registration number")}</span><input id="pf-registrationNo" inputMode="numeric" maxLength={20} aria-invalid={!!errors.registrationNo} value={draft.details.registrationNo||""} onChange={(e)=>setDraft((d)=>({...d,details:{...d.details,registrationNo:shOnlyDigits(e.target.value,20)}}))}/>{errors.registrationNo?<small role="alert">{errors.registrationNo}</small>:<small className="pf-helper">{T("در صورت درج، بین ۳ تا ۲۰ رقم","If provided, 3 to 20 digits")}</small>}</label><label className="pf-upload"><Ic.doc size={22}/><b>{T("روزنامه رسمی و مدرک سمت","Official gazette and authority proof")}</b><span>{T("امکان افزودن چند فایل","Multiple files accepted")}</span><input type="file" multiple/></label></div>}
          {["judge","arbitrator"].includes(draft.roleId)&&<div className="pf-info-note"><WIcon size={21}/><div><b>{T("فعال‌سازی این نقش با تأیید ادمین انجام می‌شود.","This role requires admin approval.")}</b><span>{T("مدارک تکمیلی پس از ثبت درخواست از شما خواسته می‌شود.","Additional evidence may be requested after submission.")}</span></div></div>}
        </div>}
        {step===3&&<div className="pf-step-content"><div className="pf-section-title"><span>{T("بازبینی نهایی","Final review")}</span><h3>{T("پیش از ثبت، اطلاعات را بررسی کنید","Review before submission")}</h3><p>{T("پس از تأیید هویت، تغییر اطلاعات پایه فقط از مسیر پشتیبانی ممکن است.","After verification, core identity changes require support.")}</p></div><div className="pf-review"><div><span>{T("نام و نام خانوادگی","Full name")}</span><b>{[draft.identity.firstName,draft.identity.lastName].join(" ")}</b></div><div><span>{T("کد ملی","National ID")}</span><b className="fa-num">{shMaskId(draft.identity.nationalId)}</b></div><div><span>{T("شماره موبایل","Mobile")}</span><b className="fa-num">{draft.identity.mobile}</b></div><div><span>{T("نقش درخواستی","Requested role")}</span><b>{fa?wizardRole.fa:wizardRole.en}</b></div></div><label className="pf-consent"><input type="checkbox" checked={consent} onChange={(e)=>{setConsent(e.target.checked);if(e.target.checked)setErrors({});}}/><span>{T("صحت اطلاعات را تأیید می‌کنم و قوانین و حریم خصوصی شهداد را پذیرفته‌ام.","I confirm the information and accept Shahdad terms and privacy policy.")}</span></label>{errors.consent&&<p className="pf-form-error" role="alert">{errors.consent}</p>}</div>}
      </div>
      <footer className="pf-wizard-actions"><button className="btn ghost" onClick={()=>step>0?setStep((s)=>s-1):setWizard(null)}>{T("مرحله قبل","Back")}</button><span>{T(`مرحله ${fmt(step+1,lang)} از ۴`,`Step ${step+1} of 4`)}</span>{step<3?<button className="btn primary" onClick={next}>{T("ادامه","Continue")}<Ic.chevL size={15}/></button>:<button className="btn primary" onClick={finish} disabled={!consent}><Ic.shieldCheck size={15}/>{T("ثبت و ارسال برای بررسی","Submit for review")}</button>}</footer>
    </section>;
  }

  const RoleIcon = Ic[role.icon] || Ic.user;
  return <section className="pf-shell" aria-label={T("مرکز هویت و پروفایل شهداد","Shahdad identity and profile center")}>
    {savedFlash&&<div className="pf-toast" role="status"><Ic.shieldCheck size={17}/>{T("اطلاعات پروفایل با موفقیت ذخیره شد.","Profile saved successfully.")}</div>}
    <header className="pf-hero">
      <div className="pf-avatar" aria-hidden="true"><span>{initials}</span><i><Ic.shieldCheck size={13}/></i></div>
      <div className="pf-hero-copy"><div className="pf-eyebrow"><Ic.idcard size={14}/>{T("هویت مرکزی شهداد","Shahdad core identity")}</div><h2>{fullName}</h2><div className="pf-meta"><span className={`pf-status ${status.tone}`}><i></i>{fa?status.fa:status.en}</span><span><Ic.idcard size={13}/>{T("کد ملی","National ID")}: <b className="fa-num">{shMaskId(identity.nationalId)}</b></span><span><Ic.user size={13}/>{identity.mobile||T("موبایل ثبت نشده","No mobile")}</span></div></div>
      <div className="pf-completion"><div style={{"--pf-progress":`${roleState.completion*3.6}deg`}}><strong className="fa-num">{fmt(roleState.completion,lang)}%</strong><span>{T("تکمیل","complete")}</span></div><button className="btn primary" onClick={()=>beginWizard()}><Ic.docEdit size={15}/>{T("تکمیل پروفایل","Complete profile")}</button></div>
    </header>
    <div className="pf-layout">
      <aside className="pf-roles">
        <div className="pf-side-title"><div><span>{T("نقش‌های من","My roles")}</span><b>{T("هویت واحد، فضای کاری مستقل","One identity, separate workspaces")}</b></div><button onClick={()=>beginWizard("__add__")} aria-label={T("افزودن نقش","Add role")}><Ic.plus size={16}/></button></div>
        <div className="pf-role-list">{profile.roles.map((item)=>{const def=SH_ROLE_TYPES.find((x)=>x.id===item.id)||SH_ROLE_TYPES[0];const Icon=Ic[def.icon]||Ic.user;const st=SH_STATUS[item.status]||SH_STATUS.incomplete;return <button key={item.id} className={profile.activeRole===item.id?"active":""} onClick={()=>setActiveRole(item.id)}><i><Icon size={18}/></i><span><b>{fa?def.fa:def.en}</b><small>{fa?st.fa:st.en}</small></span><em className={st.tone}></em><Ic.chevL size={14}/></button>})}</div>
        <button className="pf-add-role" onClick={()=>beginWizard("__add__")}><Ic.plus size={16}/><span>{T("افزودن نقش جدید","Add another role")}</span></button>
        <div className="pf-privacy"><Ic.shield size={18}/><div><b>{T("مرز حریم خصوصی","Privacy boundary")}</b><span>{T("اطلاعات هویتی مشترک است؛ فایلینگ، دسترسی و کیف پول هر نقش جدا می‌ماند.","Identity is shared; filing, access and wallet remain role-specific.")}</span></div></div>
      </aside>
      <main className="pf-main">
        <div className="pf-role-head"><div className="pf-role-mark"><RoleIcon size={23}/></div><div><span>{T("فضای کاری فعال","Active workspace")}</span><h3>{fa?role.fa:role.en}</h3><p>{fa?role.hintFa:role.hintEn}</p></div><button className="btn ghost" onClick={()=>beginWizard()}><Ic.docEdit size={14}/>{T("مدیریت نقش","Manage role")}</button></div>
        <div className="pf-metrics"><div><span><Ic.folder size={16}/>{T("فایلینگ نقش","Role filing")}</span><b>{roleState.filing}</b><small>{T("مستقل از سایر نقش‌ها","Independent workspace")}</small></div><div><span><Ic.coin size={16}/>{T("کیف پول نقش","Role wallet")}</span><b className="fa-num">{fmt(roleState.wallet,lang)} {T("تومان","Toman")}</b><small>{T("تراکنش‌های تفکیک‌شده","Separated transactions")}</small></div><div><span><Ic.shieldCheck size={16}/>{T("سطح دسترسی","Access level")}</span><b>{roleState.status==="verified"?T("فعال","Active"):T("پایه","Basic")}</b><small>{T("متناسب با وضعیت و پلن","Based on status and plan")}</small></div></div>
        <div className="pf-content-grid"><section className="pf-card"><div className="pf-card-title"><div><span>{T("چرخه اعتبارسنجی","Validation lifecycle")}</span><h4>{T("وضعیت این نقش","Role status")}</h4></div><span className={`pf-status ${status.tone}`}><i></i>{fa?status.fa:status.en}</span></div><div className="pf-timeline">{[
          ["done",T("ثبت هویت پایه","Core identity registered"),T("اطلاعات مشترک حساب","Shared account information")],
          [roleState.completion>45?"done":"current",T("تکمیل اطلاعات نقش","Role information"),T("مدارک و اطلاعات اختصاصی","Role-specific evidence")],
          [roleState.status==="verified"?"done":roleState.status==="pending"?"current":"future",T("اعتبارسنجی","Validation"),T("بررسی مدارک توسط شهداد","Evidence review by Shahdad")],
          [roleState.status==="verified"?"done":"future",T("فعال‌سازی نهایی","Final activation"),T("دسترسی متناسب با نقش","Role-aware access")],
        ].map((x,i)=><div key={i} className={x[0]}><i>{x[0]==="done"?<Ic.shieldCheck size={13}/>:fmt(i+1,lang)}</i><span><b>{x[1]}</b><small>{x[2]}</small></span></div>)}</div></section>
        <section className="pf-card"><div className="pf-card-title"><div><span>{T("اطلاعات مرکزی","Core information")}</span><h4>{T("شناسنامه حساب","Account identity")}</h4></div><button onClick={()=>beginWizard()}>{T("مشاهده و تکمیل","View & complete")}</button></div><div className="pf-facts"><div><span>{T("نام کامل","Full name")}</span><b>{fullName}</b></div><div><span>{T("موبایل","Mobile")}</span><b className="fa-num">{identity.mobile||"—"}</b></div><div><span>{T("ایمیل","Email")}</span><b>{identity.email||"—"}</b></div><div><span>{T("محل سکونت","Location")}</span><b>{[identity.province,identity.city].filter(Boolean).join("، ")||"—"}</b></div></div><div className="pf-lock-note"><Ic.shield size={15}/><span>{identity.locked?T("اطلاعات هویتی تأییدشده قفل است؛ اصلاح فقط با تیکت و احراز مجدد انجام می‌شود.","Verified identity is locked; changes require support and re-verification."):T("پس از تأیید، اطلاعات هویتی برای امنیت حساب قفل می‌شود.","Identity fields lock after verification for account security.")}</span></div></section></div>
        <section className="pf-next"><div><span>{T("پیشنهاد هوشمند بعدی","Recommended next step")}</span><h4>{roleState.completion<100?T("پروفایل این نقش را کامل کنید","Complete this role profile"):T("همه‌چیز برای شروع آماده است","Your workspace is ready")}</h4><p>{roleState.completion<100?T("تکمیل اطلاعات، مسیر دسترسی به خدمات حقوقی متناسب را باز می‌کند.","Completing your details unlocks the right legal services."):T("اکنون می‌توانید با همین نقش وارد خدمات و پرونده‌های مرتبط شوید.","You can now enter relevant services and cases with this role.")}</p></div><button className="btn primary" onClick={()=>beginWizard()}>{roleState.completion<100?T("ادامه تکمیل","Continue setup"):T("بازبینی اطلاعات","Review details")}<Ic.chevL size={15}/></button></section>
      </main>
    </div>
  </section>;
};

Object.assign(window,{ ProfilingView });
