// V31.106 - Smart Lawyer: paid access gate and cross-module workspace.
const SmartLawyerView = ({ lang, session, onOpen }) => {
  const t = (fa, en) => lang === "en" ? en : fa;
  const tools = [
    { id:"case", icon:"folder", title:t("مدیریت پرونده","Case management"), detail:t("زمینه، رویداد و گردش کار","Context, events and workflow") },
    { id:"docmgmt", icon:"doc", title:t("اسناد حقوقی","Legal documents"), detail:t("خواندن و تحلیل مستندات","Read and analyze documents") },
    { id:"contracts", icon:"docEdit", title:t("قراردادها","Contracts"), detail:t("بازبینی بندها و تعارض‌ها","Review clauses and conflicts") },
    { id:"risk", icon:"shieldAlert", title:t("تحلیل ریسک","Risk analysis"), detail:t("ریسک، شدت و اقدام اصلاحی","Risk, severity and mitigation") },
    { id:"drafting", icon:"scroll", title:t("نگارش حقوقی","Legal drafting"), detail:t("لایحه، دادخواست و نامه","Briefs, petitions and letters") },
    { id:"calc", icon:"calc", title:t("محاسبات حقوقی","Legal calculations"), detail:t("ارث، مهریه، دیه و تعرفه","Inheritance, mahr and tariffs") },
    { id:"lawyer", icon:"scale", title:t("شبکه وکلا","Lawyer network"), detail:t("۶ پروفایل فعال فعلی","6 active profiles") },
    { id:"expert", icon:"microscope", title:t("کارشناسان رسمی","Official experts"), detail:t("انتخاب کارشناس متناسب","Match the right expert") },
    { id:"clock", icon:"clock", title:t("تقویم حقوقی","Legal calendar"), detail:t("مهلت‌ها، جلسات و یادآوری","Deadlines and hearings") },
    { id:"consult", icon:"chat", title:t("مشاوره","Consultation"), detail:t("متنی، صوتی، تصویری و ترکیبی","Text, voice, video and hybrid") }
  ];
  const toolById = Object.fromEntries(tools.map((tool) => [tool.id, tool]));
  const prompts = [
    { label:t("پرونده‌ام را بررسی کن","Review my case"), prompt:t("پرونده‌های باز من را بررسی کن و سه اقدام بعدی را به ترتیب اولویت بگو.","Review my open cases and prioritize the next three actions."), tools:["case","docmgmt","clock"] },
    { label:t("این قرارداد چه ریسکی دارد؟","Assess this contract"), prompt:t("این قرارداد را تحلیل کن، بندهای پرریسک را مشخص کن و اصلاح پیشنهادی بده.","Analyze this contract, flag risky clauses and suggest revisions."), tools:["contracts","risk","drafting"] },
    { label:t("بهترین وکیل را پیدا کن","Find the right lawyer"), prompt:t("از میان وکلای فعلی، مناسب‌ترین وکیل را بر اساس موضوع، شهر و امتیاز پیشنهاد بده.","Recommend the best current lawyer by matter, city and score."), tools:["lawyer","consult"] },
    { label:t("برایم لایحه آماده کن","Draft a legal brief"), prompt:t("بر اساس اطلاعات پرونده و اسناد، پیش‌نویس لایحه را با استنادهای لازم آماده کن.","Draft a legal brief from the case and documents with relevant citations."), tools:["case","docmgmt","drafting"] }
  ];
  const thinkingSteps = [
    t("تشخیص نوع مسئله و انتخاب مسیر...","Classifying the matter and selecting a route..."),
    t("فراخوانی ماژول‌های مرتبط...","Calling the relevant modules..."),
    t("تطبیق داده‌ها و منابع حقوقی...","Cross-checking legal data and sources..."),
    t("ترکیب نتیجه در یک پاسخ قابل اقدام...","Composing one actionable response...")
  ];

  const currentPlan = typeof getCurrentPlan === "function" ? getCurrentPlan(session) : null;
  const subscriptionActive = Boolean(session && !session.isGuest && typeof isSubscriptionActive === "function" && isSubscriptionActive(session.subscription));
  const hasPaidPlan = Boolean(subscriptionActive && currentPlan && currentPlan.id !== "pluto");
  const currentPlanName = currentPlan && typeof planLocalize === "function" ? planLocalize(lang, currentPlan.name) : t("پلوتون","Pluto");
  const [selectedTools, setSelectedTools] = React.useState(["case","docmgmt","risk"]);
  const [messages, setMessages] = React.useState([{
    who:"ai",
    text:t("سلام، من وکیل هوشمند شهداد هستم. مسئله را یک‌بار توضیح بده؛ خودم ابزارهای لازم را انتخاب می‌کنم و یک پاسخ منسجم و قابل اقدام می‌سازم.","Hello, I am Shahdad's Smart Lawyer. Describe the matter once; I will select the right tools and compose one actionable answer."),
    tools:[]
  }]);
  const [input, setInput] = React.useState(() => {
    const pending = (typeof window !== "undefined" && window.__pendingAsk) || "";
    if (pending) window.__pendingAsk = "";
    return pending;
  });
  const [files, setFiles] = React.useState([]);
  const [thinking, setThinking] = React.useState(false);
  const [stepIndex, setStepIndex] = React.useState(0);
  const [runLog, setRunLog] = React.useState([]);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, files, thinking, runLog]);
  React.useEffect(() => {
    if (!thinking) return;
    setStepIndex(0);
    const timer = setInterval(() => setStepIndex((value) => (value + 1) % thinkingSteps.length), 1050);
    return () => clearInterval(timer);
  }, [thinking]);

  const renderIcon = (tool, size=18) => {
    const ToolIcon = Ic[tool.icon] || Ic.bot;
    return <ToolIcon size={size}/>;
  };
  const openTool = (id) => {
    if (!hasPaidPlan || !onOpen) return;
    AudioCtl.open();
    onOpen(id);
  };
  const toggleTool = (id) => {
    AudioCtl.click();
    setSelectedTools((current) => current.includes(id) ? current.filter((toolId) => toolId !== id) : [...current, id]);
  };
  const choosePrompt = (item) => {
    AudioCtl.click();
    setInput(item.prompt);
    setSelectedTools(item.tools);
  };
  const addFile = (type) => {
    AudioCtl.click();
    setFiles((current) => [...current, { id:`${Date.now()}-${current.length}`, type, name:type === "قرارداد" ? "قرارداد آماده بررسی" : `${type} پیوست`, status:t("آماده تحلیل","Ready for analysis") }]);
    setSelectedTools((current) => current.includes("docmgmt") ? current : [...current,"docmgmt"]);
  };
  const inferTools = (question) => {
    const detected = new Set(selectedTools);
    if (/قرارداد|بند|تعهد|مبایعه|اجاره|contract|clause/i.test(question)) ["contracts","risk","drafting"].forEach((id) => detected.add(id));
    if (/پرونده|دادگاه|جلسه|مهلت|ابلاغ|case|court|deadline/i.test(question)) ["case","docmgmt","clock"].forEach((id) => detected.add(id));
    if (/وکیل|مشاور|نماینده|lawyer|counsel/i.test(question)) ["lawyer","consult"].forEach((id) => detected.add(id));
    if (/ارث|مهریه|دیه|محاسبه|تعرفه|inheritance|calculate/i.test(question)) detected.add("calc");
    if (/کارشناس|کارشناسی|expert/i.test(question)) detected.add("expert");
    return [...detected].filter((id) => toolById[id]);
  };
  const send = async () => {
    const question = input.trim();
    if (!hasPaidPlan || !question || thinking) return;
    const routedTools = inferTools(question);
    setMessages((current) => [...current, { who:"user", text:question, tools:[] }]);
    setInput("");
    setSelectedTools(routedTools);
    setRunLog(routedTools.map((id) => ({ id, status:"running" })));
    setThinking(true);
    AudioCtl.startAiPulse();
    try {
      const moduleNames = routedTools.map((id) => toolById[id].title).join("، ");
      const prompt = `You are SHAHDAD AI Smart Lawyer for Iranian law. Selected Shahdad modules: ${moduleNames}. Reply in ${lang === "en" ? "English" : "Persian"} with concise sections: summary, findings, risks, next action. Cite article numbers only when confident. User: ${question}`;
      const canComplete = window.claude && typeof window.claude.complete === "function";
      const reply = canComplete ? await window.claude.complete(prompt) : "";
      setMessages((current) => [...current, {
        who:"ai",
        text:reply || t("مسیر تحلیل آماده شد. در اتصال عملیاتی، داده‌های ماژول‌های انتخاب‌شده بررسی و نتیجه همراه با منابع، ریسک‌ها و اقدام بعدی در همین‌جا یکپارچه می‌شود.","The analysis route is ready. In live integration, selected module data will be combined here with sources, risks and next actions."),
        tools:routedTools
      }]);
      setRunLog(routedTools.map((id) => ({ id, status:"done" })));
      AudioCtl.chime();
    } catch (error) {
      setMessages((current) => [...current, { who:"ai", text:t("پاسخ دریافت نشد. مسیر ماژول‌ها حفظ شده است؛ دوباره تلاش کنید.","No response was received. The module route is preserved; please retry."), tools:routedTools }]);
      setRunLog(routedTools.map((id) => ({ id, status:"ready" })));
    }
    AudioCtl.stopAiPulse();
    setThinking(false);
  };

  if (!hasPaidPlan) return (
    <div className="smart-lawyer-gate">
      <section className="sl-gate-card">
        <div className="sl-gate-copy">
          <div className="sl-gate-seal"><Ic.bot size={34}/></div>
          <span className="sl-kicker">{t("وکیل هوشمند شهداد AI","Shahdad AI Smart Lawyer")}</span>
          <h2>{t("دسترسی این ماژول به پلن پولی فعال نیاز دارد","This module requires an active paid plan")}</h2>
          <p>{t("وکیل هوشمند یک چت ساده نیست؛ برای بررسی پرونده، تحلیل سند و استفاده از سایر ماژول‌ها باید اشتراک پولی حساب فعال باشد.","Smart Lawyer is more than chat. An active paid subscription is required to inspect cases, analyze documents and use other modules.")}</p>
          <div className="sl-entitlement"><div><span>{t("پلن فعلی","Current plan")}</span><strong>{currentPlanName || t("پلوتون","Pluto")}</strong></div><em>{t("فاقد دسترسی وکیل هوشمند","Smart Lawyer unavailable")}</em></div>
          <div className="sl-gate-features">
            <span><Ic.shieldCheck size={17}/>{t("دسترسی یکپارچه به ۵۳ ماژول در ۵ لایه","Integrated access to 53 modules across 5 layers")}</span>
            <span><Ic.shieldCheck size={17}/>{t("تحلیل پرونده، سند، قرارداد و ریسک در یک جریان","Case, document, contract and risk analysis in one flow")}</span>
            <span><Ic.shieldCheck size={17}/>{t("ثبت مسیر ابزارها و ارائه پاسخ نهایی منسجم","Visible tool trail and one coherent final answer")}</span>
          </div>
          <button className="sl-primary" onClick={() => { AudioCtl.open(); if (onOpen) onOpen("plans"); }}><Ic.shieldCheck size={17}/>{t("مشاهده و فعال‌سازی پلن‌ها","View and activate plans")}</button>
        </div>
        <div className="sl-gate-preview" aria-label={t("پیش‌نمایش غیرعملیاتی فضای وکیل هوشمند","Non-operational Smart Lawyer preview")}>
          <div className="sl-preview-label"><span>{t("پیش‌نمایش رابط پس از فعال‌سازی","Interface preview after activation")}</span><em>{t("غیرعملیاتی","Non-operational")}</em></div>
          <div className="sl-preview-board">
            <div className="sl-preview-tools"><b>{t("ابزارها","Tools")}</b>{tools.slice(0,6).map((tool,index) => <span key={tool.id} className={index < 3 ? "on" : ""}>{renderIcon(tool,13)}{tool.title}</span>)}</div>
            <div className="sl-preview-chat"><header><strong>{t("فضای کار پرونده","Matter workspace")}</strong><i/></header><div className="sl-preview-message ai">{t("موضوع را بگو؛ ابزارهای لازم را من انتخاب می‌کنم.","Describe the matter; I will select the required tools.")}</div><div className="sl-preview-message user">{t("این قرارداد را بررسی کن و قدم بعدی را بگو.","Review this contract and give me the next step.")}</div><div className="sl-preview-input">{t("درخواست حقوقی خود را بنویسید...","Write your legal request...")}</div></div>
            <div className="sl-preview-route"><b>{t("مسیر اجرا","Execution route")}</b><span>۱ · {t("قراردادها","Contracts")}</span><span>۲ · {t("تحلیل ریسک","Risk analysis")}</span><span>۳ · {t("نگارش حقوقی","Legal drafting")}</span><small>۵۳ {t("ماژول در دسترس","modules available")}</small></div>
          </div>
          <small>{t("این نما فقط برای ارزیابی طراحی است و هیچ ماژول یا موتور هوش مصنوعی را اجرا نمی‌کند.","This view is for design evaluation only and runs no module or AI engine.")}</small>
        </div>
      </section>
    </div>
  );

  return (
    <div className="smart-lawyer">
      <header className="sl-topbar">
        <div className="sl-identity"><div className="sl-orb"><Ic.bot size={25}/></div><div><span className="sl-kicker">{t("شهداد AI","SHAHDAD AI")}</span><h2>{t("وکیل هوشمند","Smart Lawyer")}</h2><p>{t("یک مسئله، تمام ابزارهای حقوقی لازم","One matter, every legal tool it needs")}</p></div></div>
        <div className="sl-top-actions"><button className="sl-ecosystem-button" onClick={() => openTool("ecosystem")}><Ic.chip size={16}/>{t("۵۳ ماژول در ۵ لایه","53 modules in 5 layers")}</button><span className="sl-plan-status"><i/>{t(`پلن ${currentPlanName} فعال`,`${currentPlanName} active`)}</span></div>
      </header>
      <div className="sl-workspace">
        <aside className="sl-tool-rail">
          <div className="sl-section-head"><div><span>{t("دسترسی کامل","Full access")}</span><h3>{t("ابزارهای قابل فراخوانی","Callable tools")}</h3></div><b>{selectedTools.length}</b></div>
          <p className="sl-section-copy">{t("وکیل هوشمند ابزارها را خودکار انتخاب می‌کند؛ برای کنترل بیشتر می‌توانید مسیر را تغییر دهید.","Smart Lawyer selects tools automatically; you can adjust the route.")}</p>
          <div className="sl-tool-list">{tools.map((tool) => { const selected=selectedTools.includes(tool.id); return <button key={tool.id} className={"sl-tool "+(selected?"selected":"")} aria-pressed={selected} onClick={() => toggleTool(tool.id)}><span className="sl-tool-icon">{renderIcon(tool)}</span><span><strong>{tool.title}</strong><small>{tool.detail}</small></span><i aria-hidden="true"/></button>; })}</div>
        </aside>
        <main className="sl-chat-panel">
          <div className="sl-chat-head"><div><span className="sl-kicker">{t("فضای کار پرونده","Matter workspace")}</span><h3>{t("موضوع را بگو؛ مسیر اجرا را من می‌سازم","Describe the matter; I will build the route")}</h3></div><span className="sl-live"><i/>{thinking?thinkingSteps[stepIndex]:t("آماده دریافت درخواست","Ready")}</span></div>
          <div className="sl-messages" ref={scrollRef}>
            {messages.map((message,index) => <article key={index} className={"sl-message "+message.who}><span className="sl-message-avatar">{message.who==="ai"?<Ic.bot size={17}/>:<Ic.user size={17}/>}</span><div className="sl-message-body"><p>{message.text}</p>{message.tools&&message.tools.length>0&&<div className="sl-message-tools"><span>{t("ابزارهای استفاده‌شده","Tools used")}</span>{message.tools.map((id)=>toolById[id]&&<button key={id} onClick={()=>openTool(id)}>{renderIcon(toolById[id],13)}{toolById[id].title}</button>)}</div>}</div></article>)}
            {files.map((file)=><article className="sl-file" key={file.id}><span><Ic.paperclip size={17}/></span><div><strong>{file.name}</strong><small>{file.type} · {file.status}</small></div><button onClick={()=>setInput(t("این فایل را تحلیل کن و نکات حقوقی قابل اقدام را استخراج کن.","Analyze this file and extract actionable legal points."))}>{t("افزودن به درخواست","Add to request")}</button></article>)}
            {thinking&&<article className="sl-thinking"><div><i/><span>{thinkingSteps[stepIndex]}</span></div><em><b/></em></article>}
          </div>
          <div className="sl-quick-prompts">{prompts.map((item)=><button key={item.label} onClick={()=>choosePrompt(item)}>{item.label}</button>)}</div>
          <div className="sl-composer"><button className="sl-attach" onClick={()=>addFile("PDF")} title={t("افزودن PDF","Add PDF")}><Ic.paperclip size={17}/></button><textarea rows="2" value={input} onChange={(event)=>setInput(event.target.value)} onKeyDown={(event)=>{if(event.key==="Enter"&&!event.shiftKey){event.preventDefault();send();}}} placeholder={t("سوال، موضوع پرونده، متن قرارداد یا خواسته‌ات را بنویس...","Write your question, case, contract or request...")}/><button className="sl-send" disabled={!input.trim()||thinking} onClick={send} aria-label={t("ارسال درخواست","Send request")}><Ic.send size={18}/></button></div>
          <div className="sl-composer-meta"><span>{t("PDF، Word، تصویر، صوت، قرارداد و دادخواست","PDF, Word, image, audio, contract and petition")}</span><span>{t("خروجی باید پیش از اقدام حقوقی نهایی بررسی شود","Review output before final legal action")}</span></div>
        </main>
        <aside className="sl-run-panel">
          <div className="sl-run-summary"><span className="sl-kicker">{t("وضعیت ارکستراتور","Orchestrator status")}</span><strong>{t("دسترسی سراسری فعال","Global access enabled")}</strong><p>{t("هر درخواست می‌تواند چند ماژول را در یک مسیر واحد به کار بگیرد.","Each request can use several modules in one route.")}</p><div><span><b>۵۳</b>{t("ماژول","modules")}</span><span><b>۵</b>{t("لایه","layers")}</span><span><b>۱</b>{t("پاسخ","answer")}</span></div></div>
          <section className="sl-run-route"><div className="sl-section-head"><div><span>{t("ردپای اجرا","Execution trail")}</span><h3>{t("مسیر همین درخواست","Current request route")}</h3></div></div>{runLog.length===0?<div className="sl-empty-route"><Ic.chip size={22}/><strong>{t("هنوز درخواستی اجرا نشده","No request has run yet")}</strong><span>{t("پس از ارسال، ماژول‌های درگیر اینجا دیده می‌شوند.","Used modules will appear here after sending.")}</span></div>:<ol>{runLog.map((item,index)=>{const tool=toolById[item.id];if(!tool)return null;return <li key={item.id}><span className={"sl-route-state "+item.status}>{item.status==="done"?<Ic.shieldCheck size={14}/>:index+1}</span><div><strong>{tool.title}</strong><small>{item.status==="running"?t("در حال فراخوانی","Calling"):item.status==="done"?t("مسیر تکمیل شد","Route complete"):t("آماده","Ready")}</small></div><button onClick={()=>openTool(item.id)} aria-label={t(`باز کردن ${tool.title}`,`Open ${tool.title}`)}><Ic.chevL size={15}/></button></li>;})}</ol>}</section>
          <section className="sl-current-data"><span className="sl-kicker">{t("داده‌های فعلی","Current data")}</span><h3>{t("شبکه وکلا","Lawyer network")}</h3><p>{t("۶ پروفایل فعال با امتیاز ترکیبی تجربه، تخصص، مهارت و تحصیلات.","6 active profiles scored by experience, specialty, skill and education.")}</p><button onClick={()=>openTool("lawyer")}>{t("مشاهده و انتخاب وکیل","Browse lawyers")}<Ic.chevL size={15}/></button></section>
          <div className="sl-transparency"><Ic.shieldCheck size={17}/><span>{t("انتخاب ابزارها و مسیر هر پاسخ برای کاربر قابل مشاهده است.","Tool selection and answer routes remain visible to the user.")}</span></div>
        </aside>
      </div>
    </div>
  );
};

Object.assign(window,{SmartLawyerView});
if(window.MODULES&&window.MODULES.aiChat){Object.assign(window.MODULES.aiChat,{t:{fa:"وکیل هوشمند",ar:"المحامي الذكي",en:"Smart Lawyer"},s:{fa:"دستیار یکپارچه با دسترسی به ماژول‌های شهداد",ar:"مساعد متكامل مع وصول إلى وحدات شهداد",en:"Integrated assistant with access to Shahdad modules"},View:SmartLawyerView});}