// Process Master setup — tree on left, detail+RACI on right

const ProcessMasterPage = ({ mainProcesses, setMainProcesses, processes, setProcesses, subprocesses, setSubprocesses, positions, departments, divisions, auditLog, setAuditLog, tenant, canEdit }) => {
  const [selected, setSelected] = useState({ type:"sub", id: subprocesses[0]?.id });
  const [tab, setTab] = useState("info");
  const [deleteFor, setDeleteFor] = useState(null);
  const [adding, setAdding] = useState(null);
  const toast = useToast();

  // Edit mode + draft state for the right-side detail panel
  const [isEditing, setIsEditing] = useState(false);
  const [draft, setDraft] = useState(null);

  const audit = (action, reason, who="ธนพร อัศวิน") => {
    setAuditLog(prev => [{ id:"a"+Math.random().toString(36).slice(2,7), scope:"tenant", tenant_id:tenant.id, action, reason, performed_by:who, at: nowStamp() }, ...prev]);
  };

  const handleDelete = (type, id, reason) => {
    if (type === "mp") {
      setMainProcesses(p => p.filter(x=>x.id!==id));
      audit("delete", `ลบ Main Process — ${reason}`);
    }
    if (type === "pr") { setProcesses(p => p.filter(x=>x.id!==id)); audit("delete", `ลบ Process — ${reason}`); }
    if (type === "sub") { setSubprocesses(p => p.filter(x=>x.id!==id)); audit("delete", `ลบ Sub-process — ${reason}`); }
    toast({ kind:"success", msg:"ลบรายการสำเร็จ และบันทึก Audit Log แล้ว" });
    setDeleteFor(null);
  };

  // Build tree
  const tree = useMemo(() => mainProcesses.slice().sort(byOrder).map(mp => ({
    mp,
    processes: processes.filter(p => p.main_process_id === mp.id).slice().sort(byOrder).map(pr => ({
      pr,
      subs: subprocesses.filter(s => s.process_id === pr.id).slice().sort(byOrder),
    })),
  })), [mainProcesses, processes, subprocesses]);

  const selectedSub = selected.type === "sub" ? subprocesses.find(s=>s.id===selected.id) : null;

  // Reset edit mode when selection changes
  useEffect(() => { setIsEditing(false); setDraft(null); }, [selected.id, selected.type]);

  const enterEdit = () => {
    if (!canEdit) return;
    if (selectedSub) { setDraft({ ...selectedSub }); setIsEditing(true); }
  };
  const cancelEdit = () => { setDraft(null); setIsEditing(false); };
  const saveEdit = () => {
    if (!draft) return;
    setSubprocesses(prev => prev.map(s => s.id === draft.id ? draft : s));
    audit("update", `แก้ไข Sub-process — ${draft.name}`);
    toast({ kind:"success", msg:"บันทึกการแก้ไขเรียบร้อย" });
    setIsEditing(false); setDraft(null);
  };

  return (
    <div className="p-6">
      <PageHeader
        title="Process Master"
        subtitle="กำหนด Main Process → Process → Sub-process และผูก RACI ตามผังองค์กร"
        right={canEdit ? <>
          <Button icon="download" variant="secondary" onClick={()=>{
            downloadCsv(`${tenant.tenant_code}_process_master.csv`,
              ["Main Process","Process","Sub-process","Frequency","Due rule","R","A","C","I","Tracking"],
              subprocesses.map(sp => {
                const mp = mainProcesses.find(m=>m.id===sp.main_process_id);
                const pr = processes.find(p=>p.id===sp.process_id);
                return [mp?.name||"", pr?.name||"", sp.name, sp.frequency, sp.due_day,
                  positions.find(p=>p.id===sp.R)?.name||"", positions.find(p=>p.id===sp.A)?.name||"",
                  sp.C.map(id=>positions.find(p=>p.id===id)?.name).filter(Boolean).join(" / "),
                  sp.I.map(id=>positions.find(p=>p.id===id)?.name).filter(Boolean).join(" / "),
                  sp.track_status === false ? "ปิด" : "เปิด"];
              }));
          }}>Export</Button>
          <Button icon="plus" onClick={()=>setAdding({type:"mp"})}>เพิ่ม Main Process</Button>
        </> : <>
          <Badge color="slate" icon="eye">โหมดอ่านอย่างเดียว</Badge>
          <Button icon="download" variant="secondary" onClick={()=>{
            downloadCsv(`${tenant.tenant_code}_process_master.csv`,
              ["Main Process","Process","Sub-process","Frequency","Due rule"],
              subprocesses.map(sp => {
                const mp = mainProcesses.find(m=>m.id===sp.main_process_id);
                const pr = processes.find(p=>p.id===sp.process_id);
                return [mp?.name||"", pr?.name||"", sp.name, sp.frequency, sp.due_day];
              }));
          }}>Export</Button>
        </>}/>

      {!canEdit && (
        <div className="mb-4 px-4 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-700 text-[12.5px] flex items-center gap-2.5">
          <Icon name="shield" size={14} className="text-slate-500"/>
          <span>คุณกำลังดูข้อมูลแบบ <strong>อ่านอย่างเดียว</strong> · เฉพาะผู้ใช้สิทธิ์ <strong>Company Admin</strong> เท่านั้นที่สามารถแก้ไข Master Data ได้ ติดต่อ Admin ของบริษัทหากต้องการเปลี่ยนแปลง</span>
        </div>
      )}

      <div className="grid grid-cols-12 gap-4">
        {/* Tree */}
        <div className="col-span-12 lg:col-span-4 bg-white rounded-2xl border border-ink-100 overflow-hidden">
          <div className="px-3 py-3 border-b border-ink-100 flex items-center gap-2">
            <Icon name="workflow" size={14} className="text-ink-500"/>
            <div className="text-[13px] font-semibold text-ink-900">Process Tree</div>
            <div className="ml-auto text-[11px] text-ink-500">{mainProcesses.length} · {processes.length} · {subprocesses.length}</div>
          </div>
          <div className="max-h-[640px] overflow-y-auto thin-scroll p-1.5">
            {tree.map(({mp, processes:prs}) => (
              <TreeNode key={mp.id}
                label={mp.name} icon="workflow" defaultOpen
                tone="indigo" selected={selected.type==="mp" && selected.id===mp.id}
                onClick={()=>{ setSelected({type:"mp", id:mp.id}); setTab("info"); }}
                actions={canEdit ? <TreeActions onAdd={()=>setAdding({type:"pr", parent:mp.id})} onDelete={()=>setDeleteFor({type:"mp", id:mp.id, name:mp.name})}/> : null}>
                {prs.map(({pr, subs}) => (
                  <TreeNode key={pr.id}
                    label={pr.name} icon="layers" tone="violet" defaultOpen
                    selected={selected.type==="pr" && selected.id===pr.id}
                    onClick={()=>{ setSelected({type:"pr", id:pr.id}); setTab("info"); }}
                    actions={canEdit ? <TreeActions onAdd={()=>setAdding({type:"sub", parent:pr.id, mp:mp.id})} onDelete={()=>setDeleteFor({type:"pr", id:pr.id, name:pr.name})}/> : null}>
                    {subs.map(s => {
                      const R = positions.find(p=>p.id===s.R);
                      return (
                        <TreeLeaf key={s.id}
                          selected={selected.type==="sub" && selected.id===s.id}
                          onClick={()=>{ setSelected({type:"sub", id:s.id}); setTab("info"); }}
                          onDelete={canEdit ? ()=>setDeleteFor({type:"sub", id:s.id, name:s.name}) : null}
                          label={s.name}
                          sub={`${s.frequency} · R: ${R?.name || "—"}`}/>
                      );
                    })}
                  </TreeNode>
                ))}
              </TreeNode>
            ))}
          </div>
        </div>

        {/* Detail */}
        <div className="col-span-12 lg:col-span-8">
          {selectedSub ? (
            <div className="bg-white rounded-2xl border border-ink-100 overflow-hidden">
              <div className="px-5 py-4 border-b border-ink-100">
                <div className="flex items-start gap-3 justify-between">
                  <div className="flex-1 min-w-0">
                    <div className="text-[10.5px] uppercase tracking-wider text-ink-400 flex items-center gap-2">
                      Sub-process
                      {isEditing && <Badge color="amber" icon="edit">กำลังแก้ไข</Badge>}
                    </div>
                    <div className="text-[18px] font-bold text-ink-900 mt-0.5">{(isEditing?draft?.name:selectedSub.name) || selectedSub.name}</div>
                    <div className="text-[12px] text-ink-500 mt-0.5">
                      {mainProcesses.find(m=>m.id===selectedSub.main_process_id)?.name} · {processes.find(p=>p.id===selectedSub.process_id)?.name}
                    </div>
                  </div>
                  {/* Edit-mode toolbar */}
                  <div className="flex items-center gap-2 shrink-0">
                    {!isEditing && canEdit && <Button icon="edit" variant="secondary" size="sm" onClick={enterEdit}>แก้ไข</Button>}
                    {!isEditing && !canEdit && <Badge color="slate" icon="eye">อ่านอย่างเดียว</Badge>}
                    {isEditing && <>
                      <Button variant="secondary" size="sm" onClick={cancelEdit} icon="x">ยกเลิก</Button>
                      <Button variant="primary" size="sm" onClick={saveEdit} icon="check">ยืนยันการแก้ไข</Button>
                    </>}
                  </div>
                </div>
                <div className="mt-3 flex items-center gap-1 border-b border-ink-100">
                  {[
                    { v:"info", l:"ข้อมูลกระบวนการ" },
                    { v:"raci", l:"RACI Assignment" },
                    { v:"history", l:"ประวัติการแก้ไข" },
                  ].map(t => (
                    <button key={t.v} onClick={()=>setTab(t.v)}
                      className={`relative px-3 py-2 text-[12.5px] font-medium ${tab===t.v?"text-ink-900":"text-ink-500 hover:text-ink-800"}`}>
                      {t.l}{tab===t.v && <span className="absolute -bottom-px left-0 right-0 h-0.5 bg-brand-600"/>}
                    </button>
                  ))}
                </div>
              </div>
              <div className={`p-5 ${isEditing?"bg-amber-50/30 border-2 border-amber-200 m-1 rounded-xl":""}`}>
                {tab === "info" && <SubInfoTab sub={isEditing ? draft : selectedSub}
                  onChange={(patch) => isEditing ? setDraft(d => ({ ...d, ...patch })) : null}
                  readOnly={!isEditing}/>}
                {tab === "raci" && <SubRaciTab sub={isEditing ? draft : selectedSub} positions={positions} departments={departments} divisions={divisions}
                  onChange={(patch)=> isEditing ? setDraft(d => ({ ...d, ...patch })) : null}
                  readOnly={!isEditing}/>}
                {tab === "history" && <SubHistoryTab sub={selectedSub} auditLog={auditLog}/>}
              </div>
            </div>
          ) : (
            <div className="bg-white rounded-2xl border border-ink-100 p-6 bg-dot">
              <EmptyState icon="workflow" title="เลือก Sub-process จากด้านซ้าย" subtitle="หรือเพิ่มใหม่จากปุ่มในแถบบนสุด"/>
            </div>
          )}
        </div>
      </div>

      {/* Delete reason modal */}
      <ReasonModal open={!!deleteFor} onClose={()=>setDeleteFor(null)}
        onConfirm={(r)=>handleDelete(deleteFor.type, deleteFor.id, r)}
        title="ยืนยันการลบ" subtitle={deleteFor?.name}
        confirmLabel="ลบรายการ" placeholder="โปรดระบุเหตุผลในการลบ จะถูกบันทึก Audit Log"/>

      <AddProcessModal adding={adding} onClose={()=>setAdding(null)}
        onAdd={(payload)=>{
          if (adding.type === "mp") {
            setMainProcesses(p => [...p, { id:"mp"+Date.now(), name:payload.name, division_id:divisions[0]?.id, display_order:p.length+1, order:p.length+1, status:"active" }]);
          } else if (adding.type === "pr") {
            const siblings = processes.filter(x => x.main_process_id === adding.parent);
            setProcesses(p => [...p, { id:"pr"+Date.now(), main_process_id:adding.parent, name:payload.name, display_order:siblings.length+1, order:siblings.length+1 }]);
          } else if (adding.type === "sub") {
            const siblings = subprocesses.filter(x => x.process_id === adding.parent);
            setSubprocesses(p => [...p, { id:"sp"+Date.now(), main_process_id:adding.mp, process_id:adding.parent, name:payload.name, frequency:"daily", due_day:"ทุกวันทำการ", R:positions[0]?.id, A:positions[1]?.id, C:[], I:[], display_order:siblings.length+1 }]);
          }
          audit("create", `สร้าง ${adding.type==="mp"?"Main Process":adding.type==="pr"?"Process":"Sub-process"} — ${payload.name}`);
          toast({ kind:"success", msg:"เพิ่มรายการสำเร็จ" });
          setAdding(null);
        }}/>
    </div>
  );
};

// --- Tree components ---
const TreeNode = ({ label, icon, tone, selected, onClick, defaultOpen=false, actions, children }) => {
  const [open, setOpen] = useState(defaultOpen);
  const tones = { indigo:"text-indigo-600", violet:"text-violet-600", emerald:"text-emerald-600" };
  return (
    <div>
      <div className={`group flex items-center gap-1 px-2 py-1.5 rounded-md transition ${selected?"bg-brand-50":"hover:bg-ink-50"}`}>
        <button onClick={()=>setOpen(v=>!v)} className="w-5 h-5 flex items-center justify-center text-ink-400 hover:text-ink-700">
          <Icon name={open?"chevronDown":"chevronRight"} size={12}/>
        </button>
        <Icon name={icon} size={13} className={tones[tone] || "text-ink-500"}/>
        <button onClick={onClick} className={`flex-1 text-left text-[12.5px] font-medium truncate ${selected?"text-brand-700":"text-ink-800"}`}>{label}</button>
        <div className="opacity-0 group-hover:opacity-100">{actions}</div>
      </div>
      {open && <div className="pl-5">{children}</div>}
    </div>
  );
};
const TreeLeaf = ({ label, sub, selected, onClick, onDelete }) => (
  <div className={`group flex items-center gap-2 px-2 py-1.5 rounded-md transition ml-1 ${selected?"bg-brand-50":"hover:bg-ink-50"}`}>
    <span className="w-1.5 h-1.5 rounded-full bg-ink-300 ml-1.5"/>
    <button onClick={onClick} className="flex-1 text-left min-w-0">
      <div className={`text-[12px] truncate ${selected?"text-brand-700 font-semibold":"text-ink-800"}`}>{label}</div>
      <div className="text-[10.5px] text-ink-500 truncate">{sub}</div>
    </button>
    <button onClick={onDelete} className="opacity-0 group-hover:opacity-100 p-1 text-rose-500 hover:bg-rose-50 rounded"><Icon name="trash" size={11}/></button>
  </div>
);
const TreeActions = ({ onAdd, onDelete }) => (
  <div className="flex items-center gap-0.5">
    {onAdd && <button onClick={(e)=>{e.stopPropagation(); onAdd();}} className="p-1 text-ink-500 hover:bg-white rounded"><Icon name="plus" size={11}/></button>}
    {onDelete && <button onClick={(e)=>{e.stopPropagation(); onDelete();}} className="p-1 text-rose-500 hover:bg-rose-50 rounded"><Icon name="trash" size={11}/></button>}
  </div>
);

// Sub-process info tab — controlled inputs for frequency / due day rule
const SubInfoTab = ({ sub, onChange, readOnly }) => {
  const FREQ_OPTIONS = [
    { v:"daily",     l:"Daily · รายวัน" },
    { v:"weekly",    l:"Weekly · รายสัปดาห์" },
    { v:"monthly",   l:"Monthly · รายเดือน" },
    { v:"quarterly", l:"Quarterly · รายไตรมาส" },
    { v:"yearly",    l:"Yearly · รายปี" },
    { v:"ad-hoc",    l:"Ad-hoc · ตามคำขอ" },
  ];
  const DOW = [
    { v:"จันทร์", n:1 }, { v:"อังคาร", n:2 }, { v:"พุธ", n:3 },
    { v:"พฤหัส", n:4 }, { v:"ศุกร์", n:5 }, { v:"เสาร์", n:6 }, { v:"อาทิตย์", n:0 },
  ];
  const set = (patch) => onChange?.(patch);
  return (
    <div className="grid grid-cols-2 gap-4">
      <Field label="ชื่อ Sub-process" required>
        <Input value={sub.name} onChange={e=>set({ name: e.target.value })} disabled={readOnly}/>
      </Field>
      <Field label="Frequency · ความถี่" required>
        <Select value={sub.frequency} onChange={e=>set({ frequency: e.target.value, due_day: presetDueDay(e.target.value) })} disabled={readOnly}>
          {FREQ_OPTIONS.map(f=><option key={f.v} value={f.v}>{f.l}</option>)}
        </Select>
      </Field>

      {/* Frequency-specific helper picker */}
      {sub.frequency === "daily" && (
        <Field label="Due day / กำหนดส่ง" className="col-span-2">
          <Select value={sub.due_day} onChange={e=>set({ due_day: e.target.value })} disabled={readOnly}>
            <option>ทุกวันทำการ</option>
            <option>ทุกวัน (รวมเสาร์-อาทิตย์)</option>
            <option>ภายในวันถัดไป</option>
          </Select>
        </Field>
      )}
      {sub.frequency === "weekly" && (
        <Field label="Due day / กำหนดส่ง" hint="เลือกวันของสัปดาห์" className="col-span-2">
          <div className="flex items-center gap-1.5 flex-wrap">
            {DOW.map(d => {
              const cur = (sub.due_day||"").includes(d.v);
              return (
                <button key={d.v} disabled={readOnly} onClick={()=>set({ due_day: `ทุกวัน${d.v}` })}
                  className={`h-8 px-3 rounded-md text-[12px] font-medium border transition ${cur?"bg-brand-600 border-brand-600 text-white":"bg-white border-ink-200 text-ink-700 hover:bg-ink-50"} ${readOnly?"opacity-60 cursor-not-allowed":""}`}>
                  {d.v}
                </button>
              );
            })}
          </div>
        </Field>
      )}
      {sub.frequency === "monthly" && (
        <Field label="Due day / กำหนดส่ง" hint="เลือกวันที่ของเดือน (1–31) หรือวันสุดท้ายของเดือน" className="col-span-2">
          <div className="flex items-center gap-3 flex-wrap">
            <div className="flex items-center gap-1 flex-wrap">
              {[1,5,7,10,15,20,25,28,31].map(n => {
                const cur = (sub.due_day||"").match(/\d+/)?.[0] === String(n) && !(sub.due_day||"").includes("สุดท้าย");
                return (
                  <button key={n} disabled={readOnly} onClick={()=>set({ due_day: `วันที่ ${n}` })}
                    className={`w-9 h-8 rounded-md text-[12px] font-mono font-semibold border transition ${cur?"bg-brand-600 border-brand-600 text-white":"bg-white border-ink-200 text-ink-700 hover:bg-ink-50"} ${readOnly?"opacity-60 cursor-not-allowed":""}`}>
                    {n}
                  </button>
                );
              })}
              <button disabled={readOnly} onClick={()=>set({ due_day: "วันทำการสุดท้ายของเดือน" })}
                className={`h-8 px-2.5 rounded-md text-[12px] font-medium border transition ${(sub.due_day||"").includes("สุดท้าย")?"bg-brand-600 border-brand-600 text-white":"bg-white border-ink-200 text-ink-700 hover:bg-ink-50"} ${readOnly?"opacity-60 cursor-not-allowed":""}`}>
                วันทำการสุดท้าย
              </button>
            </div>
            <div className="text-[11px] text-ink-500">หรือกรอกเอง:</div>
            <Input className="!w-44" value={sub.due_day} onChange={e=>set({ due_day: e.target.value })} disabled={readOnly} placeholder="เช่น วันที่ 28 หรือ Q-end"/>
          </div>
        </Field>
      )}
      {sub.frequency === "quarterly" && (
        <Field label="Due day / กำหนดส่ง" className="col-span-2">
          <Select value={sub.due_day} onChange={e=>set({ due_day: e.target.value })} disabled={readOnly}>
            <option>สิ้นไตรมาส</option>
            <option>15 วันของเดือนสิ้นไตรมาส</option>
            <option>30 วันหลังสิ้นไตรมาส</option>
          </Select>
        </Field>
      )}
      {sub.frequency === "yearly" && (
        <Field label="Due day / กำหนดส่ง" className="col-span-2">
          <Input value={sub.due_day} onChange={e=>set({ due_day: e.target.value })} disabled={readOnly} placeholder="เช่น วันที่ 31 มี.ค. ของทุกปี"/>
        </Field>
      )}
      {sub.frequency === "ad-hoc" && (
        <Field label="Due day / กำหนดส่ง" className="col-span-2">
          <Input value={sub.due_day} onChange={e=>set({ due_day: e.target.value })} disabled={readOnly} placeholder="ตามคำขอ / SLA ที่ตกลง"/>
        </Field>
      )}

      <Field label="Status">
        <Select value={sub.status || "active"} onChange={e=>set({ status: e.target.value })} disabled={readOnly}>
          <option value="active">Active</option>
          <option value="inactive">Inactive</option>
        </Select>
      </Field>
      <Field label="ลำดับแสดงผล">
        <Input type="number" value={sub.display_order ?? 1} onChange={e=>set({ display_order: +e.target.value })} disabled={readOnly}/>
      </Field>
      <Field label="Description" className="col-span-2">
        <Textarea rows={3} value={sub.description || ""} onChange={e=>set({ description: e.target.value })} disabled={readOnly} placeholder="รายละเอียดของกระบวนการ"/>
      </Field>

      {/* Status tracking toggle */}
      <div className="col-span-2 rounded-xl border border-ink-100 bg-white p-4">
        <div className="flex items-start gap-3">
          <button type="button" disabled={readOnly}
            onClick={()=>set({ track_status: !(sub.track_status !== false) })}
            className={`relative w-10 h-5 rounded-full transition shrink-0 mt-0.5 ${(sub.track_status !== false)?"bg-emerald-500":"bg-ink-300"} ${readOnly?"opacity-60 cursor-not-allowed":""}`}>
            <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${(sub.track_status !== false)?"translate-x-5":""}`}/>
          </button>
          <div className="flex-1">
            <div className="flex items-center gap-2">
              <div className="text-[13px] font-semibold text-ink-900">ติดตามสถานะใน RACI Matrix</div>
              {(sub.track_status !== false)
                ? <Badge color="emerald" icon="checkCircle">เปิดติดตาม</Badge>
                : <Badge color="slate" icon="eye">ดูอย่างเดียว</Badge>}
            </div>
            <div className="text-[11.5px] text-ink-500 mt-1 leading-relaxed">
              {(sub.track_status !== false)
                ? "งานนี้จะมี Workflow P → A → C → S ในหน้า RACI Matrix · ผู้รับผิดชอบ R และผู้ตรวจสอบ A ต้องอัปเดตสถานะรายงวด"
                : "งานนี้เป็นข้อมูลอ้างอิงเท่านั้น (เช่น งานทั่วไปที่ตรวจสอบไม่ได้) ในหน้า RACI Matrix จะแสดงเป็น \"ดูอย่างเดียว\" ไม่มีปุ่มอัปเดตสถานะ"}
            </div>
          </div>
        </div>
      </div>

      <div className="col-span-2 mt-1 px-3 py-2.5 rounded-lg bg-emerald-50 border border-emerald-100 text-emerald-800 text-[11.5px] flex items-start gap-2">
        <Icon name="checkCircle" size={13} className="mt-0.5"/>
        <span>{readOnly ? "ค่าปัจจุบัน: " : "จะบันทึกข้อมูลกระบวนการได้เมื่อกดยืนยัน · ค่าปัจจุบัน: "}<strong className="font-semibold">{sub.frequency}</strong> · <strong className="font-semibold">{sub.due_day}</strong></span>
      </div>
    </div>
  );
};

const presetDueDay = (freq) => ({
  daily: "ทุกวันทำการ",
  weekly: "ทุกวันศุกร์",
  monthly: "วันที่ 15",
  quarterly: "สิ้นไตรมาส",
  yearly: "วันที่ 31 มี.ค.",
  "ad-hoc": "ตามคำขอ",
}[freq] || "—");

// RACI tab - allows changing R, A, C[], I[]
const SubRaciTab = ({ sub, positions, departments, divisions, onChange, readOnly }) => {
  const [picker, setPicker] = useState(null); // {role}
  const R = positions.find(p=>p.id===sub.R);
  const A = positions.find(p=>p.id===sub.A);
  const Cs = sub.C.map(id => positions.find(p=>p.id===id)).filter(Boolean);
  const Is = sub.I.map(id => positions.find(p=>p.id===id)).filter(Boolean);
  const isSame = R && A && R.id === A.id;

  const handlePick = (role, posId) => {
    if (readOnly) return;
    if (role === "R") onChange({ R: posId });
    if (role === "A") onChange({ A: posId });
    if (role === "C") onChange({ C: sub.C.includes(posId) ? sub.C.filter(x=>x!==posId) : [...sub.C, posId] });
    if (role === "I") onChange({ I: sub.I.includes(posId) ? sub.I.filter(x=>x!==posId) : [...sub.I, posId] });
  };

  return (
    <div className="grid grid-cols-2 gap-4">
      {/* R */}
      <div className="rounded-xl border border-blue-100 bg-blue-50/40 p-3">
        <div className="flex items-center gap-2 mb-2"><RaciBadge kind="R"/><div className="text-[12px] font-semibold text-blue-800">Responsible (ผู้จัดทำ)</div><span className="ml-auto text-[10px] text-blue-700 bg-blue-100 px-1.5 py-0.5 rounded">One only</span></div>
        {R ? <PositionChip pos={R} onClear={readOnly?null:()=>onChange({R:null})}/> : (readOnly ? <span className="text-[11.5px] text-ink-400 italic">— ยังไม่ได้กำหนด —</span> : <button onClick={()=>setPicker({role:"R"})} className="w-full h-9 rounded-lg border border-dashed border-blue-300 text-[12px] text-blue-700 hover:bg-blue-50">+ เลือกตำแหน่ง</button>)}
        {!readOnly && <button onClick={()=>setPicker({role:"R"})} className="mt-2 text-[11px] text-blue-700 hover:underline">เปลี่ยนตำแหน่ง</button>}
      </div>
      {/* A */}
      <div className="rounded-xl border border-violet-100 bg-violet-50/40 p-3">
        <div className="flex items-center gap-2 mb-2"><RaciBadge kind="A"/><div className="text-[12px] font-semibold text-violet-800">Accountable (ผู้ตรวจสอบ)</div><span className="ml-auto text-[10px] text-violet-700 bg-violet-100 px-1.5 py-0.5 rounded">One only</span></div>
        {A ? <PositionChip pos={A} onClear={readOnly?null:()=>onChange({A:null})}/> : (readOnly ? <span className="text-[11.5px] text-ink-400 italic">— ยังไม่ได้กำหนด —</span> : <button onClick={()=>setPicker({role:"A"})} className="w-full h-9 rounded-lg border border-dashed border-violet-300 text-[12px] text-violet-700 hover:bg-violet-50">+ เลือกตำแหน่ง</button>)}
        {!readOnly && <button onClick={()=>setPicker({role:"A"})} className="mt-2 text-[11px] text-violet-700 hover:underline">เปลี่ยนตำแหน่ง</button>}
      </div>
      {/* C */}
      <div className="rounded-xl border border-amber-100 bg-amber-50/40 p-3 col-span-2">
        <div className="flex items-center gap-2 mb-2"><RaciBadge kind="C"/><div className="text-[12px] font-semibold text-amber-800">Consulted (ผู้ให้ข้อมูล)</div><span className="ml-auto text-[10px] text-amber-700 bg-amber-100 px-1.5 py-0.5 rounded">หลายตำแหน่งได้</span></div>
        <div className="flex flex-wrap gap-2">
          {Cs.map(p => <PositionChip key={p.id} pos={p} onClear={readOnly?null:()=>handlePick("C", p.id)}/>)}
          {Cs.length === 0 && readOnly && <span className="text-[11.5px] text-ink-400 italic">— ไม่มี —</span>}
          {!readOnly && <button onClick={()=>setPicker({role:"C"})} className="h-7 px-2.5 rounded-lg border border-dashed border-amber-300 text-[12px] text-amber-700 hover:bg-amber-50 flex items-center gap-1"><Icon name="plus" size={11}/>เพิ่มตำแหน่ง</button>}
        </div>
      </div>
      {/* I */}
      <div className="rounded-xl border border-emerald-100 bg-emerald-50/40 p-3 col-span-2">
        <div className="flex items-center gap-2 mb-2"><RaciBadge kind="I"/><div className="text-[12px] font-semibold text-emerald-800">Informed (ผู้รับแจ้งข้อมูล)</div><span className="ml-auto text-[10px] text-emerald-700 bg-emerald-100 px-1.5 py-0.5 rounded">หลายตำแหน่งได้</span></div>
        <div className="flex flex-wrap gap-2">
          {Is.map(p => <PositionChip key={p.id} pos={p} onClear={readOnly?null:()=>handlePick("I", p.id)}/>)}
          {Is.length === 0 && readOnly && <span className="text-[11.5px] text-ink-400 italic">— ไม่มี —</span>}
          {!readOnly && <button onClick={()=>setPicker({role:"I"})} className="h-7 px-2.5 rounded-lg border border-dashed border-emerald-300 text-[12px] text-emerald-700 hover:bg-emerald-50 flex items-center gap-1"><Icon name="plus" size={11}/>เพิ่มตำแหน่ง</button>}
        </div>
      </div>

      {/* Validations */}
      <div className="col-span-2 space-y-2">
        {!R && <ValidationRow tone="rose" text="R is missing — โปรดเลือกผู้รับผิดชอบหลัก (R)"/>}
        {!A && <ValidationRow tone="rose" text="A is missing — โปรดเลือกผู้ตรวจสอบ (A)"/>}
        {isSame && <ValidationRow tone="amber" text="R และ A เป็นตำแหน่งเดียวกัน — แนะนำให้แยกบทบาทเพื่อการตรวจสอบที่ดี"/>}
        {R && A && !isSame && <ValidationRow tone="emerald" text="RACI assignment ครบถ้วน พร้อมใช้งาน"/>}
      </div>

      <PositionPickerModal open={!!picker} role={picker?.role} onClose={()=>setPicker(null)}
        positions={positions} departments={departments} divisions={divisions}
        selectedIds={
          picker?.role === "R" ? (sub.R?[sub.R]:[]) :
          picker?.role === "A" ? (sub.A?[sub.A]:[]) :
          picker?.role === "C" ? sub.C : sub.I
        }
        multi={picker?.role === "C" || picker?.role === "I"}
        onPick={(id) => { handlePick(picker.role, id); if (picker.role==="R"||picker.role==="A") setPicker(null); }}
      />
    </div>
  );
};

const ValidationRow = ({ tone, text }) => {
  const tones = { rose:"bg-rose-50 text-rose-700 border-rose-200", amber:"bg-amber-50 text-amber-700 border-amber-200", emerald:"bg-emerald-50 text-emerald-700 border-emerald-200" };
  const ic = tone === "emerald" ? "checkCircle" : "alert";
  return <div className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-[12px] ${tones[tone]}`}><Icon name={ic} size={13}/>{text}</div>;
};

const PositionChip = ({ pos, onClear }) => {
  const dept = byId(DEPARTMENTS, pos.department_id);
  return (
    <span className="inline-flex items-center gap-1.5 px-2 py-1 bg-white border border-ink-200 rounded-lg text-[11.5px] shadow-sm">
      <span className="font-medium text-ink-900">{pos.name}</span>
      <span className="text-ink-500">·</span><span className="text-ink-600">{dept?.name}</span>
      {onClear && <button onClick={onClear} className="ml-1 text-ink-400 hover:text-rose-500"><Icon name="x" size={11}/></button>}
    </span>
  );
};

const PositionPickerModal = ({ open, onClose, role, positions, departments, divisions, selectedIds, multi, onPick }) => {
  const [q, setQ] = useState("");
  useEffect(() => { if (open) setQ(""); }, [open]);
  const grouped = useMemo(() => {
    const filtered = positions.filter(p => !q || p.name.toLowerCase().includes(q.toLowerCase()) || departments.find(d=>d.id===p.department_id)?.name.toLowerCase().includes(q.toLowerCase()));
    const out = {};
    filtered.forEach(p => {
      const d = departments.find(x=>x.id===p.department_id); if (!d) return;
      const div = divisions.find(x=>x.id===d.division_id); if (!div) return;
      const key = `${div.name} › ${d.name}`;
      if (!out[key]) out[key] = [];
      out[key].push(p);
    });
    return out;
  }, [positions, departments, divisions, q]);
  return (
    <Modal open={open} onClose={onClose} title={`เลือกตำแหน่ง — ${role}`} subtitle={multi ? "เลือกได้หลายตำแหน่ง" : "เลือกได้ครั้งละ 1 ตำแหน่ง"} width={560}
      footer={<Button onClick={onClose}>เสร็จสิ้น</Button>}>
      <div className="relative mb-3">
        <Icon name="search" size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-400"/>
        <Input value={q} onChange={e=>setQ(e.target.value)} placeholder="ค้นหา…" className="pl-9"/>
      </div>
      <div className="max-h-[400px] overflow-y-auto thin-scroll space-y-3">
        {Object.entries(grouped).map(([k, ps]) => (
          <div key={k}>
            <div className="text-[10.5px] uppercase tracking-wider text-ink-400 font-semibold mb-1">{k}</div>
            <div className="grid grid-cols-2 gap-1.5">
              {ps.map(p => {
                const sel = selectedIds.includes(p.id);
                return (
                  <button key={p.id} onClick={()=>onPick(p.id)} className={`flex items-center gap-2 px-2 py-1.5 rounded-md border text-left transition ${sel?"bg-brand-50 border-brand-300":"bg-white border-ink-200 hover:bg-ink-50"}`}>
                    {multi && <Checkbox checked={sel} onChange={()=>{}}/>}
                    <div className="min-w-0 flex-1">
                      <div className="text-[12px] font-medium text-ink-900 truncate">{p.name}</div>
                      <div className="text-[10px] text-ink-500 font-mono">{p.level}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </Modal>
  );
};

const SubHistoryTab = ({ sub, auditLog }) => {
  const rel = auditLog.filter(a => (a.reason||"").includes(sub.name));
  if (rel.length === 0) return <EmptyState icon="history" title="ยังไม่มีการเปลี่ยนแปลง"/>;
  return (
    <div className="space-y-2">
      {rel.map(a => (
        <div key={a.id} className="border border-ink-100 rounded-lg p-3 flex items-start gap-3">
          <Icon name="history" size={14} className="text-ink-400 mt-0.5"/>
          <div className="flex-1">
            <div className="text-[12.5px] text-ink-900">{a.reason}</div>
            <div className="text-[11px] text-ink-500 mt-0.5">โดย {a.performed_by} · <span className="font-mono">{a.at}</span></div>
          </div>
          <Badge color="indigo">{a.action}</Badge>
        </div>
      ))}
    </div>
  );
};

const AddProcessModal = ({ adding, onClose, onAdd }) => {
  const [name, setName] = useState("");
  useEffect(() => { if (adding) setName(""); }, [adding]);
  if (!adding) return null;
  const t = adding.type === "mp" ? "Main Process" : adding.type === "pr" ? "Process" : "Sub-process";
  return (
    <Modal open onClose={onClose} title={`เพิ่ม ${t} ใหม่`} width={480}
      footer={<>
        <Button variant="secondary" onClick={onClose}>ยกเลิก</Button>
        <Button disabled={!name.trim()} onClick={()=>onAdd({name:name.trim()})}>เพิ่ม</Button>
      </>}>
      <Field label={`ชื่อ ${t}`} required>
        <Input value={name} onChange={e=>setName(e.target.value)} autoFocus placeholder={`เช่น ${adding.type==="mp"?"Finance & Accounting":"Accounts Payable"}`}/>
      </Field>
    </Modal>
  );
};

Object.assign(window, { ProcessMasterPage });
const byOrder = (a, b) => (a.display_order ?? a.order ?? 999) - (b.display_order ?? b.order ?? 999);
window.byOrder = byOrder;
