// popups.jsx — Modal system + per-module content panels

const Modal = ({ title, sub, iconKey, className = "", onClose, isTopMost = true, children }) => {
  const Icon = Ic[iconKey] || Ic.chip;
  const backdropRef = React.useRef(null);
  const dialogRef = React.useRef(null);
  const onCloseRef = React.useRef(onClose);
  const titleId = React.useId();
  const subId = React.useId();
  const activeLang = document.documentElement.lang || "fa";
  const closeLabel = activeLang === "fa" ? "بستن" : activeLang === "ar" ? "إغلاق" : "Close";
  React.useEffect(() => { onCloseRef.current = onClose; }, [onClose]);
  React.useEffect(() => {
    const previouslyFocused = document.activeElement;
    const isTopMost = () => {
      const backdrops = document.querySelectorAll(".backdrop");
      return backdrops.length && backdrops[backdrops.length - 1] === backdropRef.current;
    };
    const frame = window.requestAnimationFrame(() => dialogRef.current?.focus());
    const h = (e) => {
      if (!isTopMost()) return;
      if (e.key === "Escape") {
        e.preventDefault();
        onCloseRef.current();
        return;
      }
      if (e.key !== "Tab" || !dialogRef.current) return;
      const focusable = [...dialogRef.current.querySelectorAll(
        'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
      )].filter((node) => !node.hasAttribute("hidden") && node.getAttribute("aria-hidden") !== "true");
      if (!focusable.length) {
        e.preventDefault();
        dialogRef.current.focus();
        return;
      }
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault();
        last.focus();
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", h);
    return () => {
      window.cancelAnimationFrame(frame);
      window.removeEventListener("keydown", h);
      if (previouslyFocused && previouslyFocused.isConnected) previouslyFocused.focus();
    };
  }, []);
  return (
    <div
      ref={backdropRef}
      className="backdrop"
      aria-hidden={isTopMost ? undefined : "true"}
      inert={isTopMost ? undefined : ""}
      onClick={(e) => { if (isTopMost && e.target === e.currentTarget) onCloseRef.current(); }}
    >
      <div
        ref={dialogRef}
        className={`modal ${className}`.trim()}
        role="dialog"
        aria-modal={isTopMost ? "true" : "false"}
        aria-labelledby={titleId}
        aria-describedby={sub ? subId : undefined}
        tabIndex="-1"
      >
        <div className="modal-head">
          <div className="lh">
            <div className="ic"><Icon size={20} /></div>
            <div>
              <div className="ti" id={titleId}>{title}</div>
              {sub && <div className="st" id={subId}>{sub}</div>}
            </div>
          </div>
          <div className="rh">
            <button type="button" title="Minimize" aria-label="Minimize" disabled><Ic.minus size={16}/></button>
            <button type="button" title="Expand" aria-label="Expand" disabled><Ic.expand size={16}/></button>
            <button type="button" className="close" onClick={onClose} aria-label={closeLabel}><Ic.close size={16}/></button>
          </div>
        </div>
        <div className="modal-body">{children}</div>
      </div>
    </div>
  );
};

// =====================================================================
// MODULE CONTENT VIEWS
// =====================================================================

const ConsultView = ({ lang }) => (
  <div>
    <div className="between mt-2" style={{marginBottom: 14}}>
      <div className="tabs">
        <div className="tab on">{lang==="fa"?"همه":"All"}</div>
        <div className="tab">{lang==="fa"?"زمان‌بندی شده":"Scheduled"}</div>
        <div className="tab">{lang==="fa"?"انجام شده":"Done"}</div>
      </div>
      <button className="btn primary">
        <Ic.plus size={14}/> {lang==="fa"?"درخواست مشاوره جدید":"Request new consultation"}
      </button>
    </div>
    <table className="table">
      <thead><tr>
        <th>{lang==="fa"?"وکیل":"Lawyer"}</th>
        <th>{lang==="fa"?"موضوع":"Topic"}</th>
        <th>{lang==="fa"?"نوع":"Type"}</th>
        <th>{lang==="fa"?"زمان":"When"}</th>
        <th>{lang==="fa"?"مدت":"Duration"}</th>
        <th>{lang==="fa"?"هزینه":"Fee"}</th>
        <th>{lang==="fa"?"وضعیت":"Status"}</th>
      </tr></thead>
      <tbody>
        {CONSULTS.map((c, i) => {
          const kindIc = c.kind === "video" ? "🎥" : c.kind === "voice" ? "🎙" : "💬";
          const st = STATUS_PILL[c.status];
          return (
            <tr key={i}>
              <td>{c.lawyer[lang]}</td>
              <td>{c.topic[lang]}</td>
              <td><span style={{opacity: 0.9}}>{kindIc}</span></td>
              <td>{c.when[lang]}</td>
              <td>{fmt(c.dur, lang)} {lang==="fa"?"دقیقه":"min"}</td>
              <td>{fmt(c.price, lang)}K</td>
              <td><span className={"pill " + st.kind}>{st[lang]}</span></td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </div>
);

const LAWYER_DIRECTORY = [
  {
    id:"center-5975", name:{fa:"امیر حاجیان",en:"Amir Hajian"}, photo:"uploads/lawyers/center-005975.jpg",
    license:"۴۸۳۳۴", city:{fa:"آذرشهر، آذربایجان شرقی",en:"Azarshahr, East Azerbaijan"}, center:"center",
    affiliation:{fa:"مرکز وکلا، کارشناسان رسمی و مشاوران خانواده قوه قضاییه",en:"Judiciary Center for Lawyers"}, shahdad:true,
    bio:{fa:"وکیل دادگستری با رویکرد مسئله‌محور و تمرکز بر تحلیل دقیق اسناد، شفافیت مسیر پرونده و گزارش منظم به موکل.",en:"Attorney focused on document analysis, a clear case strategy and consistent client updates."},
    education:{fa:"کارشناسی ارشد حقوق خصوصی",en:"LL.M. in Private Law"}, experience:16,
    specialties:[{fa:"دعاوی ملکی",en:"Property"},{fa:"قراردادها",en:"Contracts"},{fa:"حقوق تجاری",en:"Commercial"}],
    scores:{experience:4.9,specialty:4.8,skill:4.8,education:4.6}, clients:4.9, reviews:132
  },
  {
    id:"bar-10", name:{fa:"علی ابراهیمی",en:"Ali Ebrahimi"}, photo:"uploads/lawyers/bar-000010.jpg",
    license:"۹۴", city:{fa:"اراک، استان مرکزی",en:"Arak, Markazi"}, center:"bar",
    affiliation:{fa:"کانون وکلای دادگستری استان مرکزی",en:"Markazi Bar Association"}, shahdad:true,
    bio:{fa:"مشاور و وکیل دادگستری با تمرکز بر ارزیابی ریسک پرونده، انتخاب راهکار عملی و همراهی مرحله‌به‌مرحله موکل.",en:"Attorney focused on case-risk assessment, practical strategy and step-by-step client support."},
    education:{fa:"کارشناسی ارشد حقوق خصوصی",en:"LL.M. in Private Law"}, experience:17,
    specialties:[{fa:"دعاوی مدنی",en:"Civil"},{fa:"املاک",en:"Property"},{fa:"داوری",en:"Arbitration"}],
    scores:{experience:4.9,specialty:4.7,skill:4.8,education:4.6}, clients:4.8, reviews:126
  },
  {
    id:"center-7398", name:{fa:"رسول نظامی",en:"Rasoul Nezami"}, photo:"uploads/lawyers/center-007398.jpg",
    license:"۴۵۷۸۸", city:{fa:"آذرشهر، آذربایجان شرقی",en:"Azarshahr, East Azerbaijan"}, center:"center",
    affiliation:{fa:"مرکز وکلا، کارشناسان رسمی و مشاوران خانواده قوه قضاییه",en:"Judiciary Center for Lawyers"}, shahdad:false,
    bio:{fa:"فعال در پرونده‌های کیفری و اختلافات پیچیده با تمرکز بر تدوین دفاع منسجم و بررسی جزئیات پرونده.",en:"Criminal-litigation attorney focused on coherent defense and detailed case review."},
    education:{fa:"کارشناسی ارشد حقوق جزا و جرم‌شناسی",en:"LL.M. in Criminal Law"}, experience:14,
    specialties:[{fa:"دعاوی کیفری",en:"Criminal"},{fa:"جرایم اقتصادی",en:"Financial Crime"},{fa:"تجدیدنظر",en:"Appeals"}],
    scores:{experience:4.7,specialty:4.9,skill:4.8,education:4.7}, clients:4.7, reviews:89
  },
  {
    id:"bar-11", name:{fa:"مریم ابراهیمی",en:"Maryam Ebrahimi"}, photo:"uploads/lawyers/bar-000011.jpg",
    license:"۱۶۸", city:{fa:"دلیجان، استان مرکزی",en:"Delijan, Markazi"}, center:"bar",
    affiliation:{fa:"کانون وکلای دادگستری استان مرکزی",en:"Markazi Bar Association"}, shahdad:false,
    bio:{fa:"فعال در حوزه خانواده و امور مدنی با رویکرد حل‌وفصل کم‌تنش، مذاکره حرفه‌ای و حفظ منافع بلندمدت موکل.",en:"Family-law attorney with a negotiation-led, low-conflict approach."},
    education:{fa:"کارشناسی ارشد حقوق خانواده",en:"LL.M. in Family Law"}, experience:13,
    specialties:[{fa:"حقوق خانواده",en:"Family"},{fa:"امور حسبی",en:"Probate"},{fa:"دعاوی مدنی",en:"Civil"}],
    scores:{experience:4.6,specialty:4.9,skill:4.8,education:4.7}, clients:4.9, reviews:94
  },
  {
    id:"center-11676", name:{fa:"رقیه جعفری شتوبانی",en:"Roghayeh Jafari"}, photo:"uploads/lawyers/center-011676.jpg",
    license:"۱۳۱۵۶", city:{fa:"آذرشهر، آذربایجان شرقی",en:"Azarshahr, East Azerbaijan"}, center:"center",
    affiliation:{fa:"مرکز وکلا، کارشناسان رسمی و مشاوران خانواده قوه قضاییه",en:"Judiciary Center for Lawyers"}, shahdad:true,
    bio:{fa:"وکیل و مشاور حقوقی در پرونده‌های خانواده و املاک، با تأکید بر توضیح ساده فرایند و دسترسی‌پذیری برای موکل.",en:"Family and property attorney emphasizing clear process explanations and accessibility."},
    education:{fa:"کارشناسی ارشد حقوق خصوصی",en:"LL.M. in Private Law"}, experience:11,
    specialties:[{fa:"خانواده",en:"Family"},{fa:"املاک",en:"Property"},{fa:"اجرای احکام",en:"Enforcement"}],
    scores:{experience:4.4,specialty:4.7,skill:4.8,education:4.6}, clients:4.8, reviews:103
  },
  {
    id:"bar-15", name:{fa:"سمیه احمدی",en:"Somayeh Ahmadi"}, photo:"uploads/lawyers/bar-000015.jpg",
    license:"۲۷۸", city:{fa:"اراک، استان مرکزی",en:"Arak, Markazi"}, center:"bar",
    affiliation:{fa:"کانون وکلای دادگستری استان مرکزی",en:"Markazi Bar Association"}, shahdad:false,
    bio:{fa:"وکیل دعاوی کار و تأمین اجتماعی با تمرکز بر مستندسازی دقیق، مذاکره نتیجه‌محور و پیگیری منظم.",en:"Labor-law attorney focused on documentation and outcome-driven negotiation."},
    education:{fa:"کارشناسی ارشد حقوق عمومی",en:"LL.M. in Public Law"}, experience:10,
    specialties:[{fa:"حقوق کار",en:"Labor"},{fa:"تأمین اجتماعی",en:"Social Security"},{fa:"دعاوی مدنی",en:"Civil"}],
    scores:{experience:4.3,specialty:4.6,skill:4.7,education:4.6}, clients:4.7, reviews:72
  }
];

const lawyerScore = (p) => Object.values(p.scores).reduce((sum,n)=>sum+n,0) / 4;
const lawyerText = (obj, lang) => obj[lang] || obj.fa || obj.en;
const LawyerStars = ({value,label}) => (
  <span className="lv-stars" aria-label={`${label}: ${value.toFixed(1)} / 5`}>
    {[1,2,3,4,5].map((n)=><Ic.star key={n} size={14} className={n<=Math.round(value)?"on":""}/>)}
  </span>
);
const LawyerScoreRow = ({icon,label,value}) => {
  const Icon = Ic[icon] || Ic.star;
  return <div className="lv-score-row">
    <span><Icon size={15}/>{label}</span><div><i style={{width:`${value*20}%`}}/></div><b>{value.toFixed(1)}</b>
  </div>;
};

const LawyerView = ({ lang }) => {
  const L = (fa,en,ar=fa) => lang==="fa"?fa:lang==="ar"?ar:en;
  const [query,setQuery] = React.useState("");
  const [city,setCity] = React.useState("all");
  const [specialty,setSpecialty] = React.useState("all");
  const [center,setCenter] = React.useState("all");
  const [sort,setSort] = React.useState("score");
  const [selectedId,setSelectedId] = React.useState(LAWYER_DIRECTORY[0].id);
  const deferredQuery = React.useDeferredValue(query.trim().toLocaleLowerCase());
  const cities = React.useMemo(()=>[...new Set(LAWYER_DIRECTORY.map(p=>lawyerText(p.city,lang)))],[lang]);
  const specialties = React.useMemo(()=>[...new Set(LAWYER_DIRECTORY.flatMap(p=>p.specialties.map(x=>lawyerText(x,lang))))],[lang]);
  const filtered = React.useMemo(()=>LAWYER_DIRECTORY.filter(p=>{
    const hay=[lawyerText(p.name,lang),lawyerText(p.city,lang),p.license,...p.specialties.map(x=>lawyerText(x,lang))].join(" ").toLocaleLowerCase();
    return (!deferredQuery||hay.includes(deferredQuery)) && (city==="all"||lawyerText(p.city,lang)===city)
      && (specialty==="all"||p.specialties.some(x=>lawyerText(x,lang)===specialty))
      && (center==="all"||(center==="shahdad"?p.shahdad:p.center===center));
  }).sort((a,b)=>sort==="experience"?b.experience-a.experience:lawyerScore(b)-lawyerScore(a)),[deferredQuery,city,specialty,center,sort,lang]);
  React.useEffect(()=>{if(filtered.length&&!filtered.some(p=>p.id===selectedId))setSelectedId(filtered[0].id)},[filtered,selectedId]);
  const selected=LAWYER_DIRECTORY.find(p=>p.id===selectedId)||filtered[0];
  const centerLabel=(p)=>p.center==="center"?L("مرکز وکلا","Judiciary Center","مركز المحامين"):L("کانون وکلا","Bar Association","نقابة المحامين");
  return <section className="lv-directory" aria-label={L("فهرست و معرفی وکلا","Lawyer directory","دليل المحامين")}>
    <div className="lv-intro">
      <div><span><Ic.shieldCheck size={15}/>{L("دایرکتوری تخصصی شهداد","Shahdad verified directory","دليل شهداد الموثق")}</span>
      <h2>{L("انتخاب وکیل، با اطلاعات روشن","Choose with clarity","اختر محاميك بوضوح")}</h2>
      <p>{L("جست‌وجو بر پایه تخصص، سابقه، محل فعالیت و امتیازهای شفاف","Search by expertise, experience, location and transparent ratings","ابحث حسب الخبرة والموقع والتقييم")}</p></div>
      <div className="lv-count"><strong>{fmt(42896,lang)}</strong><span>{L("وکیل در بانک شهداد","lawyers indexed","محامٍ في الدليل")}</span></div>
    </div>

    <div className="lv-filter-card">
      <div className="lv-filter-grid">
        <label className="lv-search"><span>{L("جست‌وجوی وکیل","Search lawyer","بحث عن محامٍ")}</span><div><Ic.search size={17}/><input value={query} onChange={e=>setQuery(e.target.value)} placeholder={L("نام، شماره پروانه یا تخصص...","Name, license or specialty...","الاسم أو رقم الترخيص...")}/></div></label>
        <label><span>{L("محل فعالیت","Location","الموقع")}</span><select value={city} onChange={e=>setCity(e.target.value)}><option value="all">{L("همه شهرها","All cities","كل المدن")}</option>{cities.map(x=><option key={x}>{x}</option>)}</select></label>
        <label><span>{L("تخصص وکالتی","Specialty","التخصص")}</span><select value={specialty} onChange={e=>setSpecialty(e.target.value)}><option value="all">{L("همه تخصص‌ها","All specialties","كل التخصصات")}</option>{specialties.map(x=><option key={x}>{x}</option>)}</select></label>
        <label><span>{L("مرتب‌سازی","Sort by","الترتيب")}</span><select value={sort} onChange={e=>setSort(e.target.value)}><option value="score">{L("امتیاز تخصصی شهداد","Shahdad score","تقييم شهداد")}</option><option value="experience">{L("بیشترین سابقه","Most experienced","الأكثر خبرة")}</option></select></label>
      </div>
      <div className="lv-center-row"><span>{L("نوع مرکز","Affiliation","الجهة")}</span><div role="group" aria-label={L("نوع مرکز","Affiliation","الجهة")}>
        {[["all",L("همه وکلا","All lawyers","كل المحامين")],["shahdad",L("وکلای Shahdad AI","Shahdad AI lawyers","محامو Shahdad AI")],["center",L("مرکز وکلا","Judiciary Center","مركز المحامين")],["bar",L("کانون وکلا","Bar Association","نقابة المحامين")]].map(x=><button key={x[0]} className={center===x[0]?"on":""} onClick={()=>setCenter(x[0])}>{x[0]==="shahdad"&&<Ic.shieldCheck size={13}/>} {x[1]}</button>)}
      </div></div>
    </div>

    <div className="lv-meta"><span>{L(`${fmt(filtered.length,lang)} وکیل یافت شد`,`${filtered.length} lawyers found`,`${fmt(filtered.length,lang)} محامين`)}</span><small><Ic.star size={13}/>{L("امتیاز شهداد: سابقه + تخصص + مهارت + تحصیلات","Shahdad: experience + expertise + skill + education","تقييم شهداد المهني")}</small></div>

    {filtered.length?<div className="lv-layout">
      <div className="lv-list" role="list">
        {filtered.map(p=>{const score=lawyerScore(p),active=selected&&selected.id===p.id;return <button key={p.id} role="listitem" className={`lv-card ${active?"active":""}`} aria-pressed={active} onClick={()=>setSelectedId(p.id)}>
          <img src={p.photo} alt={L(`تصویر ${p.name.fa}`,`${p.name.en} portrait`,`صورة المحامي`)} loading="lazy"/>
          <div className="lv-card-body"><div className="lv-card-title"><div><h3>{lawyerText(p.name,lang)}<Ic.shieldCheck size={14}/></h3><p>{centerLabel(p)} · {L("پروانه","License","الترخيص")} <b>{p.license}</b></p></div>{p.shahdad&&<span className="lv-shahdad"><Ic.shieldCheck size={12}/>{L("وکیل Shahdad AI","Shahdad AI lawyer","محامي Shahdad AI")}</span>}</div>
          <div className="lv-card-facts"><span><Ic.building size={14}/>{lawyerText(p.city,lang)}</span><span><Ic.clock size={14}/>{fmt(p.experience,lang)} {L("سال سابقه","years","سنة")}</span></div>
          <div className="lv-card-bottom"><div className="lv-tags">{p.specialties.slice(0,2).map(x=><span key={x.fa}>{lawyerText(x,lang)}</span>)}</div><div className="lv-card-score"><LawyerStars value={score} label={L("امتیاز شهداد","Shahdad score","تقييم شهداد")}/><b>{score.toFixed(1)}</b></div></div></div>
        </button>})}
      </div>
      {selected&&<aside className="lv-profile">
        <div className="lv-profile-head"><img src={selected.photo} alt=""/><div><div className="lv-verified"><Ic.shieldCheck size={14}/>{L("هویت و پروانه بررسی شده","Identity & license verified","تم التحقق من الهوية")}</div><h3>{lawyerText(selected.name,lang)}</h3><p>{centerLabel(selected)} · {L("شماره پروانه","License","رقم الترخيص")} <b>{selected.license}</b></p>{selected.shahdad&&<span className="lv-shahdad is-detail"><Ic.shieldCheck size={12}/>{L("وکیل Shahdad AI · ثبت‌نام‌شده و دارای قرارداد فعال","Shahdad AI lawyer · registered with an active contract","محامي Shahdad AI مسجل ومتعاقد")}</span>}</div></div>
        <div className="lv-profile-content">
          <div className="lv-bio"><h4><Ic.user size={16}/>{L("درباره وکیل","Biography","نبذة")}</h4><p>{lawyerText(selected.bio,lang)}</p></div>
          <div className="lv-info-grid"><div><span><Ic.cap size={15}/>{L("تحصیلات","Education","التعليم")}</span><b>{lawyerText(selected.education,lang)}</b></div><div><span><Ic.clock size={15}/>{L("سابقه فعالیت","Experience","الخبرة")}</span><b>{fmt(selected.experience,lang)} {L("سال","years","سنة")}</b></div><div><span><Ic.building size={15}/>{L("محل اشتغال","Workplace","مكان العمل")}</span><b>{lawyerText(selected.city,lang)}</b></div><div><span><Ic.shield size={15}/>{L("نوع مرکز","Affiliation","الجهة")}</span><b>{lawyerText(selected.affiliation,lang)}</b></div></div>
          <div className="lv-specialties"><h4><Ic.scale size={16}/>{L("زمینه‌های تخصصی وکالتی","Practice areas","مجالات التخصص")}</h4><div className="lv-tags">{selected.specialties.map(x=><span key={x.fa}>{lawyerText(x,lang)}</span>)}</div></div>
          <div className="lv-ratings"><div className="lv-pro-score"><span>{L("امتیاز تخصصی شهداد","Shahdad professional score","تقييم شهداد المهني")}</span><strong>{lawyerScore(selected).toFixed(1)}<small>/۵</small></strong><LawyerStars value={lawyerScore(selected)} label={L("امتیاز تخصصی شهداد","Shahdad score","تقييم شهداد")}/></div><div className="lv-breakdown"><LawyerScoreRow icon="clock" label={L("سابقه","Experience","الخبرة")} value={selected.scores.experience}/><LawyerScoreRow icon="scale" label={L("تخصص","Expertise","التخصص")} value={selected.scores.specialty}/><LawyerScoreRow icon="shieldCheck" label={L("مهارت","Skill","المهارة")} value={selected.scores.skill}/><LawyerScoreRow icon="cap" label={L("تحصیلات","Education","التعليم")} value={selected.scores.education}/></div><div className="lv-client-score"><span><Ic.group size={18}/>{L("میانگین امتیاز موکلان","Client rating average","متوسط تقييم العملاء")}</span><strong>{selected.clients.toFixed(1)}<small>/۵</small></strong><LawyerStars value={selected.clients} label={L("امتیاز موکلان","Client rating","تقييم العملاء")}/><em>{fmt(selected.reviews,lang)} {L("نظر ثبت‌شده","reviews","تقييماً")}</em></div></div>
          <small className="lv-demo"><Ic.shieldAlert size={13}/>{L("بیو، تحصیلات، تخصص و امتیازهای این نمونه برای ارزیابی طراحی نمایش داده شده‌اند.","Biography, education, specialties and ratings are demo content for design review.","المعلومات التفصيلية تجريبية لمراجعة التصميم.")}</small>
        </div>
        <div className="lv-actions"><button className="btn primary"><Ic.cal size={15}/>{L("درخواست مشاوره","Request consultation","طلب استشارة")}</button><button className="btn ghost"><Ic.idcard size={15}/>{L("پروفایل کامل","Full profile","الملف الكامل")}</button></div>
      </aside>}
    </div>:<div className="lv-empty"><Ic.search size={28}/><h3>{L("وکیلی با این مشخصات پیدا نشد","No matching lawyer found","لا يوجد محامٍ مطابق")}</h3><button className="btn ghost" onClick={()=>{setQuery("");setCity("all");setSpecialty("all");setCenter("all")}}>{L("پاک کردن فیلترها","Clear filters","مسح الفلاتر")}</button></div>}
  </section>;
};

const CaseView = ({ lang }) => (
  <div>
    <div className="between mt-2" style={{marginBottom: 14}}>
      <div className="searchbar" style={{maxWidth:340, height:36}}>
        <Ic.search size={14}/><input placeholder={lang==="fa"?"جستجو در پرونده‌ها...":"Search cases..."} />
      </div>
      <div className="flex gap-2">
        <button className="btn ghost"><Ic.scroll size={14}/> {lang==="fa"?"خروجی":"Export"}</button>
        <button className="btn primary"><Ic.plus size={14}/> {lang==="fa"?"پرونده جدید":"New case"}</button>
      </div>
    </div>
    <table className="table">
      <thead><tr>
        <th>#</th>
        <th>{lang==="fa"?"عنوان":"Title"}</th>
        <th>{lang==="fa"?"نوع":"Type"}</th>
        <th>{lang==="fa"?"وکیل":"Lawyer"}</th>
        <th>{lang==="fa"?"تاریخ":"Date"}</th>
        <th>{lang==="fa"?"اولویت":"Priority"}</th>
        <th>{lang==="fa"?"وضعیت":"Status"}</th>
      </tr></thead>
      <tbody>
        {CASES.map((c) => {
          const st = STATUS_PILL[c.status];
          const prk = c.priority === "high" ? "danger" : c.priority === "med" ? "warn" : "neutral";
          const prl = c.priority === "high" ? (lang==="fa"?"بالا":"High") : c.priority === "med" ? (lang==="fa"?"متوسط":"Med") : (lang==="fa"?"پایین":"Low");
          return (
            <tr key={c.id}>
              <td className="fa-num">{c.id}</td>
              <td>{c.title[lang]}</td>
              <td>{c.type[lang]}</td>
              <td>{c.lawyer[lang]}</td>
              <td className="fa-num">{c.date[lang]}</td>
              <td><span className={"pill " + prk}>{prl}</span></td>
              <td><span className={"pill " + st.kind}>{st[lang]}</span></td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </div>
);

const ContractsView = ({ lang }) => (
  <div>
    <div className="between mt-2" style={{marginBottom: 14}}>
      <div className="tabs">
        <div className="tab on">{lang==="fa"?"همه":"All"}</div>
        <div className="tab">{lang==="fa"?"پیش‌نویس":"Drafts"}</div>
        <div className="tab">{lang==="fa"?"بازبینی":"Review"}</div>
        <div className="tab">{lang==="fa"?"امضا شده":"Signed"}</div>
      </div>
      <button className="btn gold">
        <Ic.bot size={14}/> {lang==="fa"?"قرارداد جدید با AI":"New contract with AI"}
      </button>
    </div>
    <table className="table">
      <thead><tr>
        <th>{lang==="fa"?"شناسه":"ID"}</th>
        <th>{lang==="fa"?"عنوان":"Title"}</th>
        <th>{lang==="fa"?"نوع":"Type"}</th>
        <th>{lang==="fa"?"تاریخ":"Date"}</th>
        <th>{lang==="fa"?"امتیاز ریسک":"Risk score"}</th>
        <th>{lang==="fa"?"وضعیت":"Status"}</th>
      </tr></thead>
      <tbody>
        {CONTRACTS.map((c) => {
          const st = STATUS_PILL[c.status];
          const rcol = c.risk > 50 ? "danger" : c.risk > 25 ? "warn" : "ok";
          return (
            <tr key={c.id}>
              <td className="fa-num">{c.id}</td>
              <td>{c.title[lang]}</td>
              <td>{c.type[lang]}</td>
              <td className="fa-num">{c.date[lang]}</td>
              <td>
                <div style={{display:"flex", alignItems:"center", gap:8}}>
                  <div style={{width:60, height:4, background:"rgba(168,213,232,0.15)", borderRadius:4, overflow:"hidden"}}>
                    <div style={{width:c.risk+"%", height:"100%", background: rcol==="danger"?"var(--danger)":rcol==="warn"?"var(--gold)":"var(--sage)"}}/>
                  </div>
                  <span className={"pill " + rcol}>{fmt(c.risk, lang)}</span>
                </div>
              </td>
              <td><span className={"pill " + st.kind}>{st[lang]}</span></td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </div>
);

const RiskView = ({ lang }) => {
  const score = 78;
  const c = 2 * Math.PI * 64;
  const off = c * (1 - score/100);
  return (
    <div>
      <div className="row" style={{alignItems:"center", gap: 24}}>
        <div className="risk-ring">
          <svg viewBox="0 0 160 160">
            <circle cx="80" cy="80" r="64" stroke="rgba(168,213,232,0.12)" strokeWidth="10" fill="none"/>
            <circle cx="80" cy="80" r="64" stroke="url(#riskg)" strokeWidth="10" fill="none"
              strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off}
              style={{transition:"stroke-dashoffset 1.5s ease"}}/>
            <defs>
              <linearGradient id="riskg" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0" stopColor="#00D4FF"/>
                <stop offset="1" stopColor="#C9A96E"/>
              </linearGradient>
            </defs>
          </svg>
          <div className="label">
            <div>
              <div className="n fa-num">{fmt(score, lang)}</div>
              <div className="l">{lang==="fa"?"امتیاز ریسک":"RISK SCORE"}</div>
            </div>
          </div>
        </div>
        <div style={{flex:1}}>
          <h4 style={{fontSize:13, fontWeight:600, color:"var(--ice-white)"}}>
            {lang==="fa"?"وضعیت ریسک: متوسط":"Risk level: Moderate"}
          </h4>
          <p style={{fontSize:12, color:"var(--frost)", marginTop:8, lineHeight:1.7}}>
            {lang==="fa"
              ? "تحلیل هوشمند ۴ بند از قرارداد را در سطح ریسک متوسط شناسایی کرده است. پیشنهاد می‌شود قبل از امضا، بندهای ۱۲ و ۱۸ بازنگری شوند."
              : "AI analysis flagged 4 clauses as moderate risk. Sections 12 and 18 are recommended for review before signing."}
          </p>
          <div className="kpi-grid" style={{gridTemplateColumns:"repeat(3, 1fr)", marginTop:14}}>
            <div className="kpi"><div className="n fa-num">{fmt(4, lang)}</div><div className="l">{lang==="fa"?"بند پرریسک":"High-risk clauses"}</div></div>
            <div className="kpi"><div className="n fa-num">{fmt(11, lang)}</div><div className="l">{lang==="fa"?"بند بازبینی":"Review items"}</div></div>
            <div className="kpi"><div className="n fa-num">{fmt(92, lang)}<small style={{fontSize:14}}>%</small></div><div className="l">{lang==="fa"?"اطمینان مدل":"Model confidence"}</div></div>
          </div>
        </div>
      </div>
      <div style={{marginTop:18, padding:14, borderRadius:12, border:"1px dashed var(--line-strong)", background:"rgba(0,212,255,0.04)", textAlign:"center"}}>
        <div style={{fontSize:12, color:"var(--frost)"}}>
          {lang==="fa"?"قرارداد یا سند خود را برای تحلیل بکشید و رها کنید":"Drag and drop your contract for analysis"}
        </div>
        <button className="btn primary" style={{marginTop:10}}>
          <Ic.paperclip size={14}/> {lang==="fa"?"انتخاب فایل":"Choose file"}
        </button>
      </div>
    </div>
  );
};

const LegacyCalcView = ({ lang }) => {
  const [tab, setTab] = React.useState("inh");
  const [v, setV] = React.useState({ estate: 1000, sons: 2, daughters: 1, wife: true });

  // Simplified inheritance calculation for demo
  const computeInh = () => {
    let total = v.estate;
    let wifeShare = v.wife ? total / 8 : 0;
    let rem = total - wifeShare;
    let unit = rem / (v.sons * 2 + v.daughters);
    return {
      wife: Math.round(wifeShare),
      son: Math.round(unit * 2),
      daughter: Math.round(unit),
      total: Math.round(total)
    };
  };
  const inh = computeInh();
  return (
    <div>
      <div className="tabs">
        <div className={"tab" + (tab==="inh"?" on":"")} onClick={() => setTab("inh")}>{lang==="fa"?"ارث":"Inheritance"}</div>
        <div className={"tab" + (tab==="mhr"?" on":"")} onClick={() => setTab("mhr")}>{lang==="fa"?"مهریه":"Mahrieh"}</div>
        <div className={"tab" + (tab==="diy"?" on":"")} onClick={() => setTab("diy")}>{lang==="fa"?"دیه":"Diye"}</div>
      </div>
      {tab === "inh" && (
        <div className="row" style={{marginTop: 12, alignItems:"stretch"}}>
          <div style={{flex:1}}>
            <div className="field" style={{marginBottom:10}}>
              <label>{lang==="fa"?"ارزش کل ترکه (میلیون تومان)":"Total estate (M IRR)"}</label>
              <input type="number" value={v.estate} onChange={e=>setV({...v,estate:+e.target.value})}/>
            </div>
            <div className="row">
              <div className="field"><label>{lang==="fa"?"تعداد پسر":"Sons"}</label>
                <input type="number" value={v.sons} onChange={e=>setV({...v,sons:+e.target.value})}/>
              </div>
              <div className="field"><label>{lang==="fa"?"تعداد دختر":"Daughters"}</label>
                <input type="number" value={v.daughters} onChange={e=>setV({...v,daughters:+e.target.value})}/>
              </div>
            </div>
            <div className="field" style={{marginTop:10}}>
              <label>
                <input type="checkbox" checked={v.wife} onChange={e=>setV({...v,wife:e.target.checked})} style={{marginInlineEnd:8}}/>
                {lang==="fa"?"دارای همسر":"Has spouse"}
              </label>
            </div>
            <button className="btn primary mt-3"><Ic.bot size={14}/> {lang==="fa"?"محاسبه با AI":"Calculate with AI"}</button>
          </div>
          <div style={{flex:1}}>
            <div className="calc-result">
              <div className="l">{lang==="fa"?"نتیجه محاسبه ارث":"INHERITANCE RESULT"}</div>
              <div className="n fa-num">{fmt(inh.total, lang)}<small style={{fontSize:14, color:"var(--frost)"}}> M</small></div>
              <div className="s">{lang==="fa"?"بر اساس فقه شیعه (نظام ولاء)":"Based on Shia jurisprudence"}</div>
              <div className="breakdown">
                {v.wife && <div className="li"><span>{lang==="fa"?"سهم همسر (۱/۸)":"Spouse (1/8)"}</span><b className="fa-num">{fmt(inh.wife, lang)}</b></div>}
                {v.sons > 0 && <div className="li"><span>{lang==="fa"?`سهم هر پسر`:`Each son`}</span><b className="fa-num">{fmt(inh.son, lang)}</b></div>}
                {v.daughters > 0 && <div className="li"><span>{lang==="fa"?`سهم هر دختر`:`Each daughter`}</span><b className="fa-num">{fmt(inh.daughter, lang)}</b></div>}
              </div>
            </div>
          </div>
        </div>
      )}
      {tab === "mhr" && (
        <div className="row" style={{marginTop:12}}>
          <div style={{flex:1}}>
            <div className="field"><label>{lang==="fa"?"مهریه (سکه)":"Mahrieh (coins)"}</label><input type="number" defaultValue="110"/></div>
            <div className="field mt-2"><label>{lang==="fa"?"قیمت روز سکه (میلیون تومان)":"Coin price today (M IRR)"}</label><input type="number" defaultValue="28"/></div>
            <button className="btn primary mt-3"><Ic.calc size={14}/> {lang==="fa"?"محاسبه به نرخ روز":"Calculate at today's rate"}</button>
          </div>
          <div style={{flex:1}}>
            <div className="calc-result">
              <div className="l">{lang==="fa"?"مهریه به نرخ روز":"MAHRIEH AT TODAY'S RATE"}</div>
              <div className="n fa-num">{fmt(3080, lang)}<small style={{fontSize:14, color:"var(--frost)"}}> M IRR</small></div>
              <div className="s">{lang==="fa"?"۱۱۰ سکه بهار آزادی × قیمت روز":"110 Bahar Azadi coins × today's rate"}</div>
            </div>
          </div>
        </div>
      )}
      {tab === "diy" && (
        <div className="row" style={{marginTop:12}}>
          <div style={{flex:1}}>
            <div className="field"><label>{lang==="fa"?"نوع آسیب":"Injury type"}</label>
              <select><option>{lang==="fa"?"شکستگی":"Fracture"}</option><option>{lang==="fa"?"جراحت":"Wound"}</option></select>
            </div>
            <div className="field mt-2"><label>{lang==="fa"?"ماه ارتکاب":"Month"}</label>
              <select><option>{lang==="fa"?"ماه حرام":"Sacred month"}</option><option>{lang==="fa"?"عادی":"Regular"}</option></select>
            </div>
            <button className="btn primary mt-3">{lang==="fa"?"محاسبه دیه ۱۴۰۲":"Compute 2026 Diye"}</button>
          </div>
          <div style={{flex:1}}>
            <div className="calc-result">
              <div className="l">{lang==="fa"?"دیه قابل پرداخت":"PAYABLE DIYE"}</div>
              <div className="n fa-num">{fmt(960, lang)}<small style={{fontSize:14, color:"var(--frost)"}}> M IRR</small></div>
              <div className="s">{lang==="fa"?"بر اساس دیه کامل ۱۴۰۲ × ۲٪":"Based on full Diye 2026 × 2%"}</div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const CALC_TOOLS = [
  { id:"delay", icon:"clock", fa:"خسارت تأخیر تأدیه", en:"Delay damages" },
  { id:"mahr", icon:"gem", fa:"مهریه به نرخ روز", en:"Mahr at current value" },
  { id:"execution", icon:"scale", fa:"نیم‌عشر اجرایی", en:"Execution fee" },
  { id:"court", icon:"briefcase", fa:"هزینه دادرسی", en:"Court fee" },
  { id:"arbitration", icon:"handshake", fa:"حق‌الزحمه داوری", en:"Arbitration fee" },
  { id:"inheritance", icon:"users", fa:"سهم‌الارث", en:"Inheritance" },
  { id:"diye", icon:"shield", fa:"دیه و ارش", en:"Diye & arsh" },
  { id:"expert", icon:"search", fa:"دستمزد کارشناسی", en:"Expert fee" },
  { id:"landExpert", icon:"home", fa:"هزینه کارشناسی تعیین تکلیف", en:"Property expert fee" },
  { id:"regionalProperty", icon:"home", fa:"ارزش منطقه‌ای املاک", en:"Regional property value" },
  { id:"office", icon:"file", fa:"دفتر خدمات قضایی", en:"Judicial office fee" },
  { id:"attorney", icon:"scroll", fa:"حق‌الوکاله و تمبر", en:"Attorney fee & stamp" }
];

const moneyFa = (n) => new Intl.NumberFormat("fa-IR", {maximumFractionDigits:0}).format(Math.max(0, Number(n)||0));
const latinDigits = (v) => String(v ?? "").replace(/[۰-۹]/g,d=>"۰۱۲۳۴۵۶۷۸۹".indexOf(d)).replace(/[٠-٩]/g,d=>"٠١٢٣٤٥٦٧٨٩".indexOf(d));
const cleanNumber = (v) => latinDigits(v).replace(/[٬،,\s]/g,"").replace(/[٫]/g,".").replace(/[^0-9.]/g,"").replace(/(\..*)\./g,"$1");
const nval = (v) => Math.max(0, Number(cleanNumber(v)) || 0);
const NumericInput = ({value,onValue,decimal=false,placeholder="مبلغ را وارد کنید"}) => {
  const [draft,setDraft] = React.useState(()=>String(value ?? ""));
  React.useEffect(()=>{
    const external = String(value ?? "");
    setDraft((current)=>current === external ? current : external);
  },[value]);
  const update = (raw) => {
    let next = cleanNumber(raw);
    if (!decimal) next = next.replace(/\./g, "");
    setDraft(next);
    onValue(next);
  };
  return <input
    type="text"
    inputMode={decimal?"decimal":"numeric"}
    pattern={decimal?"[0-9۰-۹٠-٩.,٫٬]*":"[0-9۰-۹٠-٩٬،,]*"}
    autoComplete="off"
    spellCheck={false}
    enterKeyHint="done"
    dir="ltr"
    data-numeric-input="true"
    placeholder={placeholder}
    value={draft}
    onChange={e=>update(e.currentTarget.value)}
    onCompositionEnd={e=>update(e.currentTarget.value)}
    onPaste={e=>{
      e.preventDefault();
      update(e.clipboardData.getData("text"));
    }}
  />;
};

const CompleteRegionalPropertyView = () => {
  const [resources,setResources]=React.useState(null),[province,setProvince]=React.useState("9303"),[city,setCity]=React.useState("11744"),[year,setYear]=React.useState("1405"),[block,setBlock]=React.useState("1-01"),[blockQuery,setBlockQuery]=React.useState(""),[landUse,setLandUse]=React.useState("residential"),[landArea,setLandArea]=React.useState(""),[width,setWidth]=React.useState("12"),[noAccess,setNoAccess]=React.useState(false),[outside,setOutside]=React.useState(false);
  const [hasBuilding,setHasBuilding]=React.useState(true),[buildingUse,setBuildingUse]=React.useState("residential_office"),[structure,setStructure]=React.useState("concrete_steel_metal"),[buildingArea,setBuildingArea]=React.useState(""),[parkingArea,setParkingArea]=React.useState(""),[storageArea,setStorageArea]=React.useState(""),[age,setAge]=React.useState(""),[floors,setFloors]=React.useState("1"),[commercialFloor,setCommercialFloor]=React.useState("0"),[stage,setStage]=React.useState("complete"),[special,setSpecial]=React.useState("none");
  React.useEffect(()=>{Promise.all([
    fetch("legal-data/regional-values/index.json?v=31.33").then(r=>r.json()),
    fetch("legal-data/regional-values/tehran-boundaries.json?v=31.33").then(r=>r.json()),
    ...["1405","1404"].map(y=>fetch(`legal-data/regional-values/tehran-${y}.json?v=31.33`).then(r=>r.json()))
  ]).then(([catalog,boundaries,y1405,y1404])=>{const byBlock=Object.fromEntries(boundaries.blocks.map(x=>[x.block,x]));const attach=(data)=>({...data,blocks:data.blocks.map(x=>({...x,...byBlock[x.block]}))});setResources({catalog,datasets:{"1405":attach(y1405),"1404":attach(y1404)}});}).catch(()=>setResources({error:true}));},[]);
  if(!resources)return <div className="calc-empty">در حال بارگذاری دفترچه‌های رسمی ارزش معاملاتی…</div>;
  if(resources.error)return <div className="calc-empty">بارگذاری دفترچه ارزش معاملاتی ناموفق بود.</div>;
  const {catalog,datasets}=resources;
  const provinceCities=catalog.cities.filter(x=>x.province_id===province);
  const selectedCity=catalog.cities.find(x=>x.id===city);
  const cityStatus={active:"فعال",in_progress:"در حال تکمیل در مرجع",legacy:"نسخه قدیمی",completed_label:"تکمیل‌شده"};
  const locationFields=<div className="calc-fields two"><div className="field"><label>استان</label><select value={province} onChange={e=>{const next=e.target.value;const list=catalog.cities.filter(x=>x.province_id===next);const preferred=list.find(x=>x.status==="active")||list[0];setProvince(next);setCity(preferred?.id||"");setBlock("1-01");}}>{catalog.provinces.map(x=><option value={x.id} key={x.id}>{x.name}</option>)}</select></div><div className="field"><label>شهر</label><select value={city} onChange={e=>{setCity(e.target.value);setBlock("1-01");}}>{provinceCities.map(x=><option value={x.id} key={x.id}>{x.name}{x.status!=="active"?` — ${cityStatus[x.status]||x.status}`:""}</option>)}</select></div></div>;
  const hasOfficialDataset=province==="9303"&&["9304","11744"].includes(city);
  if(!hasOfficialDataset)return <div className="calc-workspace regional-property"><div className="calc-form"><div className="calc-section-title">ارزش معاملاتی عرصه و اعیان</div>{locationFields}<div className="calc-hint">{selectedCity?.name||"شهر انتخابی"} در فهرست مرجع ثبت شده است. داده قیمت و محدوده بلوک‌های این شهر در حال اتصال به دفترچه رسمی ۱۴۰۵ است؛ تا پیش از تطبیق کامل، عدد تقریبی یا ساختگی نمایش داده نمی‌شود.</div></div><div className="calc-result legal-result"><div className="l">وضعیت پوشش</div><div className="n">{cityStatus[selectedCity?.status]||"ثبت‌شده"}</div><div className="legal-output">فهرست شامل {catalog.provinces.length.toLocaleString("fa-IR")} استان و {catalog.cities.length.toLocaleString("fa-IR")} ردیف شهر از سامانه مرجع است.</div></div></div>;
  const data=datasets[year];
  const row=data.blocks.find(x=>x.block===block)||data.blocks[0],land=data.land,building=data.building;
  const normalizedBlockQuery=blockQuery.trim().toLocaleLowerCase("fa-IR");
  const visibleBlocks=data.blocks.filter(x=>{const district=x.block.split("-")[0];const searchable=`${x.block} ${district} ${x.boundary||""} ${x.main_streets||""}`.toLocaleLowerCase("fa-IR");return !normalizedBlockQuery||searchable.includes(normalizedBlockQuery);});
  const describeBlock=(x)=>{const district=x.block.split("-")[0];const place=x.main_streets||x.boundary;return `منطقه ${district} · بلوک ${x.block}${place?` — ${place}`:""}`;};
  const landUses=[
    ["residential","مسکونی"],["office","اداری"],["commercial","تجاری"],
    ["service_education_culture_health_leisure_tourism_hotel","خدماتی، آموزشی، فرهنگی، درمانی، تفریحی، گردشگری و هتل‌داری"],
    ["industrial_workshop_transport_warehouse_parking","صنعتی، کارگاهی، حمل‌ونقل، انبار و توقفگاه"],
    ["agriculture_irrigated_garden_livestock_aquaculture_flower","باغ، زراعت آبی، دامداری، آبزیان و گل‌وگیاه"],
    ["agriculture_dry_farming","زراعت دیم"],["other","سایر یا فاقد کاربری"]
  ];
  const directBase=["residential","office","commercial"].includes(landUse)?row[landUse]:row.residential;
  const usageFactor=land.usage_factors[landUse]||1,widthRate=landUse==="commercial"?land.width_adjustment_per_meter.commercial:land.width_adjustment_per_meter.other;
  const widthCap=landUse==="residential"?land.width_increase_cap_m.residential:land.width_increase_cap_m.other;
  const effectiveWidth=Math.min(Math.max(0,nval(width)),widthCap),widthFactor=Math.max(0,1+(effectiveWidth-land.base_passage_width_m)*widthRate);
  const accessFactor=noAccess&&land.no_independent_access_factor?land.no_independent_access_factor:1,outsideFactor=outside?land.unpriced_outside_city_factor:1;
  const landRate=directBase*usageFactor*widthFactor*accessFactor*outsideFactor,landValue=landRate*nval(landArea);
  const buildingRate=building.rates_per_sqm_rial[buildingUse]?.[structure]||0;
  const floorFactor=buildingUse==="residential_office"?1+Math.max(0,Math.floor(nval(floors))-5)*building.residential_office_extra_floor_factor:buildingUse==="commercial"?1-Math.min(building.commercial_floor_discount_cap,Math.abs(Math.floor(Number(cleanNumber(commercialFloor))||0))*building.commercial_floor_discount):1;
  const ageFactor=1-Math.min(building.age_discount_cap,Math.floor(nval(age))*building.age_discount_per_year),stageFactor=building.unfinished_stage_factors[stage]||1,specialFactor=special==="none"?1:.5;
  const mainBuilding=buildingRate*nval(buildingArea)*floorFactor,annexBuilding=building.exclude_residential_parking_storage&&buildingUse==="residential_office"?0:buildingRate*(nval(parkingArea)+nval(storageArea))*building.parking_storage_factor*floorFactor;
  const buildingValue=hasBuilding?(mainBuilding+annexBuilding)*ageFactor*stageFactor*specialFactor:0,total=landValue+buildingValue,ready=nval(landArea)>0;
  return <div className="calc-workspace regional-property"><div className="calc-form"><div className="calc-section-title">ارزش معاملاتی عرصه و اعیان ـ تهران {year}</div>
    {locationFields}<div className="field"><label>سال دفترچه</label><select value={year} onChange={e=>{setYear(e.target.value);setNoAccess(false);}}><option value="1405">۱۴۰۵ ـ جاری</option><option value="1404">۱۴۰۴</option></select></div>
    <div className="field"><label>جست‌وجوی بلوک با شماره، منطقه یا نام خیابان</label><input value={blockQuery} onChange={e=>setBlockQuery(e.target.value)} placeholder="مثلاً منطقه ۱، بلوک 1-01 یا نام خیابان"/></div>
    <div className="field"><label>محدوده بلوک منطقه‌ای</label><select value={block} onChange={e=>setBlock(e.target.value)}>{visibleBlocks.map(x=><option value={x.block} key={x.block}>{describeBlock(x)}</option>)}</select>{visibleBlocks.length===0&&<div className="calc-hint">بلوک منطبق با جست‌وجو پیدا نشد.</div>}</div>
    {row.boundary&&<div className="block-boundary-card"><b>بلوک {row.block}{row.main_streets?` · خیابان‌های اصلی: ${row.main_streets}`:""}</b><div><span><strong>شمال:</strong> {row.north}</span><span><strong>شرق:</strong> {row.east}</span><span><strong>جنوب:</strong> {row.south}</span><span><strong>غرب:</strong> {row.west}</span></div></div>}
    <div className="calc-section-sub">مشخصات عرصه</div><div className="field"><label>نوع کاربری عرصه</label><select value={landUse} onChange={e=>setLandUse(e.target.value)}>{landUses.map(([v,l])=><option value={v} key={v}>{l}</option>)}</select></div>
    <div className="calc-fields two"><div className="field"><label>مساحت عرصه (مترمربع)</label><NumericInput value={landArea} onValue={setLandArea} decimal placeholder="مساحت عرصه"/></div><div className="field"><label>عرض معبر واقعی دسترسی (متر)</label><NumericInput value={width} onValue={setWidth} decimal placeholder="عرض معبر"/></div></div>
    {land.no_independent_access_factor&&<label className="calc-check"><input type="checkbox" checked={noAccess} onChange={e=>setNoAccess(e.target.checked)}/> ملک راه عبور مستقل ندارد و از ملک مجاور حق عبور دارد</label>}<label className="calc-check"><input type="checkbox" checked={outside} onChange={e=>setOutside(e.target.checked)}/> ملک در حریم قانونیِ فاقد ارزش تعیین‌شده قرار دارد</label>
    <label className="calc-check"><input type="checkbox" checked={hasBuilding} onChange={e=>setHasBuilding(e.target.checked)}/> ملک دارای اعیانی است</label>
    {hasBuilding&&<><div className="calc-section-sub">مشخصات اعیانی</div><div className="calc-fields two"><div className="field"><label>کاربری اعیانی</label><select value={buildingUse} onChange={e=>setBuildingUse(e.target.value)}><option value="commercial">تجاری</option><option value="residential_office">مسکونی و اداری</option><option value="service_industrial">خدماتی، صنعتی، درمانی، آموزشی، گردشگری، انبار و حمل‌ونقل</option><option value="agriculture">کشاورزی، دامداری، آبزیان و گل‌وگیاه</option></select></div><div className="field"><label>نوع سازه</label><select value={structure} onChange={e=>setStructure(e.target.value)}><option value="concrete_steel_metal">تمام‌بتن، اسکلت بتنی یا فلزی و سوله</option><option value="other">سایر</option></select></div></div>
    <div className="calc-fields two"><div className="field"><label>زیربنای اصلی (مترمربع)</label><NumericInput value={buildingArea} onValue={setBuildingArea} decimal placeholder="زیربنای اصلی"/></div><div className="field"><label>قدمت (سال)</label><NumericInput value={age} onValue={setAge} placeholder="قدمت بنا"/></div></div>
    <div className="calc-fields two"><div className="field"><label>پارکینگ (مترمربع)</label><NumericInput value={parkingArea} onValue={setParkingArea} decimal placeholder="مساحت پارکینگ"/></div><div className="field"><label>انباری (مترمربع)</label><NumericInput value={storageArea} onValue={setStorageArea} decimal placeholder="مساحت انباری"/></div></div>
    {buildingUse==="residential_office"&&<div className="field"><label>تعداد طبقات روی زمین (بدون زیرزمین و پیلوت)</label><NumericInput value={floors} onValue={setFloors} placeholder="تعداد طبقات"/></div>}
    {buildingUse==="commercial"&&<div className="field"><label>فاصله طبقه تجاری از همکف</label><select value={commercialFloor} onChange={e=>setCommercialFloor(e.target.value)}><option value="0">همکف</option><option value="1">یک طبقه بالاتر یا پایین‌تر</option><option value="2">دو طبقه بالاتر یا پایین‌تر</option><option value="3">سه طبقه یا بیشتر</option></select></div>}
    <div className="calc-fields two"><div className="field"><label>مرحله ساخت</label><select value={stage} onChange={e=>setStage(e.target.value)}><option value="complete">کامل</option><option value="foundation">فونداسیون ـ ۱۰٪</option><option value="skeleton">اسکلت ـ ۳۰٪</option><option value="rough_construction">سفت‌کاری ـ ۵۰٪</option><option value="finishing">نازک‌کاری ـ ۸۰٪</option></select></div><div className="field"><label>تخفیف انتقال اول</label><select value={special} onChange={e=>setSpecial(e.target.value)}><option value="none">ندارد</option><option value="worn">نوساز بافت فرسوده تا ۳ سال</option><option value="support">پروژه برنامه حمایتی دولت</option></select></div></div></>}
    <div className="calc-hint">برای ملکِ برِ بزرگراه یا راه‌آهن بدون دسترسی مستقیم، عرض معبر واقعی ورود به ملک را وارد کنید. {building.exclude_residential_parking_storage&&"طبق دفترچه ۱۴۰۵، پارکینگ و انباری متعلق به واحد مسکونی در ارزش اعیانی منظور نمی‌شود. "}مرز و معابر هر بلوک در مرحله تکمیل بانک جغرافیایی از سامانه مرجع افزوده می‌شود.</div>
  </div><div className="calc-result legal-result"><div className="l">جمع ارزش معاملاتی رسمی</div><div className="n">{ready?moneyFa(total):"—"} <small>{ready?"ریال":""}</small></div>{ready&&<div className="breakdown"><div className="li"><span>قیمت پایه عرصه بلوک</span><b>{moneyFa(directBase)} ریال/مترمربع</b></div><div className="li"><span>ضریب کاربری × عرض × دسترسی</span><b>{(usageFactor*widthFactor*accessFactor*outsideFactor).toLocaleString("fa-IR",{maximumFractionDigits:5})}</b></div><div className="li"><span>ارزش عرصه</span><b>{moneyFa(landValue)} ریال</b></div>{hasBuilding&&<><div className="li"><span>نرخ پایه اعیانی</span><b>{moneyFa(buildingRate)} ریال/مترمربع</b></div><div className="li"><span>ارزش اعیانی</span><b>{moneyFa(buildingValue)} ریال</b></div></>}</div>}
    <div className="legal-output">مبنای محاسبه: دفترچه رسمی ارزش معاملاتی املاک مناطق ۲۲گانه تهران، لازم‌الاجرا در سال {year}؛ صفحات ضوابط {data.source.rules_pages.join("، ")} و جدول بلوک‌ها {data.source.prices_pages[0]} تا {data.source.prices_pages.at(-1)}.</div><div className="legal-output">در محاسبه جاری، ۳۰٪ ارزش عرصه به نرخ اعیانی افزوده نشده است؛ این عبارت در دفترچه {year} وجود ندارد و تذکر مشابه دفترچه ۱۴۰۱ با رأی شماره ۴۴۵۶۷۰ هیأت عمومی دیوان عدالت اداری ابطال شده است.</div><button className="btn secondary" onClick={()=>window.print()}>چاپ یا ذخیره PDF</button>
  </div></div>;
};

const LegacyNationalRegionalPropertyView = () => {
  const [index,setIndex]=React.useState(null),[officialIndex,setOfficialIndex]=React.useState(null),[provinceData,setProvinceData]=React.useState(null),[province,setProvince]=React.useState(""),[location,setLocation]=React.useState(""),[year,setYear]=React.useState(""),[documentKind,setDocumentKind]=React.useState("transaction"),[data,setData]=React.useState(null),[rules,setRules]=React.useState(null),[record,setRecord]=React.useState(""),[query,setQuery]=React.useState("");
  const [landUse,setLandUse]=React.useState("residential"),[landArea,setLandArea]=React.useState(""),[width,setWidth]=React.useState("12"),[noAccess,setNoAccess]=React.useState(false),[outside,setOutside]=React.useState(false);
  const [hasBuilding,setHasBuilding]=React.useState(true),[buildingUse,setBuildingUse]=React.useState("residential_office"),[structure,setStructure]=React.useState("concrete_steel_metal"),[buildingArea,setBuildingArea]=React.useState(""),[parkingArea,setParkingArea]=React.useState(""),[storageArea,setStorageArea]=React.useState(""),[age,setAge]=React.useState(""),[floors,setFloors]=React.useState("1"),[commercialFloor,setCommercialFloor]=React.useState("0"),[stage,setStage]=React.useState("complete"),[special,setSpecial]=React.useState("none");
  React.useEffect(()=>{Promise.all([
    fetch("legal-data/regional-values/national/index.json?v=31.52").then(r=>{if(!r.ok)throw new Error("calculator-index");return r.json();}),
    fetch("legal-data/regional-values/official-documents/index.json?v=31.52").then(r=>{if(!r.ok)throw new Error("official-index");return r.json();})
  ]).then(([calculator,official])=>{setIndex(calculator);setOfficialIndex(official);const first=official.provinces.find(x=>x.available_years?.includes(1405))||official.provinces[0];setProvince(first?.name||"");}).catch(()=>setIndex({error:true}));},[]);
  const officialProvince=officialIndex?.provinces?.find(x=>x.name===province),allProvinceDocuments=provinceData?.documents||[],provinceCalculatorVariants=(index?.locations||[]).filter(x=>x.province===province);
  const calculatorPlaces=documentKind==="transaction"?provinceCalculatorVariants.filter((x,i,list)=>list.findIndex(y=>y.location_key===x.location_key)===i):[],calculatorPlaceNames=new Set(calculatorPlaces.map(x=>x.name));
  const tehranAggregateLabels=new Set(["غرب استان تهران","شرق استان تهران","جنوب استان تهران","شهرستان‌های استان تهران","شمیرانات"]);
  const documentPlaceNames=[...new Set(allProvinceDocuments.filter(x=>x.kind===documentKind).flatMap(x=>x.sub_locations?.length?x.sub_locations:[x.location]))].filter(x=>!calculatorPlaceNames.has(x)).filter(x=>province!=="تهران"||!tehranAggregateLabels.has(x));
  const documentPlaces=documentPlaceNames.map(location=>({location}));
  const selectedLocationKey=location.startsWith("calc:")?location.slice(5):"",selectedPlaceName=location.startsWith("place:")?location.slice(6):(calculatorPlaces.find(x=>x.location_key===selectedLocationKey)?.name||"");
  const placeCalculatorVariants=provinceCalculatorVariants.filter(x=>x.location_key===selectedLocationKey),placeDocuments=allProvinceDocuments.filter(x=>x.kind===documentKind&&(x.location===selectedPlaceName||x.sub_locations?.includes(selectedPlaceName)));
  const yearOptions=[...new Set([...placeCalculatorVariants.map(x=>Number(x.effective_year)),...placeDocuments.map(x=>Number(x.effective_year))])].filter(Boolean).sort((a,b)=>b-a).map(String);
  const selectedLocation=placeCalculatorVariants.find(x=>String(x.effective_year)===year),selectedDocuments=placeDocuments.filter(x=>String(x.effective_year)===year),selectedDocument=selectedDocuments.find(x=>x.source_url===selectedLocation?.source_url)||selectedDocuments[0]||allProvinceDocuments.find(x=>x.source_url===selectedLocation?.source_url);
  React.useEffect(()=>{if(!officialProvince){setProvinceData(null);return;}setProvinceData(null);fetch(`${officialProvince.data_url}?v=31.52`).then(r=>{if(!r.ok)throw new Error("province-documents");return r.json();}).then(setProvinceData).catch(()=>setProvinceData({error:true,documents:[]}));setLocation("");setYear("");setData(null);setRules(null);setRecord("");setQuery("");setLandArea("");setBuildingArea("");setParkingArea("");setStorageArea("");},[province,officialIndex]);
  React.useEffect(()=>{const first=calculatorPlaces[0],document=documentPlaces[0];setLocation(first?`calc:${first.location_key}`:document?`place:${document.location}`:"");},[province,documentKind,provinceData,index]);
  React.useEffect(()=>{setYear(yearOptions.includes("1405")?"1405":(yearOptions[0]||""));},[location,documentKind,provinceData,index]);
  React.useEffect(()=>{if(!location||!year){setData(null);setRules(null);return;}const item=selectedLocation;if(!item){setData({unavailable:true});setRules(null);setRecord("");return;}const isTehranCurrent=item.province==="تهران"&&item.name==="تهران"&&String(item.effective_year)==="1405",mainRequest=fetch(`${item.data_url}?v=31.52`).then(r=>{if(!r.ok)throw new Error("document");return r.json();}),boundaryUrl=item.boundaries_url||(isTehranCurrent?"legal-data/regional-values/tehran-boundaries.json":null),rulesUrl=item.rules_url||(isTehranCurrent?"legal-data/regional-values/tehran-1405.json":null),boundaryRequest=boundaryUrl?fetch(`${boundaryUrl}?v=31.52`).then(r=>r.ok?r.json():null).catch(()=>null):Promise.resolve(null),rulesRequest=rulesUrl?fetch(`${rulesUrl}?v=31.52`).then(r=>r.ok?r.json():null).catch(()=>null):Promise.resolve(null);Promise.all([mainRequest,boundaryRequest,rulesRequest]).then(([payload,boundaries,rulesPayload])=>{let blocks=payload.blocks;if(boundaries?.blocks){const byBlock=Object.fromEntries(boundaries.blocks.map(x=>[x.block,x]));blocks=payload.blocks.map(x=>({...x,...byBlock[x.block],id:x.id||x.block,description:byBlock[x.block]?.main_streets||byBlock[x.block]?.boundary||x.description||null}));}setData({...payload,blocks});setRules(rulesPayload||((payload.land&&payload.building)?payload:null));setRecord(blocks[0]?.id||"");}).catch(()=>setData({error:true}));},[location,year,index]);
  if(!index||!officialIndex)return <div className="calc-empty">در حال بارگذاری بانک رسمی سالانه ارزش معاملاتی املاک…</div>;
  if(index.error||officialIndex.error)return <div className="calc-empty">بارگذاری بانک رسمی سالانه ناموفق بود.</div>;
  const provinceInfo=index.provinces.find(x=>x.name===province),normalized=query.trim().toLocaleLowerCase("fa-IR");
  const visible=data?.blocks?.filter(x=>!normalized||`${x.block} ${x.description||""} ${x.locality||""} ${Object.values(x.boundary||{}).join(" ")}`.toLocaleLowerCase("fa-IR").includes(normalized))||[];
  const row=visible.find(x=>x.id===record)||visible[0]||data?.blocks?.[0];
  const rulesRow=rules?.blocks?.find(x=>x.block===row?.block)||rules?.blocks?.find(x=>x.id===row?.id),land=rules?.land||rulesRow?.land,building=rules?.building||rulesRow?.building,hasRules=Boolean(land&&building);
  const directUses=["residential","office","commercial"],landUses=[["residential","مسکونی"],["office","اداری"],["commercial","تجاری"],["service_education_culture_health_leisure_tourism_hotel","خدماتی، آموزشی، فرهنگی، درمانی، تفریحی، گردشگری و هتل‌داری"],["industrial_workshop_transport_warehouse_parking","صنعتی، کارگاهی، حمل‌ونقل، انبار و توقفگاه"],["agriculture_irrigated_garden_livestock_aquaculture_flower","باغ، زراعت آبی، دامداری، آبزیان و گل‌وگیاه"],["agriculture_dry_farming","زراعت دیم"],["other","سایر یا فاقد کاربری"]];
  const directBase=directUses.includes(landUse)?(row?.[landUse]||0):(hasRules?(row?.residential||0):0),usageFactor=land?.usage_factors?.[landUse]||1,widthRate=landUse==="commercial"?land?.width_adjustment_per_meter?.commercial||0:land?.width_adjustment_per_meter?.other||0,widthCap=landUse==="residential"?land?.width_increase_cap_m?.residential||0:land?.width_increase_cap_m?.other||0,effectiveWidth=land?Math.min(Math.max(0,nval(width)),widthCap):0,widthFactor=land?Math.max(0,1+(effectiveWidth-(land.base_passage_width_m||12))*widthRate):1,accessFactor=noAccess&&land?.no_independent_access_factor?land.no_independent_access_factor:1,outsideFactor=outside&&land?.unpriced_outside_city_factor?land.unpriced_outside_city_factor:1,landRate=directBase*usageFactor*widthFactor*accessFactor*outsideFactor,landValue=landRate*nval(landArea);
  const buildingRate=building?.rates_per_sqm_rial?.[buildingUse]?.[structure]||0,floorsValue=Math.floor(nval(floors))||0,floorFactor=!building?1:buildingUse==="residential_office"?1+Math.max(0,floorsValue-(building.residential_office_extra_floor_starts_at||6)+1)*(building.residential_office_extra_floor_factor||0):buildingUse==="commercial"?1-Math.min(building.commercial_floor_discount_cap||0,Math.abs(Math.floor(nval(commercialFloor)))*(building.commercial_floor_discount||0)):1,ageFactor=building?1-Math.min(building.age_discount_cap||0,Math.floor(nval(age))*(building.age_discount_per_year||0)):1,stageFactor=building?.unfinished_stage_factors?.[stage]||1,specialFactor=special==="none"?1:(building?.worn_fabric_new_first_transfer_factor||.5),mainBuilding=buildingRate*nval(buildingArea)*floorFactor,annexBuilding=building&&building.exclude_residential_parking_storage&&buildingUse==="residential_office"?0:buildingRate*(nval(parkingArea)+nval(storageArea))*(building?.parking_storage_factor||.5)*floorFactor,buildingValue=hasBuilding&&hasRules?(mainBuilding+annexBuilding)*ageFactor*stageFactor*specialFactor:0,total=landValue+buildingValue,ready=Boolean(row)&&nval(landArea)>0&&directBase>0;
  const sourceStatus={ok:"فایل رسمی سالم و در آرشیو کنترل شده است",missing_from_official_server:"پیوند در فهرست رسمی وجود دارد، اما سرور فایل قابل دریافت برنگرداند",source_zero_filled:"فایل منتشرشده در منبع رسمی معیوب و تماماً خالی است",catalog_only:"رکورد در فهرست رسمی ثبت شده است"};
  const boundaryLabel=(x)=>{const raw=x.description||x.locality||"",place=String(raw).trim()===String(x.block).trim()?"":raw,short=place&&place.length>220?`${place.slice(0,220)}…`:place;return `بلوک ${x.block}${short?` — ${short}`:" — شرح محدوده در دفترچه"}`;};
  return <div className="calc-workspace regional-property"><div className="calc-form"><div className="calc-section-title">ارزش معاملاتی و اجاری املاک ـ بانک رسمی کشور</div>
    <div className="calc-fields two"><div className="field"><label>استان</label><select value={province} onChange={e=>setProvince(e.target.value)}>{officialIndex.provinces.map(x=><option value={x.name} key={x.name}>{x.name} ({x.document_count.toLocaleString("fa-IR")} سند)</option>)}</select></div><div className="field"><label>شهر / محدوده رسمی</label><select value={location} onChange={e=>setLocation(e.target.value)} disabled={!calculatorPlaces.length&&!documentPlaces.length}>{calculatorPlaces.length||documentPlaces.length?<>{calculatorPlaces.length>0&&<optgroup label="دارای جدول محاسباتی">{calculatorPlaces.map(x=><option value={`calc:${x.location_key}`} key={`calc:${x.location_key}`}>{x.name}</option>)}</optgroup>}{documentPlaces.length>0&&<optgroup label="سایر محدوده‌های موجود در اسناد رسمی">{documentPlaces.map(x=><option value={`place:${x.location}`} key={`place:${x.location}`}>{x.location}</option>)}</optgroup>}</>:<option>محدوده رسمی ثبت نشده است</option>}</select></div></div>
    <div className="calc-fields two"><div className="field"><label>سال اجرای دفترچه این شهر</label><select value={year} onChange={e=>setYear(e.target.value)} disabled={!yearOptions.length}>{yearOptions.map((y,i)=><option value={y} key={y}>{y}{y==="1405"?" — سال جاری":i===0?" — جدیدترین موجود":""}</option>)}</select></div><div className="field"><label>نوع دفترچه</label><select value={documentKind} onChange={e=>setDocumentKind(e.target.value)}><option value="transaction">ارزش معاملاتی عرصه و اعیان</option><option value="rental">ارزش اجاری املاک</option></select></div></div>
    <div className="calc-hint">بانک رسمی شامل {officialIndex.document_count.toLocaleString("fa-IR")} سند از {officialIndex.province_count.toLocaleString("fa-IR")} استان است: {officialIndex.kind_counts.transaction.toLocaleString("fa-IR")} دفترچه معاملاتی و {officialIndex.kind_counts.rental.toLocaleString("fa-IR")} دفترچه اجاری. از میان آن‌ها {index.calculator_dataset_count.toLocaleString("fa-IR")} دفترچه با {index.calculator_block_count.toLocaleString("fa-IR")} ردیف نرخ و محدوده برای محاسبه ساختاری شده است.</div>
    {provinceData?.error&&<div className="calc-hint">فهرست رسمی این استان بارگذاری نشد.</div>}
    {data?.unavailable&&selectedDocument&&<div className="block-boundary-card"><b>{selectedDocument.title}</b><div><span>سال اجرا: {selectedDocument.effective_year||"نامشخص"}</span><span>نوع: {selectedDocument.kind==="rental"?"ارزش اجاری":"ارزش معاملاتی"}</span>{selectedDocument.publication_date&&<span>تاریخ انتشار: {selectedDocument.publication_date}</span>}{selectedDocument.source_size&&<span>حجم اعلامی: {selectedDocument.source_size}</span>}<span>{sourceStatus[selectedDocument.status]||"در فهرست رسمی ثبت شده است"}</span></div><a className="btn secondary" href={selectedDocument.source_url} target="_blank" rel="noreferrer">مشاهده و دریافت فایل رسمی</a></div>}
    {documentKind==="rental"&&<div className="calc-hint">دفترچه‌های اجاری برای مشاهده و استناد در دسترس‌اند. محاسبه عرصه و اعیان فقط با دفترچه ارزش معاملاتی انجام می‌شود.</div>}
    {data&&!data.error&&!data.unavailable&&<><div className="field"><label>جست‌وجوی بلوک، محدوده یا خیابان</label><input value={query} onChange={e=>setQuery(e.target.value)} placeholder="مثلاً ۲۳ یا نام خیابان"/></div><div className="field"><label>بلوک و محدوده</label><select value={row?.id||""} onChange={e=>setRecord(e.target.value)}>{visible.map(x=><option value={x.id} key={x.id}>{boundaryLabel(x)}</option>)}</select>{visible.length===0&&<div className="calc-hint">بلوک منطبق با جست‌وجو پیدا نشد.</div>}</div>{row&&(row.description||row.boundary)&&<div className="block-boundary-card"><b>بلوک {row.block} — شرح محدوده رسمی</b>{row.boundary&&Object.values(row.boundary).some(Boolean)?<div>{row.boundary.north&&<span><strong>شمال:</strong> {row.boundary.north}</span>}{row.boundary.east&&<span><strong>شرق:</strong> {row.boundary.east}</span>}{row.boundary.south&&<span><strong>جنوب:</strong> {row.boundary.south}</span>}{row.boundary.west&&<span><strong>غرب:</strong> {row.boundary.west}</span>}</div>:<div><span>{row.description}</span></div>}</div>}
    <div className="calc-section-sub">مشخصات عرصه</div><div className="field"><label>نوع کاربری عرصه</label><select value={landUse} onChange={e=>setLandUse(e.target.value)}>{landUses.map(([v,l])=><option value={v} key={v} disabled={!hasRules&&!directUses.includes(v)}>{l}{!hasRules&&!directUses.includes(v)?" — نیازمند ضریب همان دفترچه":""}</option>)}</select></div><div className="calc-fields two"><div className="field"><label>مساحت عرصه (مترمربع)</label><NumericInput value={landArea} onValue={setLandArea} decimal placeholder="مساحت عرصه"/></div><div className="field"><label>عرض معبر واقعی دسترسی (متر)</label><NumericInput value={width} onValue={setWidth} decimal placeholder="عرض معبر"/></div></div>
    <label className="calc-check"><input type="checkbox" checked={noAccess} onChange={e=>setNoAccess(e.target.checked)} disabled={!land?.no_independent_access_factor}/> ملک راه عبور مستقل ندارد</label><label className="calc-check"><input type="checkbox" checked={outside} onChange={e=>setOutside(e.target.checked)} disabled={!land?.unpriced_outside_city_factor}/> ملک خارج از محدوده دارای ارزش تعیین‌شده قرار دارد</label>
    <div className="calc-section-sub">مشخصات اعیان</div><label className="calc-check"><input type="checkbox" checked={hasBuilding&&hasRules} onChange={e=>setHasBuilding(e.target.checked)} disabled={!hasRules}/> ملک دارای اعیانی است</label>{hasRules&&hasBuilding&&<><div className="calc-fields two"><div className="field"><label>کاربری اعیانی</label><select value={buildingUse} onChange={e=>setBuildingUse(e.target.value)}><option value="commercial">تجاری</option><option value="residential_office">مسکونی و اداری</option><option value="service_industrial">خدماتی، صنعتی، درمانی، آموزشی و انبار</option><option value="agriculture">کشاورزی و دامداری</option></select></div><div className="field"><label>نوع سازه</label><select value={structure} onChange={e=>setStructure(e.target.value)}><option value="concrete_steel_metal">تمام‌بتن، اسکلت بتنی یا فلزی و سوله</option><option value="other">سایر</option></select></div></div><div className="calc-fields two"><div className="field"><label>زیربنای اصلی (مترمربع)</label><NumericInput value={buildingArea} onValue={setBuildingArea} decimal placeholder="زیربنای اصلی"/></div><div className="field"><label>قدمت بنا (سال)</label><NumericInput value={age} onValue={setAge} placeholder="قدمت بنا"/></div></div><div className="calc-fields two"><div className="field"><label>پارکینگ (مترمربع)</label><NumericInput value={parkingArea} onValue={setParkingArea} decimal placeholder="مساحت پارکینگ"/></div><div className="field"><label>انباری (مترمربع)</label><NumericInput value={storageArea} onValue={setStorageArea} decimal placeholder="مساحت انباری"/></div></div><div className="field"><label>تعداد طبقات روی زمین</label><NumericInput value={floors} onValue={setFloors} placeholder="تعداد طبقات"/></div>{buildingUse==="commercial"&&<div className="field"><label>فاصله طبقه تجاری از همکف</label><select value={commercialFloor} onChange={e=>setCommercialFloor(e.target.value)}><option value="0">همکف</option><option value="1">یک طبقه بالاتر یا پایین‌تر</option><option value="2">دو طبقه</option><option value="3">سه طبقه یا بیشتر</option></select></div>}<div className="field"><label>مرحله ساخت</label><select value={stage} onChange={e=>setStage(e.target.value)}><option value="foundation">فونداسیون</option><option value="skeleton">اسکلت</option><option value="rough_construction">سفت‌کاری</option><option value="finishing">نازک‌کاری</option><option value="complete">تکمیل‌شده</option></select></div><div className="field"><label>وضعیت انتقال اول</label><select value={special} onChange={e=>setSpecial(e.target.value)}><option value="none">عادی</option><option value="worn">بافت فرسوده / انتقال اول</option></select></div></>}
    {!hasRules&&<div className="calc-hint">در این دفترچه فعلاً نرخ مستقیم عرصه برای کاربری‌های مسکونی، اداری و تجاری قابل محاسبه است. محاسبه اعیان و سایر کاربری‌ها تا استخراج ضرایب همان سند غیرفعال مانده و هیچ ضریب استان دیگری جایگزین نشده است.</div>}</>}
  </div><div className="calc-result legal-result"><div className="l">{documentKind==="rental"?"دفترچه رسمی ارزش اجاری":"ارزش کل قابل محاسبه"}</div><div className="n">{ready?moneyFa(total):"—"} <small>{ready?"ریال":""}</small></div>{ready&&<div className="breakdown"><div className="li"><span>ارزش عرصه</span><b>{moneyFa(landValue)} ریال</b></div>{hasRules&&<div className="li"><span>ارزش اعیان</span><b>{moneyFa(buildingValue)} ریال</b></div>}<div className="li"><span>نرخ رسمی عرصه</span><b>{moneyFa(landRate)} ریال / مترمربع</b></div><div className="li"><span>بلوک</span><b>{row.block}</b></div>{row.source_page&&<div className="li"><span>صفحه دفترچه</span><b>{row.source_page.toLocaleString("fa-IR")}</b></div>}</div>}{(selectedDocument?.source_url||selectedLocation?.source_url)&&<><div className="legal-output">منبع دفترچه: {selectedDocument?.title||selectedLocation?.source_title}</div><a className="btn secondary" href={`${selectedDocument?.source_url||selectedLocation.source_url}${row?.source_page?`#page=${row.source_page}`:""}`} target="_blank" rel="noreferrer">{row?.source_page?`مشاهده صفحه ${row.source_page.toLocaleString("fa-IR")} در فایل رسمی`:"مشاهده فایل در منبع رسمی"}</a></>}{officialProvince&&<div className="legal-output">صفحه رسمی استان: <a href={officialProvince.source_url} target="_blank" rel="noreferrer">سازمان امور مالیاتی کشور</a></div>}</div></div>;
};

const LiveNationalRegionalPropertyView = () => {
  const cacheVersion="31.84";
  const [indexes,setIndexes]=React.useState(null),[rulesBanks,setRulesBanks]=React.useState(null),[year,setYear]=React.useState("1405"),[province,setProvince]=React.useState("تهران"),[locationId,setLocationId]=React.useState(""),[data,setData]=React.useState(null),[record,setRecord]=React.useState(""),[query,setQuery]=React.useState(""),[landUse,setLandUse]=React.useState("residential"),[landArea,setLandArea]=React.useState(""),[width,setWidth]=React.useState("12");
  const [hasBuilding,setHasBuilding]=React.useState(true),[buildingUse,setBuildingUse]=React.useState("residential_office"),[structure,setStructure]=React.useState("concrete_steel_metal"),[buildingArea,setBuildingArea]=React.useState(""),[parkingArea,setParkingArea]=React.useState(""),[storageArea,setStorageArea]=React.useState(""),[age,setAge]=React.useState("0"),[floorNo,setFloorNo]=React.useState("0"),[floorCount,setFloorCount]=React.useState("1"),[stage,setStage]=React.useState("complete"),[noGroundFloor,setNoGroundFloor]=React.useState(false),[wornFirstTransfer,setWornFirstTransfer]=React.useState(false),[governmentSupport,setGovernmentSupport]=React.useState(false),[error,setError]=React.useState("");
  const [noAccess,setNoAccess]=React.useState(false),[outside,setOutside]=React.useState(false),[plaque,setPlaque]=React.useState(""),[propertyAddress,setPropertyAddress]=React.useState(""),[notes,setNotes]=React.useState(""),[rateOption,setRateOption]=React.useState("base");
  const normalizeSearch=(value)=>latinDigits(String(value||"")).replace(/ي/g,"ی").replace(/ك/g,"ک").replace(/\s+/g," ").trim().toLocaleLowerCase("fa-IR");
  const boundaryTokens=["خیابان","بلوار","بزرگراه","رودخانه","ارتفاعات","میدان","جاده","شمال","جنوب","شرق","غرب","حدفاصل","کوه","پل","کوچه","مسیر","راه آهن"],fixOfficialFragment=(value)=>{const text=String(value||"").trim(),reversed=[...text].reverse().join(""),score=(candidate)=>boundaryTokens.reduce((sum,token)=>sum+(candidate.includes(token)?1:0),0);return score(reversed)>score(text)?reversed:text;},officialBoundary=(item)=>{if(!item)return{};const existing=item.boundary||{},parsed={};const parts=String(item.description||item.locality||"").split("|").map(fixOfficialFragment).filter(Boolean),directions={"شمال":"north","شرق":"east","جنوب":"south","غرب":"west"};parts.forEach(part=>{const match=part.match(/^(شمال|شرق|جنوب|غرب)\s*[:：]\s*(.+)$/);if(match)parsed[directions[match[1]]]=match[2].trim();});const labels=parts.map((part,index)=>directions[part.replace(/[:：]/g,"").trim()]?index:-1).filter(index=>index>=0),beforeMode=labels.length&&labels[0]>=2;labels.forEach(index=>{const direction=directions[parts[index].replace(/[:：]/g,"").trim()],candidate=beforeMode?parts[index-1]:parts[index+1];if(direction&&candidate&&!directions[candidate.replace(/[:：]/g,"").trim()])parsed[direction]=candidate;});const usable=(value)=>value&&!directions[String(value).replace(/[:：]/g,"").trim()];return {north:parsed.north||(usable(existing.north)?fixOfficialFragment(existing.north):""),east:parsed.east||(usable(existing.east)?fixOfficialFragment(existing.east):""),south:parsed.south||(usable(existing.south)?fixOfficialFragment(existing.south):""),west:parsed.west||(usable(existing.west)?fixOfficialFragment(existing.west):"")};};
  const officialLocality=(item)=>{const text=String(item?.locality||"").replace(/\s+/g," ").trim();if(!text||/^\d+(?:[-.]\d+)*$/.test(latinDigits(text))||/^(?:درادن|یتلاماعم شزرا)/.test(text)||/^ارزش (?:معاملاتی|اجاری) هر متر/.test(text)||/^(?:محدوده بلوک|شرح)$/.test(text)||/^(?:ض رع|ضرع اب)/.test(text))return "";if(/^(?:بر خیابان|معبر با عرض|کلیه معابر با عرض)/.test(text))return `مبنای نرخ: ${text}`;return fixOfficialFragment(text);};
  const officialDescription=(item)=>{const text=String(item?.description||"").replace(/\s+/g," ").trim();if(!text||/^\d+(?:[-.]\d+)*$/.test(latinDigits(text))||/^(?:درادن|یتلاماعم شزرا)/.test(text)||/^ارزش (?:معاملاتی|اجاری) هر متر/.test(text)||/^(?:ض رع|ضرع اب)/.test(text)||/^شمال:\s*\|\s*شرق:\s*\|\s*جنوب:\s*\|\s*غرب:\s*$/.test(text))return "";return fixOfficialFragment(text);};
  React.useEffect(()=>{let active=true;Promise.all(["1405","1404"].flatMap(value=>[fetch(`legal-data/regional-values/national-${value}/index.json?v=${cacheVersion}`).then(r=>{if(!r.ok)throw new Error(`index-${value}`);return r.json();}),fetch(`legal-data/regional-values/official-rules-${value}/index.json?v=${cacheVersion}`).then(r=>r.ok?r.json():null).catch(()=>null)])).then(([i1405,r1405,i1404,r1404])=>{if(!active)return;setIndexes({"1405":i1405,"1404":i1404});setRulesBanks({"1405":r1405,"1404":r1404});}).catch(()=>active&&setError("بانک رسمی ارزش معاملاتی بارگذاری نشد."));return()=>{active=false;};},[]);
  const index=indexes?.[year],provinceNames=React.useMemo(()=>{if(!indexes)return[];return [...new Set([...(indexes["1405"]?.provinces||[]).map(x=>x.name),...(indexes["1404"]?.provinces||[]).map(x=>x.name)])];},[indexes]),locations=(index?.locations||[]).filter(x=>x.province===province),location=locations.find(x=>x.id===locationId)||locations[0]||null;
  React.useEffect(()=>{setLocationId(locations[0]?.id||"");setData(null);setRecord("");setQuery("");setLandArea("");setBuildingArea("");setParkingArea("");setStorageArea("");setRateOption("base");},[year,province,indexes]);
  React.useEffect(()=>{if(!location){setData(null);return;}let active=true;setData(null);setRecord("");const documentRequest=fetch(`${location.data_url}?v=${cacheVersion}`).then(r=>{if(!r.ok)throw new Error("document");return r.json();}),boundaryRequest=location.province==="تهران"&&location.name==="تهران"?fetch(`legal-data/regional-values/tehran-boundaries.json?v=${cacheVersion}`).then(r=>r.ok?r.json():null).catch(()=>null):Promise.resolve(null);Promise.all([documentRequest,boundaryRequest]).then(([payload,boundaries])=>{if(!active)return;let mergedBlocks=payload.blocks||[];if(boundaries?.blocks){const byBlock=Object.fromEntries(boundaries.blocks.map(item=>[item.block,item]));mergedBlocks=mergedBlocks.map(item=>{const extra=byBlock[item.block];return extra?{...item,boundary:{north:extra.north,east:extra.east,south:extra.south,west:extra.west},main_streets:extra.main_streets,description:extra.boundary||item.description}:item;});}setData({...payload,blocks:mergedBlocks});setRecord(mergedBlocks[0]?.id||"");}).catch(()=>active&&setError("جدول رسمی این شهر بارگذاری نشد."));return()=>{active=false;};},[locationId,year,province,indexes]);
  const rulesRecord=location?rulesBanks?.[year]?.documents?.[location.id]:null,rulesReady=Boolean(rulesRecord?.calculator_ready),landRules=rulesReady?rulesRecord.land:null,buildingRules=rulesReady?rulesRecord.building:null,blocks=data&&location&&data.id===location.id?(data.blocks||[]):[],normalizedQuery=normalizeSearch(query),visibleBlocks=blocks.filter(x=>!normalizedQuery||normalizeSearch(`${x.block} ${x.locality||""} ${x.description||""} ${Object.values(officialBoundary(x)).join(" ")}`).includes(normalizedQuery)),row=visibleBlocks.find(x=>x.id===record)||visibleBlocks[0]||(!normalizedQuery?blocks.find(x=>x.id===record)||blocks[0]:null),rowBoundary=officialBoundary(row);
  React.useEffect(()=>setRateOption("base"),[row?.id]);
  const directLandUses=new Set(["residential","office","commercial"]),landUses=[["residential","مسکونی"],["office","اداری"],["commercial","تجاری"],["service_education_culture_health_leisure_tourism_hotel","خدماتی، آموزشی، فرهنگی، درمانی، تفریحی، گردشگری و هتل‌داری"],["industrial_workshop_transport_warehouse_parking","صنعتی، کارگاهی، حمل‌ونقل، انبار و توقفگاه"],["agriculture_irrigated_garden_livestock_aquaculture_flower","باغ، زراعت آبی، دامداری، آبزیان و گل‌وگیاه"],["agriculture_dry_farming","زراعت دیم"],["other","سایر یا فاقد کاربری"]];
  const rateOptions=Array.isArray(row?.rate_options)?row.rate_options:[],selectedRateOption=rateOptions.find(item=>item.id===rateOption)||rateOptions[0]||null,selectedRates=selectedRateOption?.rates||row||{},rowLockStatus=row?.quality?.status||"",rowLocked=Boolean(row?.quality?.locked)||["locked_source_ambiguity","selection_review_required"].includes(rowLockStatus);
  const directBase=Number(selectedRates?.[directLandUses.has(landUse)?landUse:"residential"]||0),usageFactor=directLandUses.has(landUse)?1:Number(landRules?.usage_factors?.[landUse]||0),widthRates=landRules?.width_adjustment_per_meter||{},widthRate=landUse==="commercial"?Number(widthRates.commercial||0):landUse==="office"?Number(widthRates.office??widthRates.other??0):Number(widthRates.other||0),baseWidth=Number(landRules?.base_passage_width_m||0),widthCap=landUse==="residential"?Number(landRules?.width_increase_cap_m?.residential||0):Number(landRules?.width_increase_cap_m?.other||0),actualWidth=Math.max(0,nval(width)),effectiveWidth=actualWidth>baseWidth?Math.min(actualWidth,widthCap):actualWidth,widthFactor=landRules?Math.max(0,1+(effectiveWidth-baseWidth)*widthRate):0,accessFactor=noAccess?Number(landRules?.no_independent_access_factor||1):1,outsideFactor=outside?Number(landRules?.unpriced_outside_city_factor||1):1,landRate=directBase*usageFactor*widthFactor*accessFactor*outsideFactor,landValue=landRate*nval(landArea),landReady=Boolean(rulesReady&&row&&!rowLocked&&landRate>0&&nval(landArea)>0);
  const buildingRate=Number(buildingRules?.rates_per_sqm_rial?.[buildingUse]?.[structure]||0),rawFloorNumber=Math.trunc(nval(floorNo)),floorNumber=noGroundFloor&&Math.abs(rawFloorNumber)===1?0:rawFloorNumber,floors=Math.max(1,Math.trunc(nval(floorCount))||1),residentialFloorFactor=buildingUse==="residential_office"?1+Math.max(0,floors-Number(buildingRules?.residential_office_extra_floor_starts_at||999)+1)*Number(buildingRules?.residential_office_extra_floor_factor||0):1,commercialFloorFactor=buildingUse==="commercial"?1-Math.min(Number(buildingRules?.commercial_floor_discount_cap||0),Math.abs(floorNumber)*Number(buildingRules?.commercial_floor_discount||0)):1,floorFactor=buildingUse==="commercial"?commercialFloorFactor:residentialFloorFactor,ageFactor=1-Math.min(Number(buildingRules?.age_discount_cap||0),Math.max(0,Math.trunc(nval(age)))*Number(buildingRules?.age_discount_per_year||0)),stageFactor=Number(buildingRules?.unfinished_stage_factors?.[stage]||1),specialFactor=(wornFirstTransfer?Number(buildingRules?.worn_fabric_new_first_transfer_factor||1):1)*(governmentSupport?Number(buildingRules?.state_support_first_transfer_factor||1):1),mainBuildingValue=buildingRate*nval(buildingArea)*floorFactor,annexArea=nval(parkingArea)+nval(storageArea),annexValue=buildingRules?.exclude_residential_parking_storage&&buildingUse==="residential_office"?0:buildingRate*annexArea*Number(buildingRules?.parking_storage_factor||0)*floorFactor,buildingValue=hasBuilding&&rulesReady?(mainBuildingValue+annexValue)*ageFactor*stageFactor*specialFactor:0,buildingReady=!hasBuilding||Boolean(rulesReady&&buildingRate>0&&nval(buildingArea)>0),total=landValue+buildingValue,ready=landReady&&buildingReady,landUseLabel=landUses.find(x=>x[0]===landUse)?.[1]||"",buildingUseLabel={commercial:"تجاری",residential_office:"مسکونی و اداری",service_industrial:"خدماتی، صنعتی و عمومی",agriculture:"کشاورزی و دامداری"}[buildingUse]||"";
  const duplicateNames=new Set(locations.filter((x,i,list)=>list.findIndex(y=>y.name===x.name)!==i).map(x=>x.name)),locationLabel=(item)=>{const name=item.name.replace(/سال$/," ").trim(),same=locations.filter(x=>x.name===item.name),ordinal=same.findIndex(x=>x.id===item.id)+1;return `${name}${duplicateNames.has(item.name)?` — محدوده ${ordinal.toLocaleString("fa-IR")}`:""}`;},blockLabel=(item)=>{const boundary=officialBoundary(item),place=Object.values(boundary).filter(Boolean).join("، ")||officialDescription(item)||"شرح محدوده در سند قابل استخراج نیست",cleanLocality=officialLocality(item),locality=cleanLocality?`${cleanLocality} — `:"",locked=Boolean(item?.quality?.locked)||["locked_source_ambiguity","selection_review_required"].includes(item?.quality?.status);return `بلوک ${item.block} — ${locality}${place.length>105?`${place.slice(0,105)}…`:place}${locked?" — نیازمند تطبیق با سند رسمی":""}`;},updateLabel=index?.source_page_updated?`${index.source_page_updated} ـ سال اجرای ${Number(year).toLocaleString("fa-IR")}`:`سال اجرای ${Number(year).toLocaleString("fa-IR")}`;
  if(!indexes&&!error)return <div className="calc-empty">در حال بارگذاری بانک رسمی ارزش معاملاتی املاک…</div>;
  if(error&&!indexes)return <div className="calc-empty">{error}</div>;
  return <div className="calc-workspace regional-property"><div className="calc-form"><div className="calc-section-title">محاسبه ارزش معاملاتی عرصه و اعیان ـ کل کشور</div>
    <div className="calc-fields two"><div className="field"><label>سال اجرا</label><select value={year} onChange={e=>setYear(e.target.value)}><option value="1405">۱۴۰۵</option><option value="1404">۱۴۰۴</option></select></div><div className="field"><label>استان</label><select value={province} onChange={e=>setProvince(e.target.value)}>{provinceNames.map(name=><option value={name} key={name}>{name}</option>)}</select></div></div><div className="field"><label>شهرستان / شهر</label><select value={location?.id||""} onChange={e=>setLocationId(e.target.value)} disabled={!locations.length}>{locations.length?locations.map(item=><option value={item.id} key={item.id}>{locationLabel(item)}</option>):<option value="">برای این استان در سال انتخابی جدول رسمی منتشر نشده است</option>}</select></div>
    <div className="field"><label>آخرین به‌روزرسانی</label><div className="calc-readonly-value">{updateLabel}</div></div>
    {!locations.length&&<div className="calc-hint">{year==="1405"?"در دفترچه‌های رسمی ۱۴۰۵ برای این استان داده قابل محاسبه‌ای ثبت نشده؛ سال ۱۴۰۴ را هم بررسی کنید.":"در دفترچه‌های رسمی ۱۴۰۴ برای این استان داده قابل محاسبه‌ای ثبت نشده است."}</div>}
    {blocks.length>0&&<><div className="field"><label>جست‌وجوی بلوک، خیابان یا حد محدوده</label><input value={query} onChange={e=>{setQuery(e.target.value);setRecord("");}} placeholder="مثلاً ۲۳، آزادی یا نام محله"/></div><div className="field"><label>بلوک و نشانی رسمی</label><select value={row?.id||""} onChange={e=>setRecord(e.target.value)} disabled={!visibleBlocks.length}>{visibleBlocks.length?visibleBlocks.map(x=><option value={x.id} key={x.id}>{blockLabel(x)}</option>):<option value="">نتیجه‌ای پیدا نشد</option>}</select>{!visibleBlocks.length&&<div className="calc-hint">هیچ بلوکی با عبارت جست‌وجوشده تطبیق ندارد.</div>}</div></>}
    {row&&<div className="block-boundary-card"><b>بلوک {row.block} — {officialLocality(row)||`محدوده رسمی ${location.name.replace(/سال$/," ").trim()}`}</b>{Object.values(rowBoundary).some(Boolean)?<div><span><strong>شمال:</strong> {rowBoundary.north||"در دفترچه درج نشده"}</span><span><strong>شرق:</strong> {rowBoundary.east||"در دفترچه درج نشده"}</span><span><strong>جنوب:</strong> {rowBoundary.south||"در دفترچه درج نشده"}</span><span><strong>غرب:</strong> {rowBoundary.west||"در دفترچه درج نشده"}</span></div>:officialDescription(row)?<p className="regional-boundary-description">{officialDescription(row)}</p>:<p>شرح چهارحد این ردیف از سند رسمی قابل استخراج مطمئن نیست.</p>}{row.main_streets&&<p><strong>خیابان‌های اصلی:</strong> {fixOfficialFragment(row.main_streets)}</p>}</div>}
    {rowLocked&&<div className="calc-hint danger">{rowLockStatus==="locked_source_ambiguity"?"نرخ این بلوک به‌علت هم‌پوشانی دو رقم در صفحه رسمی مبهم است.":"نشانی مرزی یا هویت این ردیف در استخراج رسمی برای انتخاب مطمئن ملک کافی نیست."} محاسبه این ردیف تا تطبیق انسانی قفل شده و هیچ عدد حدسی نمایش داده نمی‌شود.</div>}
    {rateOptions.length>0&&<div className="field"><label>مبنای نرخ رسمی عرصه</label><select value={selectedRateOption?.id||""} onChange={e=>setRateOption(e.target.value)}>{rateOptions.map(item=><option value={item.id} key={item.id}>{item.label}</option>)}</select><small>گزینه را مطابق موقعیت دقیق ملک در همان بلوک انتخاب کنید.</small></div>}
    {row&&<><div className="calc-section-sub">مشخصات ملک</div><div className="calc-fields two"><div className="field"><label>پلاک ثبتی (اختیاری)</label><input value={plaque} onChange={e=>setPlaque(e.target.value)} placeholder="برای درج در نسخه چاپی"/></div><div className="field"><label>نشانی ملک (اختیاری)</label><input value={propertyAddress} onChange={e=>setPropertyAddress(e.target.value)} placeholder="نشانی دقیق ملک"/></div></div><div className="field"><label>توضیحات (اختیاری)</label><input value={notes} onChange={e=>setNotes(e.target.value)} placeholder="توضیحات قابل درج در نسخه چاپی"/></div><div className="calc-section-sub">مشخصات عرصه</div><div className="field"><label>نوع کاربری عرصه</label><select value={landUse} onChange={e=>setLandUse(e.target.value)}>{landUses.map(([value,label])=><option value={value} key={value} disabled={!rulesReady||rowLocked}>{label}</option>)}</select></div><div className="calc-fields two"><div className="field"><label>مساحت عرصه (مترمربع)</label><NumericInput value={landArea} onValue={setLandArea} decimal placeholder="مثلاً ۲۵۰"/><small>حیاط و فضای باز ملک جزو عرصه است و جداگانه وارد نمی‌شود.</small></div><div className="field"><label>عرض معبر دسترسی (متر)</label><NumericInput value={width} onValue={setWidth} decimal placeholder={`مبنای دفترچه ${baseWidth||"—"} متر`}/></div></div>{landRules?.no_independent_access_factor&&<label className="calc-check"><input type="checkbox" checked={noAccess} onChange={e=>setNoAccess(e.target.checked)}/> ملک راه عبور مستقل ندارد و از ملک مجاور حق عبور دارد ـ ضریب {Number(landRules.no_independent_access_factor*100).toLocaleString("fa-IR")}٪</label>}{landRules?.unpriced_outside_city_factor&&<label className="calc-check"><input type="checkbox" checked={outside} onChange={e=>setOutside(e.target.checked)}/> ملک در محدوده‌ای است که ارزش معاملاتی تعیین نشده ـ ضریب نزدیک‌ترین محل مشابه {Number(landRules.unpriced_outside_city_factor*100).toLocaleString("fa-IR")}٪</label>}
    <div className="calc-section-sub">مشخصات اعیان</div><label className="calc-check"><input type="checkbox" checked={hasBuilding} onChange={e=>setHasBuilding(e.target.checked)}/> ملک دارای بنا است</label>{hasBuilding&&<><div className="calc-fields two"><div className="field"><label>کاربری اعیان</label><select value={buildingUse} onChange={e=>setBuildingUse(e.target.value)} disabled={!rulesReady}><option value="commercial">تجاری</option><option value="residential_office">مسکونی و اداری</option><option value="service_industrial">صنعتی، کارگاهی، خدماتی، آموزشی، درمانی، گردشگری، انبار و پارکینگ عمومی</option><option value="agriculture">کشاورزی، دامداری، طیور، آبزیان و گل‌وگیاه</option></select></div><div className="field"><label>نوع سازه</label><select value={structure} onChange={e=>setStructure(e.target.value)} disabled={!rulesReady}><option value="concrete_steel_metal">تمام‌بتن، اسکلت بتنی یا فلزی، سوله</option><option value="other">سایر؛ از جمله بنایی، آجری یا سیمانی فاقد اسکلت</option></select></div></div><div className="calc-fields two"><div className="field"><label>زیربنای اعیان (مترمربع)</label><NumericInput value={buildingArea} onValue={setBuildingArea} decimal placeholder="مثلاً ۱۲۰"/></div><div className="field"><label>قدمت بنا (سال)</label><NumericInput value={age} onValue={setAge} placeholder="مثلاً ۸"/></div></div><div className="calc-fields two"><div className="field"><label>مساحت پارکینگ (مترمربع)</label><NumericInput value={parkingArea} onValue={setParkingArea} decimal placeholder="مثلاً ۱۲"/></div><div className="field"><label>مساحت انباری (مترمربع)</label><NumericInput value={storageArea} onValue={setStorageArea} decimal placeholder="مثلاً ۶"/></div></div>{buildingRules?.exclude_residential_parking_storage&&buildingUse==="residential_office"&&<div className="calc-hint">طبق همین دفترچه، پارکینگ و انباریِ واحد مسکونی در ارزش اعیان منظور نمی‌شود.</div>}<div className="calc-fields two"><div className="field"><label>شماره طبقه اعیان</label><NumericInput value={floorNo} onValue={setFloorNo} placeholder="زیرزمین ۱-، همکف ۰، طبقه اول ۱"/></div><div className="field"><label>تعداد طبقات بدون زیرزمین و پیلوت</label><NumericInput value={floorCount} onValue={setFloorCount} placeholder="مثلاً ۵"/></div></div><div className="field"><label>مرحله ساخت</label><select value={stage} onChange={e=>setStage(e.target.value)} disabled={!rulesReady}><option value="complete">اتمام ـ ۱۰۰٪</option><option value="finishing">نازک‌کاری ـ ۸۰٪</option><option value="rough_construction">سفت‌کاری ـ ۵۰٪</option><option value="skeleton">اسکلت ـ ۳۰٪</option><option value="foundation">فونداسیون ـ ۱۰٪</option></select></div>{buildingUse==="commercial"&&<label className="calc-check"><input type="checkbox" checked={noGroundFloor} onChange={e=>setNoGroundFloor(e.target.checked)}/> ساختمان همکف ندارد؛ اولین طبقه بالا یا پایین همکف محسوب شود</label>}{buildingRules?.worn_fabric_new_first_transfer_factor&&<label className="calc-check"><input type="checkbox" checked={wornFirstTransfer} onChange={e=>setWornFirstTransfer(e.target.checked)}/> بنای نوساز در بافت فرسوده و اولین انتقال قطعی</label>}{buildingRules?.state_support_first_transfer_factor&&<label className="calc-check"><input type="checkbox" checked={governmentSupport} onChange={e=>setGovernmentSupport(e.target.checked)}/> طرح حمایتی مشمول دفترچه و اولین انتقال قطعی</label>}{!rulesReady&&<div className="calc-hint">ضوابط کامل عرصه و اعیان این فایل هنوز با اطمینان استخراج نشده است؛ برای جلوگیری از عدد اشتباه، نتیجه محاسبه نمایش داده نمی‌شود.</div>}</>}
    </>}
  </div><div className="calc-result legal-result"><div className="l">ارزش معاملاتی قابل محاسبه</div><div className="n">{ready?moneyFa(total):"—"} <small>{ready?"ریال":""}</small></div>{landReady&&<div className="breakdown"><div className="li"><span>سال / استان / شهر</span><b>{Number(year).toLocaleString("fa-IR")} / {province} / {location.name}</b></div>{officialLocality(row)&&<div className="li"><span>بخش / شهر جدول رسمی</span><b>{officialLocality(row)}</b></div>}<div className="li"><span>بلوک</span><b>{row.block}</b></div>{plaque&&<div className="li"><span>پلاک ثبتی</span><b>{plaque}</b></div>}{propertyAddress&&<div className="li"><span>نشانی</span><b>{propertyAddress}</b></div>}<div className="li"><span>کاربری عرصه</span><b>{landUseLabel}</b></div>{noAccess&&<div className="li"><span>ضریب فقدان راه مستقل</span><b>{Number(accessFactor*100).toLocaleString("fa-IR")}٪</b></div>}{outside&&<div className="li"><span>ضریب محدوده فاقد ارزش</span><b>{Number(outsideFactor*100).toLocaleString("fa-IR")}٪</b></div>}<div className="li"><span>ارزش عرصه</span><b>{moneyFa(landValue)} ریال</b></div>{hasBuilding&&buildingReady&&<><div className="li"><span>کاربری اعیان</span><b>{buildingUseLabel}</b></div><div className="li"><span>ارزش اعیان</span><b>{moneyFa(buildingValue)} ریال</b></div></>}{notes&&<div className="li"><span>توضیحات</span><b>{notes}</b></div>}</div>}{ready&&<button className="btn secondary" onClick={()=>window.print()}>چاپ یا ذخیره PDF</button>}</div></div>;
};

const VerifiedOfficialLiveRegionalPropertyView = () => {
  const cacheVersion="31.84";
  const [index,setIndex]=React.useState(null),[provinceId,setProvinceId]=React.useState(""),[provinceData,setProvinceData]=React.useState(null),[cityId,setCityId]=React.useState(""),[record,setRecord]=React.useState(""),[query,setQuery]=React.useState(""),[landUse,setLandUse]=React.useState("residential"),[landArea,setLandArea]=React.useState(""),[error,setError]=React.useState("");
  React.useEffect(()=>{let active=true;fetch(`legal-data/regional-values/live-national/index.json?v=${cacheVersion}`).then(r=>{if(!r.ok)throw new Error("live-index");return r.json();}).then(payload=>{if(!active)return;setIndex(payload);setProvinceId(payload.provinces.find(item=>item.name==="تهران")?.id||payload.provinces[0]?.id||"");}).catch(()=>active&&setError("بانک مستقیم سامانه رسمی بارگذاری نشد."));return()=>{active=false;};},[]);
  const provinceMeta=index?.provinces?.find(item=>item.id===provinceId)||null;
  React.useEffect(()=>{if(!provinceMeta){setProvinceData(null);return;}let active=true;setProvinceData(null);setCityId("");setRecord("");setQuery("");fetch(`${provinceMeta.data_url}?v=${cacheVersion}`).then(r=>{if(!r.ok)throw new Error("live-province");return r.json();}).then(payload=>{if(!active)return;setProvinceData(payload);const first=provinceMeta.id==="9303"?payload.cities.find(item=>item.id==="9304"):payload.cities.find(item=>item.status==="available"&&item.blocks?.length);setCityId(first?.id||payload.cities[0]?.id||"");}).catch(()=>active&&setError("داده رسمی این استان بارگذاری نشد."));return()=>{active=false;};},[provinceId]);
  const cities=provinceData?.cities||[],city=cities.find(item=>item.id===cityId)||cities[0]||null,blocks=city?.blocks||[],normalize=(value)=>latinDigits(String(value||"")).replace(/ي/g,"ی").replace(/ك/g,"ک").replace(/\s+/g," ").trim().toLocaleLowerCase("fa-IR"),needle=normalize(query),visibleBlocks=blocks.filter(item=>!needle||normalize(`${item.block} ${item.description||""} ${item.main_streets||""} ${Object.values(item.boundary||{}).join(" ")}`).includes(needle)),row=visibleBlocks.find(item=>item.id===record)||visibleBlocks[0]||(!needle?blocks.find(item=>item.id===record)||blocks[0]:null);
  React.useEffect(()=>{setRecord(blocks[0]?.id||"");setQuery("");setLandArea("");},[cityId,provinceData]);
  const duplicateCityNames=new Set(cities.filter((item,index,list)=>list.findIndex(other=>other.name===item.name)!==index).map(item=>item.name)),tehranHint=item=>item.id==="9304"?" · یافت‌آباد/سعیدی ۱۸-۰۴":item.id==="11744"?" · شهید سعیدی ۱۸-۰۸":"",cityLabel=(item)=>`${item.name}${duplicateCityNames.has(item.name)?` — شناسه رسمی ${Number(item.id).toLocaleString("fa-IR")} · ${item.block_count.toLocaleString("fa-IR")} بلوک${tehranHint(item)}`:""}${item.status!=="available"?" — داده‌ای در پاسخ رسمی نبود":""}`;
  const uses=[["residential","مسکونی"],["office","اداری"],["commercial","تجاری"]],rate=Number(row?.rates?.[landUse]||0),boundary=row?.boundary||{},boundaryStatus=row?.boundary_status||(row&&["north","east","south","west"].every(key=>String(boundary[key]||"").trim())?"complete":"incomplete"),boundaryReady=boundaryStatus==="complete",rowUsable=Boolean(row&&row.rate_status==="available"&&rate>0&&boundaryReady),value=rate*nval(landArea),ready=rowUsable&&nval(landArea)>0,capturedAt=index?.source?.captured_at?new Date(index.source.captured_at).toLocaleDateString("fa-IR"):"ثبت نشده",blockLabel=(item)=>`بلوک ${item.block}${item.main_streets?` — ${item.main_streets}`:item.description?` — ${String(item.description).replace(/\s+/g," ").slice(0,110)}${item.description.length>110?"…":""}`:""}${item.boundary_status!=="complete"?" — چهارحد ناقص؛ محاسبه قفل":""}`;
  if(!index&&!error)return <div className="calc-empty">در حال بارگذاری استخراج مستقیم سامانه رسمی…</div>;
  if(error&&!index)return <div className="calc-empty">{error}</div>;
  return <div className="calc-workspace regional-property"><div className="calc-form"><div className="calc-section-title">آخرین داده مستقیم سامانه ارزش منطقه‌ای املاک</div>
    <div className="calc-fields two"><div className="field"><label>استان</label><select value={provinceId} onChange={e=>setProvinceId(e.target.value)}>{index.provinces.map(item=><option value={item.id} key={item.id}>{item.name} — {item.city_count.toLocaleString("fa-IR")} شهر/ورودی</option>)}</select></div><div className="field"><label>شهر / حوزه رسمی</label><select value={city?.id||""} onChange={e=>setCityId(e.target.value)}>{cities.map(item=><option value={item.id} key={item.id}>{cityLabel(item)}</option>)}</select></div></div>
    <div className="field"><label>آخرین برداشت کنترل‌شده</label><div className="calc-readonly-value">{capturedAt} — سال اجرا در خود سامانه مرجع اعلام نشده است</div></div>
    {city?.status!=="available"&&<div className="calc-hint danger">برای این ورودی، سامانه رسمی در زمان برداشت هیچ جدول بلوکی برنگردانده است؛ محاسبه غیرفعال است.</div>}
    {blocks.length>0&&<><div className="field"><label>جست‌وجوی بلوک، خیابان یا حد محدوده</label><input value={query} onChange={e=>{setQuery(e.target.value);setRecord("");}} placeholder="مثلاً سعیدی، آزادی یا شماره بلوک"/></div><div className="field"><label>بلوک و نشانی رسمی</label><select value={row?.id||""} onChange={e=>setRecord(e.target.value)}>{visibleBlocks.length?visibleBlocks.map(item=><option value={item.id} key={item.id}>{blockLabel(item)}</option>):<option value="">نتیجه‌ای پیدا نشد</option>}</select></div></>}
    {row&&<div className="block-boundary-card"><b>بلوک {row.block}{row.main_streets?` — ${row.main_streets}`:""}</b><div><span><strong>شمال:</strong> {boundary.north||"در پاسخ رسمی درج نشده"}</span><span><strong>شرق:</strong> {boundary.east||"در پاسخ رسمی درج نشده"}</span><span><strong>جنوب:</strong> {boundary.south||"در پاسخ رسمی درج نشده"}</span><span><strong>غرب:</strong> {boundary.west||"در پاسخ رسمی درج نشده"}</span></div>{row.boundary_status!=="complete"&&<p>مرزهای همین ردیف در منبع رسمی ناقص بوده‌اند؛ مقدار جاافتاده حدس زده نشده است.</p>}</div>}
    {row&&<><div className="calc-section-sub">محاسبه مستقیم عرصه</div><div className="field"><label>نوع کاربری عرصه</label><select value={landUse} onChange={e=>setLandUse(e.target.value)}>{uses.map(([id,label])=><option value={id} key={id}>{label}</option>)}</select></div><div className="field"><label>مساحت عرصه (مترمربع)</label><NumericInput value={landArea} onValue={setLandArea} decimal placeholder="مثلاً ۲۵۰"/></div>{!boundaryReady&&<div className="calc-hint danger">چهارحد این ردیف در خروجی رسمی کامل نیست؛ برای جلوگیری از انتخاب اشتباه بلوک، محاسبه تا تطبیق با منبع رسمی قفل است.</div>}{boundaryReady&&rate<=0&&<div className="calc-hint danger">نرخ این کاربری در پاسخ رسمی موجود نیست؛ نتیجه عددی نمایش داده نمی‌شود.</div>}<div className="calc-hint">این حالت، نرخ و چهارجهت را عیناً از خروجی سامانه مرجع استفاده می‌کند. برای ضرایب اعیان، نوع سازه، طبقات، پارکینگ و انباری از حالت «دفترچه سالانه» استفاده کنید؛ داده دو منبع با هم مخلوط نمی‌شود.</div></>}
  </div><div className="calc-result legal-result"><div className="l">ارزش معاملاتی مستقیم عرصه</div><div className="n">{ready?moneyFa(value):"—"} <small>{ready?"ریال":""}</small></div>{ready&&<div className="breakdown"><div className="li"><span>استان / شهر</span><b>{provinceData.province?.name||provinceMeta?.name} / {city.name}</b></div><div className="li"><span>بلوک</span><b>{row.block}</b></div><div className="li"><span>نرخ رسمی هر مترمربع</span><b>{moneyFa(rate)} ریال</b></div><div className="li"><span>مساحت عرصه</span><b>{nval(landArea).toLocaleString("fa-IR")} مترمربع</b></div></div>}<div className="legal-output">منبع: سامانه محاسبه ارزش منطقه‌ای املاک — استخراج مستقیم و کنترل تمامیت محلی</div><a className="btn secondary" href={index.source.url} target="_blank" rel="noreferrer">مشاهده سامانه رسمی</a></div></div>;
};

const NationalRegionalPropertyView = () => {
  const [datasetMode,setDatasetMode]=React.useState("latest");
  return <div className="regional-property-shell"><div className="field"><label>بانک اطلاعاتی محاسبه</label><select value={datasetMode} onChange={e=>setDatasetMode(e.target.value)}><option value="latest">آخرین داده مستقیم سامانه مرجع — پوشش سراسری</option><option value="annual">دفترچه‌های رسمی سالانه ۱۴۰۵ و ۱۴۰۴ — محاسبه عرصه و اعیان</option></select></div>{datasetMode==="latest"?<VerifiedOfficialLiveRegionalPropertyView/>:<LiveNationalRegionalPropertyView/>}</div>;
};
const RegionalPropertyModule = () => <NationalRegionalPropertyView/>;

const CompleteDelayView = () => {
  const [table,setTable]=React.useState(null);
  const [amount,setAmount]=React.useState("");
  const [dueYear,setDueYear]=React.useState("1400"),[dueMonth,setDueMonth]=React.useState("1");
  const [payYear,setPayYear]=React.useState("1403"),[payMonth,setPayMonth]=React.useState("1");
  React.useEffect(()=>{fetch("legal-data/delay-indices.json?v=31.18").then(r=>r.json()).then(setTable);},[]);
  if(!table)return <div className="calc-empty">در حال بارگذاری جدول شاخص‌های ماهانه…</div>;
  const monthKeys=["farvardin","ordibehesht","khordad","tir","mordad","shahrivar","mehr","aban","azar","dey","bahman","esfand"];
  const monthNames=["فروردین","اردیبهشت","خرداد","تیر","مرداد","شهریور","مهر","آبان","آذر","دی","بهمن","اسفند"];
  const years=Object.keys(table.months||{}).sort((a,b)=>Number(a)-Number(b));
  const availableMonths=(year)=>monthKeys.map((key,i)=>table.months?.[year]?.[key]!=null?String(i+1):null).filter(Boolean);
  const dueMonths=availableMonths(dueYear),payMonths=availableMonths(payYear);
  const changeYear=(year,setYear,setMonth,currentMonth)=>{setYear(year);const available=availableMonths(year);if(!available.includes(String(currentMonth)))setMonth(available.at(-1)||"1");};
  const dueIndex=table.months?.[dueYear]?.[monthKeys[Number(dueMonth)-1]];
  const payIndex=table.months?.[payYear]?.[monthKeys[Number(payMonth)-1]];
  const dueOrder=Number(dueYear)*12+Number(dueMonth),payOrder=Number(payYear)*12+Number(payMonth);
  const invalidOrder=payOrder<dueOrder, principal=nval(amount),ready=principal>0&&!invalidOrder&&Boolean(dueIndex)&&Boolean(payIndex);
  const total=!invalidOrder&&dueIndex&&payIndex?principal*payIndex/dueIndex:0;
  const damage=Math.max(0,total-principal),ratio=!invalidOrder&&dueIndex&&payIndex?payIndex/dueIndex:0;
  return <div className="calc-workspace"><div className="calc-form">
    <div className="calc-section-title">محاسبه ماهانه خسارت تأخیر تأدیه</div>
    <div className="field"><label>مبلغ اصل دین (ریال)</label><NumericInput value={amount} onValue={setAmount}/></div>
    <div className="calc-fields two"><div className="field"><label>سال سررسید</label><select value={dueYear} onChange={e=>changeYear(e.target.value,setDueYear,setDueMonth,dueMonth)}>{years.map(y=><option key={y}>{y}</option>)}</select></div><div className="field"><label>ماه سررسید</label><select value={dueMonth} onChange={e=>setDueMonth(e.target.value)}>{dueMonths.map(v=><option value={v} key={v}>{v} - {monthNames[Number(v)-1]}</option>)}</select></div></div>
    <div className="calc-fields two"><div className="field"><label>سال پرداخت</label><select value={payYear} onChange={e=>changeYear(e.target.value,setPayYear,setPayMonth,payMonth)}>{years.map(y=><option key={y}>{y}</option>)}</select></div><div className="field"><label>ماه پرداخت</label><select value={payMonth} onChange={e=>setPayMonth(e.target.value)}>{payMonths.map(v=><option value={v} key={v}>{v} - {monthNames[Number(v)-1]}</option>)}</select></div></div>
    {invalidOrder?<div className="legal-output">تاریخ پرداخت نمی‌تواند زودتر از تاریخ سررسید باشد.</div>:<div className="calc-hint">شاخص‌ها خودکار انتخاب می‌شوند. پوشش معتبر فعلی: فروردین ۱۳۶۹ تا خرداد ۱۴۰۵. سال‌های پیش از ۱۳۶۹ و ماه‌های پس از خرداد ۱۴۰۵ به‌جای محاسبه ساختگی نمایش داده نمی‌شوند.</div>}
  </div><div className="calc-result legal-result"><div className="l">جمع اصل دین و خسارت</div><div className="n fa-num">{ready?moneyFa(total):"—"} <small>{ready?"ریال":""}</small></div>{ready&&<><div className="breakdown"><div className="li"><span>اصل دین</span><b>{moneyFa(principal)} ریال</b></div><div className="li"><span>خسارت تأخیر</span><b>{moneyFa(damage)} ریال</b></div><div className="li"><span>نسبت شاخص پرداخت به سررسید</span><b>{ratio.toLocaleString("fa-IR",{maximumFractionDigits:6})}</b></div><div className="li"><span>دوره</span><b>{monthNames[Number(dueMonth)-1]} {dueYear} تا {monthNames[Number(payMonth)-1]} {payYear}</b></div></div><div className="legal-output">فرمول: اصل دین × شاخص ماه پرداخت ÷ شاخص ماه سررسید. مستند: ماده ۵۲۲ قانون آیین دادرسی مدنی و رأی وحدت رویه شماره ۸۵۰ مورخ ۱۴۰۳/۰۵/۱۶.</div></>}</div></div>;
};

const CalcView = ({ lang }) => {
  const fa = lang === "fa";
  const [tool, setTool] = React.useState("delay");

  return <div className="legal-calculator" dir={fa?"rtl":"ltr"}>
    <div className="calc-intro"><div><b>{fa?"میز محاسبات حقوقی شهداد":"Shahdad legal calculation desk"}</b><span>{fa?"ابزار موردنظر را انتخاب کنید؛ نتیجه همراه با فرمول و جزئیات نمایش داده می‌شود.":"Choose a tool to see its formula and breakdown."}</span></div><span className="calc-source-badge">{fa?"مبنای قانونی مستند":"Documented legal basis"}</span></div>
    <div className="calc-tool-grid">{CALC_TOOLS.map(t=><button key={t.id} className={"calc-tool "+(tool===t.id?"on":"")} onClick={()=>setTool(t.id)}><Ic.calc size={18}/><span>{fa?t.fa:t.en}</span></button>)}</div>

    {tool==="delay"&&<CompleteDelayView/>}

    {tool==="mahr"&&<CompleteMahrView/>}
    {tool==="execution"&&<ExtractedReferenceView panel="execution"/>}
    {tool==="court"&&<ExtractedReferenceView panel="court"/>}
    {tool==="arbitration"&&<ExtractedReferenceView panel="arbitration"/>}
    {tool==="inheritance"&&<CompleteInheritanceView/>}
    {tool==="diye"&&<CompleteDiyaView/>}
    {tool==="expert"&&<ExtractedReferenceView panel="expert"/>}
    {tool==="landExpert"&&<ExtractedReferenceView panel="propertyExpert"/>}
    {tool==="regionalProperty"&&<RegionalPropertyModule/>}
    {tool==="office"&&<ExtractedReferenceView panel="office"/>}
    {tool==="attorney"&&<CompleteAttorneyView/>}
    <div className="calc-legal-note"><b>توجه حقوقی</b><span>نتایج این صفحه ابزار برآورد است و جایگزین محاسبه اجرای احکام، نظریه کارشناس یا مشاوره وکیل نیست. شاخص‌ها و تعرفه‌های متغیر باید از منبع رسمی روز کنترل شوند.</span></div>
  </div>;
};

const AIChatView = ({ lang }) => {
  const [msgs, setMsgs] = React.useState([
    { who: "ai", text: lang==="fa"
      ? "سلام جناب اروجی. من دستیار هوشمند شهداد هستم. در چه زمینه‌ای می‌توانم کمک کنم؟ می‌توانم در تحلیل قراردادها، استعلام پرونده، محاسبه ارث/مهریه، و راهنمایی حقوقی به شما کمک کنم."
      : "Hi Mr. Oroji. I'm SHAHDAD's AI assistant. How can I help today? I can analyze contracts, look up cases, compute inheritance/mahrieh, and offer legal guidance." },
    { who: "user", text: lang==="fa" ? "ریسک‌های قرارداد بیع ملک چیست؟" : "What are the risks of a property sale contract?" },
    { who: "ai", text: lang==="fa"
      ? "ریسک‌های اصلی قرارداد بیع ملک شامل ۴ مورد است: (۱) عدم احراز مالکیت [مادهٔ ۳۶۲ ق.م.]، (۲) رهن یا توقیف ملک، (۳) ابهام در حدود و مساحت، (۴) تأخیر در تسلیم. توصیه می‌شود استعلام رسمی ثبت + بیمه عنوان انجام شود."
      : "Top risks in property sale contracts: (1) title verification gaps [Civil Code §362], (2) liens or seizures, (3) ambiguity in boundaries/area, (4) delivery delays. I recommend an official registry check + title insurance." },
  ]);
  const [input, setInput] = React.useState(() => {
    const p = (typeof window !== "undefined" && window.__pendingAsk) || "";
    if (p) window.__pendingAsk = "";
    return p;
  });
  const [thinking, setThinking] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs, thinking]);

  const send = async () => {
    if (!input.trim()) return;
    const userMsg = input;
    setMsgs((m) => [...m, { who: "user", text: userMsg }]);
    setInput("");
    setThinking(true);
    AudioCtl.startAiPulse();
    try {
      const reply = await window.claude.complete(
        `You are SHAHDAD AI, a polished legal assistant for Iranian law. Reply in ${lang==="fa"?"Persian":"English"}, 2-3 short sentences, cite article numbers (in brackets) when relevant. User: ${userMsg}`
      );
      setMsgs((m) => [...m, { who: "ai", text: reply || (lang==="fa"?"در حال حاضر اتصال محدود است.":"Connection limited.") }]);
      AudioCtl.chime();
    } catch (e) {
      setMsgs((m) => [...m, { who: "ai", text: lang==="fa"?"خطا در دریافت پاسخ. لطفاً دوباره تلاش کنید.":"Couldn't fetch a response. Please retry." }]);
    }
    AudioCtl.stopAiPulse();
    setThinking(false);
  };

  return (
    <div className="chat-window">
      <div className="chat-msgs" ref={scrollRef}>
        {msgs.map((m, i) => (
          <div key={i} className={"msg " + m.who}>{m.text}</div>
        ))}
        {thinking && <div className="msg ai"><div className="typing"><i/><i/><i/></div></div>}
      </div>
      <div className="chat-input">
        <button className="small" title="Voice"><Ic.micSmall size={16}/></button>
        <button className="small" title="Attach"><Ic.paperclip size={16}/></button>
        <input placeholder={lang==="fa"?"سوال حقوقی خود را بپرسید...":"Ask a legal question..."}
          value={input} onChange={e=>setInput(e.target.value)}
          onKeyDown={e=>{if(e.key==="Enter")send();}}/>
        <button onClick={send}><Ic.send size={16}/></button>
      </div>
    </div>
  );
};

const SmartAIChatView = ({ lang }) => {
  const thinkingSteps = [
    "در حال تشخیص نوع مسئله حقوقی...",
    "در حال بررسی ریسک‌ها و مدارک لازم...",
    "در حال آماده‌سازی پاسخ قابل اقدام...",
    "در حال مرتب‌سازی نتیجه برای شما..."
  ];
  const quickPrompts = ["این قرارداد را بررسی کن", "ریسک‌های این متن را بگو", "برایم لایحه بنویس", "ساده توضیح بده", "به وکیل وصل کن"];
  const fileTypes = ["PDF", "Word", "تصویر", "صوت", "قرارداد", "دادخواست"];
  const [msgs, setMsgs] = React.useState([
    { who: "ai", text: "سلام، من دستیار حقوقی شهداد هستم. سوال، سند، قرارداد یا موضوع پرونده را بفرستید تا آن را به پاسخ قابل اقدام تبدیل کنم." }
  ]);
  const [input, setInput] = React.useState(() => {
    const p = (typeof window !== "undefined" && window.__pendingAsk) || "";
    if (p) window.__pendingAsk = "";
    return p;
  });
  const [thinking, setThinking] = React.useState(false);
  const [mode, setMode] = React.useState("deep");
  const [tone, setTone] = React.useState("simple");
  const [files, setFiles] = React.useState([]);
  const [stepIndex, setStepIndex] = React.useState(0);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs, files, thinking]);

  React.useEffect(() => {
    if (!thinking) return;
    setStepIndex(0);
    const id = setInterval(() => setStepIndex((x) => (x + 1) % thinkingSteps.length), 1150);
    return () => clearInterval(id);
  }, [thinking]);

  const addFile = (type) => {
    AudioCtl.click();
    setFiles((x) => [...x, { type, name: type === "قرارداد" ? "قرارداد آماده تحلیل" : `${type} پیوست`, status: "آماده تحلیل" }]);
  };

  const send = async () => {
    if (!input.trim()) return;
    const userMsg = input.trim();
    setMsgs((m) => [...m, { who: "user", text: userMsg }]);
    setInput("");
    setThinking(true);
    AudioCtl.startAiPulse();
    try {
      const reply = await window.claude.complete(
        `You are SHAHDAD AI, a polished Iranian legal assistant. Mode=${mode}; Tone=${tone}. Reply in Persian with concise sections: خلاصه، ریسک‌ها، قدم بعدی. User: ${userMsg}`
      );
      setMsgs((m) => [...m, { who: "ai", text: reply || "اتصال مدل محدود است، اما ساختار پاسخ آماده شد." }]);
      AudioCtl.chime();
    } catch (e) {
      setMsgs((m) => [...m, { who: "ai", text: "خطا در دریافت پاسخ. لطفا دوباره تلاش کنید." }]);
    }
    AudioCtl.stopAiPulse();
    setThinking(false);
  };

  return (
    <div className="smart-chat">
      <aside className="smart-chat-side">
        <div className="sc-model-card">
          <div className="sc-orb"><Ic.bot size={28} /></div>
          <b>مدل حقوقی شهداد</b>
          <span>{thinking ? "در حال تحلیل" : "آماده پاسخ"}</span>
        </div>
        <div className="sc-setting">
          <label>مود پاسخ</label>
          <div>{[["fast","سریع"],["deep","تفکر عمیق"],["formal","رسمی"]].map((x) => <button key={x[0]} className={mode === x[0] ? "on" : ""} onClick={() => setMode(x[0])}>{x[1]}</button>)}</div>
        </div>
        <div className="sc-setting">
          <label>لحن</label>
          <div>{[["simple","ساده"],["legal","حقوقی"],["lawyer","برای وکیل"]].map((x) => <button key={x[0]} className={tone === x[0] ? "on" : ""} onClick={() => setTone(x[0])}>{x[1]}</button>)}</div>
        </div>
        <div className="sc-files">
          <label>ارسال فایل</label>
          <div>{fileTypes.map((x) => <button key={x} onClick={() => addFile(x)}>{x}</button>)}</div>
        </div>
      </aside>
      <main className="smart-chat-main">
        <div className="sc-head">
          <div>
            <h3>گفت‌وگوی حقوقی شهداد</h3>
            <span>سند بده، سوال بپرس، خروجی قابل اقدام بگیر</span>
          </div>
          <div className="sc-status"><i /> {thinking ? thinkingSteps[stepIndex] : "آماده تحلیل"}</div>
        </div>
        <div className="chat-msgs smart" ref={scrollRef}>
          {msgs.map((m, i) => <div key={i} className={"msg " + m.who}>{m.text}</div>)}
          {files.map((f, i) => (
            <div key={"f"+i} className="file-chip">
              <Ic.paperclip size={15} />
              <b>{f.name}</b>
              <span>{f.type} · {f.status}</span>
              <button>تحلیل کن</button>
            </div>
          ))}
          {thinking && <div className="msg ai thinking-card"><div className="thinking-line"><i /><span>{thinkingSteps[stepIndex]}</span></div><div className="thinking-bar"><em /></div></div>}
        </div>
        <div className="quick-prompts">
          {quickPrompts.map((p) => <button key={p} onClick={() => setInput(p)}>{p}</button>)}
        </div>
        <div className="chat-input smart-input">
          <button className="small" title="Voice"><Ic.micSmall size={16}/></button>
          <button className="small" title="Attach" onClick={() => addFile("PDF")}><Ic.paperclip size={16}/></button>
          <input placeholder="سوال حقوقی، متن قرارداد یا خواسته‌ات را بنویس..." value={input} onChange={e=>setInput(e.target.value)} onKeyDown={e=>{if(e.key==="Enter")send();}}/>
          <button onClick={send}><Ic.send size={16}/></button>
        </div>
      </main>
    </div>
  );
};

const SocialShieldView = ({ lang }) => (
  <div>
    <div className="kpi-grid">
      <div className="kpi"><div className="n fa-num">{fmt(347, lang)}</div><div className="l">{lang==="fa"?"خانواده‌های تحت حمایت":"Families supported"}</div><div className="d">{lang==="fa"?"+۲۳ این ماه":"+23 this month"}</div></div>
      <div className="kpi"><div className="n fa-num">{fmt(128, lang)}</div><div className="l">{lang==="fa"?"داوطلب فعال":"Active volunteers"}</div><div className="d">{lang==="fa"?"+۹":"+9"}</div></div>
      <div className="kpi"><div className="n fa-num">{fmt(48, lang)}<small style={{fontSize:14}}>M</small></div><div className="l">{lang==="fa"?"کمک‌های جمع‌آوری شده":"Donations collected"}</div><div className="d">{lang==="fa"?"+۱۲٪":"+12%"}</div></div>
    </div>
    <h4 style={{fontSize:12.5, fontWeight:600, marginBottom:10, color:"var(--ice-white)"}}>{lang==="fa"?"درخواست‌های حمایت اخیر":"Recent support requests"}</h4>
    <table className="table">
      <thead><tr><th>#</th><th>{lang==="fa"?"نوع حمایت":"Type"}</th><th>{lang==="fa"?"شهر":"City"}</th><th>{lang==="fa"?"اولویت":"Priority"}</th><th>{lang==="fa"?"اقدام":"Action"}</th></tr></thead>
      <tbody>
        {[
          { id:"۲۲۰۹", t:{fa:"حمایت قانونی خانواده زندانی",en:"Legal support · prisoner's family"}, c:{fa:"تهران",en:"Tehran"}, p:"high"},
          { id:"۲۲۰۲", t:{fa:"حمایت روانی فرزندان",en:"Children psych support"}, c:{fa:"اصفهان",en:"Isfahan"}, p:"med"},
          { id:"۲۱۹۸", t:{fa:"معیشت ماهانه",en:"Monthly subsistence"}, c:{fa:"شیراز",en:"Shiraz"}, p:"high"},
        ].map(r=>(
          <tr key={r.id}><td className="fa-num">{r.id}</td><td>{r.t[lang]}</td><td>{r.c[lang]}</td>
            <td><span className={"pill " + (r.p==="high"?"danger":"warn")}>{r.p==="high"?(lang==="fa"?"بالا":"High"):(lang==="fa"?"متوسط":"Med")}</span></td>
            <td><button className="btn ghost" style={{padding:"4px 10px", fontSize:11}}>{lang==="fa"?"کمک می‌کنم":"Help"}</button></td></tr>
        ))}
      </tbody>
    </table>
  </div>
);

// Generic placeholder for any module not specifically built out
const GenericView = ({ lang, mod }) => (
  <div>
    <div className="kpi-grid">
      <div className="kpi"><div className="n fa-num">{fmt(124, lang)}</div><div className="l">{lang==="fa"?"موارد فعال":"Active items"}</div><div className="d">{lang==="fa"?"+۸٪":"+8%"}</div></div>
      <div className="kpi"><div className="n fa-num">{fmt(28, lang)}</div><div className="l">{lang==="fa"?"این هفته":"This week"}</div><div className="d">{lang==="fa"?"+۳":"+3"}</div></div>
      <div className="kpi"><div className="n fa-num">{fmt(96, lang)}<small style={{fontSize:14}}>%</small></div><div className="l">{lang==="fa"?"رضایت":"Satisfaction"}</div><div className="d">{lang==="fa"?"+۲":"+2"}</div></div>
    </div>
    <p style={{fontSize:12, color:"var(--frost)", lineHeight:1.8, marginBottom:14}}>
      {lang==="fa"
        ? "این ماژول به سیستم متصل است و در حال جمع‌آوری داده‌های زنده می‌باشد. از طریق گزارش‌ها، جدول‌ها و نمودارهای زیر می‌توانید به اطلاعات کامل دسترسی داشته باشید."
        : "This module is live-connected and gathering data. Explore the reports, tables, and analytics below for the complete view."}
    </p>
    <table className="table">
      <thead><tr>
        <th>#</th>
        <th>{lang==="fa"?"عنوان":"Title"}</th>
        <th>{lang==="fa"?"تاریخ":"Date"}</th>
        <th>{lang==="fa"?"وضعیت":"Status"}</th>
        <th></th>
      </tr></thead>
      <tbody>
        {[1,2,3,4].map(i => (
          <tr key={i}>
            <td className="fa-num">{fmt(1000 + i*7, lang)}</td>
            <td>{(lang==="fa"?"مورد شماره ":"Item #")+fmt(i, lang)}</td>
            <td className="fa-num">{lang==="fa"?`۱۴۰۲/۰۲/${fmt(10+i, lang)}`:`2026-05-${10+i}`}</td>
            <td><span className={"pill " + (i%2?"info":"ok")}>{i%2?(lang==="fa"?"در جریان":"Active"):(lang==="fa"?"تکمیل":"Complete")}</span></td>
            <td style={{textAlign:"end"}}><button className="btn ghost" style={{padding:"4px 10px", fontSize:11}}>{lang==="fa"?"مشاهده":"View"}</button></td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);

const ProfileView = ({ lang }) => {
  const [tab, setTab] = React.useState("profile");
  const tabs = [
    { id: "profile", iconKey: "user", fa: "پروفایل", en: "Profile" },
    { id: "plans", iconKey: "shieldCheck", fa: "پلن‌ها", en: "Plans" },
    { id: "security", iconKey: "shield", fa: "امنیت", en: "Security" },
  ];
  const items = [
    { iconKey: "user",     fa: "ویرایش پروفایل",        en: "Edit profile" },
    { iconKey: "shield",   fa: "امنیت و گذرواژه",       en: "Security & password" },
    { iconKey: "card",     fa: "اشتراک و پرداخت‌ها",     en: "Subscription & billing" },
    { iconKey: "bell",     fa: "تنظیمات اعلانات",        en: "Notification preferences" },
    { iconKey: "doc",      fa: "اسناد و مدارک من",       en: "My documents" },
    { iconKey: "settings", fa: "تنظیمات حساب",          en: "Account settings" },
  ];
  return (
    <div className="account-center">
      <div style={{display:"flex", gap:18, alignItems:"center", padding:"4px 0 18px", borderBottom:"1px dashed var(--line)"}}>
        <div style={{
          width:78, height:78, borderRadius:"50%",
          background:"linear-gradient(135deg, var(--gold), #b3935a)",
          display:"grid", placeItems:"center", fontSize:30, fontWeight:600, color:"#1a1a1a",
          boxShadow:"0 0 0 4px rgba(201,169,110,0.18), 0 0 24px rgba(201,169,110,0.35)"
        }}>ح</div>
        <div style={{flex:1}}>
          <h3 style={{fontSize:18, fontWeight:600, color:"var(--ice-white)"}}>
            {lang==="fa"?"حسین اروجی":"Hossein Oroji"}
          </h3>
          <div style={{fontSize:12, color:"var(--gold)", marginTop:4}}>
            {lang==="fa"?"وکیل پایه یک دادگستری":"Attorney at Law · Tier 1"}
          </div>
          <div style={{fontSize:11, color:"var(--frost)", opacity:0.7, marginTop:6, display:"flex", gap:12}}>
            <span><Ic.idcard size={11} style={{verticalAlign:"middle"}}/> <span className="fa-num">{lang==="fa"?"کد ملی: ۰۰۷۲۱۴۸۲۳۹":"ID: 0072148239"}</span></span>
            <span><Ic.shieldCheck size={11} style={{verticalAlign:"middle", color:"var(--cyan)"}}/> {lang==="fa"?"احراز هویت کامل":"Verified"}</span>
          </div>
        </div>
        <div style={{display:"flex", gap:8}}>
          <button className="btn ghost"><Ic.settings size={14}/> {lang==="fa"?"تنظیمات":"Settings"}</button>
          <button className="btn gold">{lang==="fa"?"خروج":"Sign out"}</button>
        </div>
      </div>

      <div className="account-tabs">
        {tabs.map((x) => {
          const Icon = Ic[x.iconKey] || Ic.user;
          return (
            <button key={x.id} className={tab === x.id ? "on" : ""} onClick={() => setTab(x.id)}>
              <Icon size={15} />
              <span>{x[lang] || x.en}</span>
            </button>
          );
        })}
      </div>

      {tab === "profile" && <React.Fragment>
      <div className="kpi-grid" style={{marginTop:16, gridTemplateColumns:"repeat(4, 1fr)"}}>
        <div className="kpi">
          <div className="n fa-num">{fmt(42, lang)}</div>
          <div className="l">{lang==="fa"?"پرونده‌های جاری":"Active cases"}</div>
        </div>
        <div className="kpi">
          <div className="n fa-num">{fmt(186, lang)}</div>
          <div className="l">{lang==="fa"?"پرونده‌های بسته":"Closed cases"}</div>
        </div>
        <div className="kpi">
          <div className="n fa-num">{fmt(4.9, lang)}<small style={{fontSize:14}}>/5</small></div>
          <div className="l">{lang==="fa"?"امتیاز کاربری":"Rating"}</div>
        </div>
        <div className="kpi">
          <div className="n">{lang==="fa"?"طلایی":"Gold"}</div>
          <div className="l">{lang==="fa"?"سطح اشتراک":"Plan tier"}</div>
          <div className="d">{lang==="fa"?"تا ۱۴۰۲/۰۸":"until 08/2026"}</div>
        </div>
      </div>

      <h4 style={{fontSize:12, fontWeight:600, color:"var(--ice-white)", margin:"18px 0 10px", letterSpacing:"0.04em"}}>
        {lang==="fa"?"دسترسی سریع":"Quick access"}
      </h4>
      <div style={{display:"grid", gridTemplateColumns:"repeat(2, 1fr)", gap:8}}>
        {items.map((it, i) => {
          const Icon = Ic[it.iconKey] || Ic.user;
          return (
            <button key={i} className="lcard" style={{
              padding:"12px 14px",
              display:"flex", alignItems:"center", gap:12, cursor:"pointer", textAlign:"start"
            }}>
              <div style={{
                width:36, height:36, borderRadius:10,
                background:"rgba(0,212,255,0.12)", border:"1px solid rgba(0,212,255,0.3)",
                display:"grid", placeItems:"center", color:"var(--cyan)"
              }}><Icon size={16}/></div>
              <div style={{flex:1}}>
                <div style={{fontSize:12.5, fontWeight:500, color:"var(--ice-white)"}}>{it[lang]}</div>
              </div>
              <Ic.chevL size={14} color="var(--frost)"/>
            </button>
          );
        })}
      </div>
      </React.Fragment>}

      {tab === "plans" &&
      <div className="plans-grid">
        {[
          ["مهمان", "رایگان", "پرسش محدود", "بدون کیف پول فعال"],
          ["پایه", "۴۹۰,۰۰۰", "مشاوره متنی", "ذخیره پرونده"],
          ["حرفه‌ای", "۹۹۰,۰۰۰", "تحلیل عمیق", "اولویت پشتیبانی"],
        ].map((p, i) => (
          <div className={"plan-card" + (i === 2 ? " active" : "")} key={p[0]}>
            <span>{p[0]}</span>
            <b className="fa-num">{p[1]} تومان</b>
            <small>{p[2]}</small>
            <small>{p[3]}</small>
            <button className={i === 2 ? "btn gold" : "btn ghost"}>{i === 2 ? "پلن فعلی" : "انتخاب پلن"}</button>
          </div>
        ))}
      </div>}

      {tab === "security" &&
      <div className="security-grid">
        {[
          ["احراز هویت", "تکمیل شده", "shieldCheck"],
          ["شماره موبایل", "تایید شده", "phone"],
          ["رمز عبور", "قابل تغییر", "shield"],
          ["نشست‌های فعال", "۲ دستگاه", "settings"],
        ].map((x) => {
          const Icon = Ic[x[2]] || Ic.shield;
          return (
            <div className="security-card" key={x[0]}>
              <Icon size={18} />
              <b>{x[0]}</b>
              <span>{x[1]}</span>
            </div>
          );
        })}
      </div>}
    </div>
  );
};

// Tri-lingual object accessor (ar falls back to en)
const L3 = (lang, o) => (o && (o[lang] || o.en)) || "";

// Calendar + clock panel — hearings, deadlines, private legal calendar
const CalendarView = ({ lang }) => {
  const [now, setNow] = React.useState(new Date());
  React.useEffect(() => { const id = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(id); }, []);
  const t = T[lang];
  const dg = (n) => lang === "fa" ? toFa(n) : lang === "ar" ? toAr(n) : String(n);

  const tf = new Intl.DateTimeFormat("en-GB", { timeZone: "Asia/Tehran", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" });
  const tp = Object.fromEntries(tf.formatToParts(now).map((p) => [p.type, p.value]));
  const timeStr = `${dg(tp.hour)}:${dg(tp.minute)}:${dg(tp.second)}`;
  const monShort = (t.monthName || "").split(" ")[0].slice(0, 4);

  let cells = Array.from({ length: 42 }, (_, i) => { const d = i - CAL_OFFSET + 1; return d >= 1 && d <= CAL_DAYS ? d : null; });
  while (cells.length > 35 && cells.slice(-7).every((c) => c === null)) cells.length -= 7;
  const dows = t.persianDays;

  const hearings = COURT_AGENDA.filter((a) => a.kind === "hearing" || a.kind === "arb").length;
  const deadlines = COURT_AGENDA.filter((a) => a.kind === "deadline").length;

  return (
    <div>
      <div className="row" style={{ marginBottom: 16, alignItems: "stretch" }}>
        <div className="cal-clock">
          <div className="cc-time fa-num">{timeStr}</div>
          <div className="cc-zone">{lang === "fa" ? "تهران · به وقت ایران" : lang === "ar" ? "طهران · بتوقيت طهران" : "Tehran · IRST"}</div>
          <div className="cc-date fa-num">{t.monthName}</div>
        </div>
        <div className="kpi"><div className="n fa-num">{dg(hearings)}</div><div className="l">{lang === "fa" ? "جلسات دادگاه و داوری" : lang === "ar" ? "جلسات المحكمة والتحكيم" : "Hearings & arbitration"}</div></div>
        <div className="kpi"><div className="n fa-num">{dg(deadlines)}</div><div className="l">{lang === "fa" ? "مهلت‌های نزدیک" : lang === "ar" ? "المواعيد القريبة" : "Upcoming deadlines"}</div></div>
        <div className="kpi"><div className="n fa-num">{dg(COURT_AGENDA.length)}</div><div className="l">{lang === "fa" ? "کل رویدادها" : lang === "ar" ? "إجمالي الأحداث" : "Total events"}</div></div>
      </div>

      <div className="cal-split">
        <div className="cal-month">
          <div className="cal-head">
            <div className="m">{t.monthName}</div>
            <div className="nav"><button><Ic.chevR size={12} /></button><button><Ic.chevL size={12} /></button></div>
          </div>
          <div className="cal-grid">
            {dows.map((d, i) => <div key={"h" + i} className="dow">{d}</div>)}
            {cells.map((d, i) => {
              if (d === null) return <div key={i} className="d mute"></div>;
              const cls = "d" + (d === CAL_TODAY ? " today" : "") + (CAL_EVENTS.includes(d) && d !== CAL_TODAY ? " has-event" : "");
              return <div key={i} className={cls}>{dg(d)}</div>;
            })}
          </div>
          <div className="cal-legend">
            <span><i className="lg today"></i> {lang === "fa" ? "امروز" : lang === "ar" ? "اليوم" : "Today"}</span>
            <span><i className="lg ev"></i> {lang === "fa" ? "رویداد" : lang === "ar" ? "حدث" : "Event"}</span>
          </div>
        </div>

        <div className="cal-agenda">
          <div className="agenda-title">{lang === "fa" ? "جلسات و مهلت‌های پیش‌رو" : lang === "ar" ? "الجلسات والمواعيد القادمة" : "Upcoming hearings & deadlines"}</div>
          {COURT_AGENDA.map((a, i) => {
            const k = AGENDA_KINDS[a.kind];
            const KIcon = Ic[k.iconKey] || Ic.chip;
            return (
              <div key={i} className="agenda-item">
                <div className="ag-date">
                  <div className="ag-day fa-num">{dg(a.day)}</div>
                  <div className="ag-mon">{monShort}</div>
                </div>
                <div className="ag-body">
                  <div className="ag-title">{L3(lang, a)}</div>
                  <div className="ag-meta">
                    <span className="ag-time fa-num"><Ic.clock size={11} /> {dg(a.time)}</span>
                    <span className={"pill " + k.pill}><KIcon size={11} /> {L3(lang, k)}</span>
                    {a.cs ? <span className="ag-case fa-num">#{dg(a.cs)}</span> : null}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

// ---- About & Contact (footer sections) ----
const AboutView = ({ lang }) => (
  <div>
    <p style={{ fontSize: 13, color: "var(--frost)", lineHeight: 2, marginBottom: 16 }}>
      {lang === "fa"
        ? "شهداد یک اکوسیستم حقوقیِ هوشمند است که خدمات حقوقی را در قالب یک منظومهٔ یکپارچه گرد هم می‌آورد: از مشاورهٔ هوشمند و وکالت تا داوری، تحلیل ریسک، قراردادهای هوشمند و سپر اجتماعی حقوقی. هدف ما، دسترس‌پذیر کردن عدالت با کمک هوش مصنوعی و شبکه‌ای از متخصصان معتبر است."
        : lang === "ar"
        ? "شهداد منظومة قانونية ذكية تجمع الخدمات القانونية في نظام واحد متكامل: من الاستشارة الذكية والمحاماة إلى التحكيم وتحليل المخاطر والعقود الذكية والدرع الاجتماعي القانوني."
        : "Shahdad is an intelligent legal ecosystem that unifies legal services into a single constellation — from AI consultation and representation to arbitration, risk analysis, smart contracts, and social legal protection. Our mission is to make justice accessible through AI and a network of verified experts."}
    </p>
    <div className="kpi-grid">
      <div className="kpi"><div className="n fa-num">{fmt(53, lang)}</div><div className="l">{lang === "fa" ? "ماژول هوشمند" : lang === "ar" ? "وحدة ذكية" : "Smart modules"}</div></div>
      <div className="kpi"><div className="n fa-num">{fmt(5, lang)}</div><div className="l">{lang === "fa" ? "لایهٔ خدمات" : lang === "ar" ? "طبقات الخدمة" : "Service layers"}</div></div>
      <div className="kpi"><div className="n fa-num">{fmt(18685, lang)}</div><div className="l">{lang === "fa" ? "کاربر فعال" : lang === "ar" ? "مستخدم نشط" : "Active users"}</div></div>
    </div>
    <div className="about-values">
      {[
        { ic: "shieldCheck", fa: "محرمانگی و امنیت داده", ar: "خصوصية وأمان البيانات", en: "Privacy & data security" },
        { ic: "scale", fa: "انطباق با قوانین ایران", ar: "متوافق مع القانون الإيراني", en: "Compliant with Iranian law" },
        { ic: "bot", fa: "هوش مصنوعی در خدمت عدالت", ar: "الذكاء الاصطناعي في خدمة العدالة", en: "AI in service of justice" },
      ].map((v, i) => {
        const Icon = Ic[v.ic] || Ic.chip;
        return (
          <div key={i} className="about-value">
            <span className="av-ic"><Icon size={16} /></span>
            <span>{v[lang] || v.en}</span>
          </div>);
      })}
    </div>
  </div>
);

const ContactView = ({ lang }) => {
  const rows = [
    { ic: "phone", label: { fa: "تلفن پشتیبانی", ar: "هاتف الدعم", en: "Support line" }, val: "۰۲۱ — ۹۱۰۰ ۰۰۰۰", ltr: false },
    { ic: "mail", label: { fa: "ایمیل", ar: "البريد الإلكتروني", en: "Email" }, val: "info@shahdad.ai", ltr: true },
    { ic: "mapPin", label: { fa: "نشانی", ar: "العنوان", en: "Address" }, val: { fa: "تهران، خیابان ولیعصر، برج شهداد", ar: "طهران، شارع ولي العصر", en: "Valiasr St., Shahdad Tower, Tehran" } },
    { ic: "clock", label: { fa: "ساعات کاری", ar: "ساعات العمل", en: "Working hours" }, val: { fa: "شنبه تا چهارشنبه · ۹ تا ۱۸", ar: "السبت - الأربعاء · ٩ - ١٨", en: "Sat–Wed · 9:00–18:00" } },
  ];
  return (
    <div>
      <p style={{ fontSize: 13, color: "var(--frost)", lineHeight: 1.9, marginBottom: 16 }}>
        {lang === "fa" ? "تیم پشتیبانی شهداد آمادهٔ پاسخگویی به شماست. از راه‌های زیر با ما در تماس باشید."
          : lang === "ar" ? "فريق دعم شهداد جاهز لمساعدتك. تواصل معنا عبر القنوات التالية."
          : "The Shahdad team is ready to help. Reach us through any of the channels below."}
      </p>
      <div className="contact-grid">
        {rows.map((r, i) => {
          const Icon = Ic[r.ic] || Ic.chip;
          const v = typeof r.val === "string" ? r.val : (r.val[lang] || r.val.en);
          return (
            <div key={i} className="contact-card">
              <span className="cc-ic"><Icon size={18} /></span>
              <div className="cc-body">
                <span className="cc-label">{r.label[lang] || r.label.en}</span>
                <span className={"cc-val" + (r.ltr ? " ltr" : "")}>{v}</span>
              </div>
            </div>);
        })}
      </div>
    </div>
  );
};

const AboutContactView = ({ lang }) => {
  const intro = lang === "fa"
    ? "شهداد در حال ساخت یک تجربه آرام، دقیق و قابل اعتماد برای خدمات حقوقی هوشمند است؛ جایی برای شروع مشاوره، پیگیری پرونده و رسیدن به پاسخ روشن، بدون شلوغی و ابهام."
    : lang === "ar"
    ? "شهداد يبني تجربة قانونية ذكية هادئة وموثوقة، تجمع الاستشارة والمتابعة والوصول إلى إجابة واضحة في مكان واحد."
    : "Shahdad is building a calm, precise, and trusted legal-tech experience for consultation, case follow-up, and clear answers in one place.";
  const rows = [
    { ic: "mapPin", label: { fa: "آدرس", ar: "العنوان", en: "Address" }, val: { fa: "فعلاً خالی", ar: "سيتم التحديث لاحقاً", en: "To be added" } },
    { ic: "phone", label: { fa: "شماره تماس", ar: "رقم الهاتف", en: "Phone" }, val: "021-9100-0000", ltr: true },
    { ic: "mail", label: { fa: "ایمیل", ar: "البريد الإلكتروني", en: "Email" }, val: "info@shahdad.ai", ltr: true },
    { ic: "clock", label: { fa: "ساعات کار پشتیبانی", ar: "ساعات الدعم", en: "Support hours" }, val: { fa: "شنبه تا چهارشنبه، ۹ تا ۱۸", ar: "السبت إلى الأربعاء، 9 إلى 18", en: "Sat to Wed, 9:00 to 18:00" } },
    { ic: "mapPin", label: { fa: "لوکیشن", ar: "الموقع", en: "Location" }, val: { fa: "در حال تکمیل", ar: "قيد التحديث", en: "Coming soon" } },
  ];
  const socials = [
    { key: "wa", label: "WhatsApp", short: "WA" },
    { key: "tg", label: "Telegram", short: "TG" },
    { key: "ig", label: "Instagram", short: "IG" },
    { key: "ba", label: "Bale", short: "BA" },
  ];
  return (
    <div className="about-contact">
      <div className="about-contact-head">
        <div>
          <h3>{lang === "fa" ? "درباره ما" : lang === "ar" ? "عن شهداد" : "About Us"}</h3>
          <p>{intro}</p>
        </div>
        <a className="enamad-seal" referrerPolicy="origin" target="_blank" rel="noopener noreferrer"
          href="https://trustseal.enamad.ir/?id=750815&Code=koK1icN65cm6rzASbEGUNHewNeVqs4qs">
          <span className="enamad-fallback">
            {lang === "fa" ? "نماد اعتماد الکترونیکی" : lang === "ar" ? "شارة الثقة الإلكترونية" : "eTrust seal"}
          </span>
          <img referrerPolicy="origin"
            src="https://trustseal.enamad.ir/logo.aspx?id=750815&Code=koK1icN65cm6rzASbEGUNHewNeVqs4qs"
            alt=""
            onError={(e) => { e.currentTarget.style.display = "none"; }}
            code="koK1icN65cm6rzASbEGUNHewNeVqs4qs" />
        </a>
      </div>

      <h4 className="contact-section-title">{lang === "fa" ? "تماس با ما" : lang === "ar" ? "اتصل بنا" : "Contact Us"}</h4>
      <div className="contact-grid about-contact-grid">
        {rows.map((r, i) => {
          const Icon = Ic[r.ic] || Ic.chip;
          const v = typeof r.val === "string" ? r.val : (r.val[lang] || r.val.en);
          return (
            <div key={i} className="contact-card">
              <span className="cc-ic"><Icon size={18} /></span>
              <div className="cc-body">
                <span className="cc-label">{r.label[lang] || r.label.en}</span>
                <span className={"cc-val" + (r.ltr ? " ltr" : "")}>{v}</span>
              </div>
            </div>
          );
        })}
      </div>

      <div className="social-row">
        {socials.map((s) => (
          <a key={s.key} className={"social-link " + s.key} href="#" onClick={(e) => e.preventDefault()} aria-label={s.label}>
            <span>{s.short}</span>
            <b>{s.label}</b>
          </a>
        ))}
      </div>
    </div>
  );
};

// MAP module key -> { iconKey, title fn, content component }
const MODULES = {
  about:      { iconKey: "info",        t: { fa:"درباره ما",          en:"About Us",             ar:"عن شهداد" },            s:{fa:"اطلاعات، اعتماد و راه‌های ارتباطی",en:"Trust and contact details", ar:"الثقة وطرق التواصل"}, View: AboutContactView },
  contact:    { iconKey: "phone",       t: { fa:"تماس با ما",          en:"Contact Us",           ar:"اتصل بنا" },            s:{fa:"راه‌های ارتباطی شهداد",en:"How to reach Shahdad", ar:"طرق التواصل"}, View: AboutContactView },
  // hex wheel
  consult:    { iconKey: "chat",        t: { fa:"مشاوره حقوقی",       en:"Legal Consultation" }, s:{fa:"مدیریت جلسات مشاوره",en:"Manage your sessions"}, View: ConsultView },
  lawyer:     { iconKey: "scale",       t: { fa:"وکیل و معرفی وکلا", en:"Lawyers & Directory", ar:"دليل المحامين" }, s:{fa:"انتخاب آگاهانه از شبکه وکلای متخصص",en:"Choose from a verified attorney network",ar:"شبكة محامين موثقة"}, View: LawyerView },
  case:       { iconKey: "folder",      t: { fa:"مدیریت پرونده‌ها",   en:"Case Management" },    s:{fa:"تمام پرونده‌های در جریان",en:"All active matters"}, View: CaseView },
  expert:     { iconKey: "microscope",  t: { fa:"کارشناسان و معرفی کارشناس",en:"Experts & Directory",ar:"دليل الخبراء"}, s:{fa:"انتخاب آگاهانه از شبکه کارشناسان رسمی",en:"Choose from verified official experts",ar:"شبكة خبراء موثقة"}, View: RealExpertView },
  arb:        { iconKey: "gavel",       t: { fa:"داوری و حل اختلاف",  en:"Arbitration" },        s:{fa:"حل اختلاف خارج از دادگاه",en:"Out-of-court resolution"}, View: GenericView },
  panel:      { iconKey: "group",       t: { fa:"هیئت حل اختلاف خصوصی",en:"Dispute Panel" },     s:{fa:"داوران شبکه شهداد",en:"Shahdad arbiter network"}, View: GenericView },
  risk:       { iconKey: "shieldAlert", t: { fa:"تحلیل ریسک حقوقی",   en:"Legal Risk Analysis" },s:{fa:"تحلیل ریسک با هوش مصنوعی",en:"AI-powered risk analysis"}, View: RiskView },
  contracts:  { iconKey: "doc",         t: { fa:"قراردادها و اسناد",  en:"Contracts & Documents"}, s:{fa:"قراردادها با تحلیل هوشمند",en:"Smart contract analysis"}, View: ContractsView },
  calc:       { iconKey: "calc",        t: { fa:"محاسبات حقوقی و مالی",en:"Legal Calculators"}, s:{fa:"ارث، مهریه، دیه",en:"Inheritance · Mahrieh · Diye"}, View: CalcView },
  shield:     { iconKey: "shield",      t: { fa:"سپر حقوقی (بیمه)",   en:"Legal Shield"},        s:{fa:"بیمه و پوشش حقوقی",en:"Legal insurance & coverage"}, View: GenericView },
  media:      { iconKey: "mic",         t: { fa:"پادکست و رسانه حقوقی",en:"Podcasts & Media"},   s:{fa:"محتوای آموزشی صوتی",en:"Audio legal content"}, View: GenericView },
  edu:        { iconKey: "cap",         t: { fa:"آموزش و وبینارها",   en:"Education & Webinars"},s:{fa:"دوره‌های تخصصی حقوقی",en:"Specialist legal courses"}, View: GenericView },
  api:        { iconKey: "chip",        t: { fa:"API و یکپارچگی",     en:"API & Integration"},   s:{fa:"اتصال به سیستم‌های سازمانی",en:"Enterprise integrations"}, View: GenericView },
  compliance: { iconKey: "shieldCheck", t: { fa:"کامپلاینس حقوقی",     en:"Compliance"},          s:{fa:"بررسی انطباق با مقررات",en:"Regulatory compliance"}, View: GenericView },
  strategy:   { iconKey: "barchart",    t: { fa:"شبیه‌ساز استراتژی و دعاوی", en:"Strategy & Litigation Simulator"}, s:{fa:"شبیه‌سازی مسیر پرونده با AI",en:"AI litigation path simulator"}, View: GenericView },
  drafting:   { iconKey: "scroll",      t: { fa:"دستیار نگارش حقوقی", en:"Legal Drafting Assistant"}, s:{fa:"تنظیم لوایح و اسناد با AI",en:"AI-assisted drafting"}, View: GenericView },

  // Sidebar extras
  dashboard:  { iconKey: "home",        t: { fa:"داشبورد اصلی",       en:"Dashboard"},           s:{fa:"نمای کلی اکوسیستم",en:"Ecosystem overview"}, View: GenericView },
  social:     { iconKey: "heart",       t: { fa:"سپر اجتماعی حقوقی",  en:"Social Legal Shield"}, s:{fa:"حمایت از زندانیان و خانواده‌ها",en:"Support for inmates & families"}, View: SocialShieldView },
  clock:      { iconKey: "clock",       t: { fa:"ساعت و تقویم حقوقی", en:"Legal Time & Calendar"}, s:{fa:"مهلت‌ها و دادگاه‌ها",en:"Deadlines & hearings"}, View: CalendarView },
  org:        { iconKey: "building",    t: { fa:"شرکت‌ها و سازمان‌ها",en:"Organizations"},       s:{fa:"حساب‌های سازمانی",en:"Org accounts"}, View: GenericView },
  settings:   { iconKey: "settings",    t: { fa:"تنظیمات و شخصی‌سازی",en:"Settings"},            s:{fa:"تنظیمات حساب کاربری",en:"Account preferences"}, View: GenericView },

  // Quick actions
  newCase:    { iconKey: "plus",        t: { fa:"ایجاد پرونده جدید",  en:"New Case"},            s:{fa:"ثبت پرونده در سیستم",en:"Register a new matter"}, View: CaseView },
  reqConsult: { iconKey: "chat",        t: { fa:"درخواست مشاوره",     en:"Request Consultation"},s:{fa:"رزرو وقت با وکیل",en:"Book a lawyer session"}, View: ConsultView },
  bookLawyer: { iconKey: "user",        t: { fa:"تعیین وقت وکیل",     en:"Book a Lawyer"},       s:{fa:"شبکه وکلای متخصص",en:"Specialist network"}, View: LawyerView },
  quickCalc:  { iconKey: "calc",        t: { fa:"محاسبه سریع",        en:"Quick Calculate"},     s:{fa:"ارث، مهریه، دیه",en:"Inheritance · Mahrieh · Diye"}, View: CalcView },

  // AI chat
  aiChat:     { iconKey: "bot",         t: { fa:"چت حقوقی هوشمند",    en:"AI Legal Chat"},       s:{fa:"دستیار AI همیشه همراه شما",en:"Your AI assistant"}, View: AIChatView },

  // Profile / user panel
  profile:    { iconKey: "idcard",      t: { fa:"مرکز هویت و پروفایل", en:"Identity & Profile"},   s:{fa:"هویت مرکزی، نقش‌ها و اعتبارسنجی",en:"Identity, roles and validation"}, View: ProfilingView },
  plans:      { iconKey: "shieldCheck", t: { fa:"پلن‌ها و اشتراک", en:"Plans & Subscription"},      s:{fa:"مقایسه پلن‌های شخصی و سازمانی",en:"Compare individual and organization plans"}, View: window.PlanCenterView },
  wallet:     { iconKey: "coin",        t: { fa:"کیف پول و پرداخت‌ها",ar:"المحفظة والمدفوعات",en:"Wallet & Payments"},      s:{fa:"مانده، شارژ حساب و مدیریت مالی",ar:"الرصيد والشحن والتحكم المالي",en:"Balance, funding and financial controls"}, View: window.WalletCenterView },

  // Quick grid items - default to GenericView
};
// fill the rest of QGRID with generic views
QGRID.forEach((q) => {
  if (!MODULES[q.id]) {
    MODULES[q.id] = { iconKey: q.iconKey, t: { fa: q.fa, en: q.en }, s: { fa: "ماژول هوشمند", en: "Smart module" }, View: GenericView };
  }
});

const MODULE_SCENE_META = {
  aiChat: { sceneLabel: { fa: "سین ۱ و ۱۵: گفت‌وگوی هوشمند", en: "Scenes 1 & 15: smart chat" }, backendKeys: ["chat_threads", "messages", "attachments", "model_mode"] },
  consult: { sceneLabel: { fa: "سین ۲ و ۴: مشاوره چندحالته", en: "Scenes 2 & 4: multi-mode consultation" }, backendKeys: ["consultation_requests", "sessions", "lawyer_profiles", "payments"] },
  reqConsult: { sceneLabel: { fa: "سین ۲: شروع درخواست مشاوره", en: "Scene 2: consultation request" }, backendKeys: ["consultation_requests", "availability", "payments"] },
  case: { sceneLabel: { fa: "سین ۵ تا ۷: مدیریت پرونده", en: "Scenes 5-7: case management" }, backendKeys: ["cases", "case_events", "tasks", "participants"] },
  newCase: { sceneLabel: { fa: "سین ۵: تشکیل پرونده جدید", en: "Scene 5: new case intake" }, backendKeys: ["cases", "documents", "participants"] },
  docmgmt: { sceneLabel: { fa: "سین ۸ و ۱۴: اسناد کنار دستیار", en: "Scenes 8 & 14: documents with assistant" }, backendKeys: ["document_versions", "document_analysis", "assistant_context"] },
  contracts: { sceneLabel: { fa: "سین ۱۴: قرارداد و بازبینی", en: "Scene 14: contract review" }, backendKeys: ["contracts", "templates", "reviews", "signatures"] },
  contractMgmt: { sceneLabel: { fa: "سین ۱۴: چرخه قرارداد", en: "Scene 14: contract lifecycle" }, backendKeys: ["contracts", "templates", "reviews", "signatures"] },
  calendar: { sceneLabel: { fa: "سین ۱۲: تقویم و مهلت‌ها", en: "Scene 12: calendar and deadlines" }, backendKeys: ["calendar_events", "court_deadlines", "availability"] },
  clock: { sceneLabel: { fa: "سین ۱۲: زمان حقوقی", en: "Scene 12: legal time" }, backendKeys: ["court_deadlines", "reminders"] },
  wallet: { sceneLabel: { fa: "سین ۹ و ۱۳: کیف پول و پرداخت", ar: "المشهدان ٩ و١٣: المحفظة والمدفوعات", en: "Scenes 9 & 13: wallet and payments" }, backendKeys: ["wallet", "transactions", "invoices"] },
  profile: { sceneLabel: { fa: "سین ۹: پروفایل، پلن و حساب", en: "Scene 9: profile, plan and account" }, backendKeys: ["profile", "plans", "subscriptions"] },
  plans: { sceneLabel: { fa: "انتخاب پلن و مدیریت اشتراک", en: "Plan selection and subscription management" }, backendKeys: ["plans", "subscriptions", "checkout"] },
  risk: { sceneLabel: { fa: "سین ۱۰: تحلیل ریسک", en: "Scene 10: risk analysis" }, backendKeys: ["risk_scores", "analytics"] },
  riskScore: { sceneLabel: { fa: "سین ۱۰: امتیاز ریسک", en: "Scene 10: risk scoring" }, backendKeys: ["risk_scores", "analytics"] },
  justice: { sceneLabel: { fa: "سین ۱۰: تحلیل عدالت", en: "Scene 10: justice analytics" }, backendKeys: ["analytics", "charts"] },
  org: { sceneLabel: { fa: "سین ۱۱: داشبورد سازمانی", en: "Scene 11: organization dashboard" }, backendKeys: ["organization_accounts", "roles", "audit_logs"] },
  compliance: { sceneLabel: { fa: "سین ۱۱: انطباق و گزارش", en: "Scene 11: compliance and audit" }, backendKeys: ["compliance_checks", "audit_logs"] },
  calc: { sceneLabel: { fa: "سین ۱۳: محاسبات حقوقی", en: "Scene 13: legal calculations" }, backendKeys: ["calculations", "tariffs"] },
  quickCalc: { sceneLabel: { fa: "سین ۱۳: محاسبه سریع", en: "Scene 13: quick calculation" }, backendKeys: ["calculations", "tariffs"] },
};
Object.keys(MODULE_SCENE_META).forEach((id) => {
  if (MODULES[id]) Object.assign(MODULES[id], MODULE_SCENE_META[id]);
});
// Specialized overrides for common quick-grid
if (MODULES.docmgmt) MODULES.docmgmt.View = ContractsView;
if (MODULES.contractMgmt) MODULES.contractMgmt.View = ContractsView;
if (MODULES.riskScore) MODULES.riskScore.View = RiskView;
if (MODULES.calendar) MODULES.calendar.View = CalendarView;
if (MODULES.aiChat) {
  MODULES.aiChat.View = SmartAIChatView;
  MODULES.aiChat.t = { fa: "گفت‌وگوی حقوقی شهداد", en: "AI Legal Chat" };
  MODULES.aiChat.s = { fa: "مود عمیق، فایل، تحلیل و پاسخ قابل اقدام", en: "Deep mode, files, analysis and action-ready answers" };
}

Object.assign(window, { Modal, MODULES });
