/* ==========================================================================
 * ADMIN NEXT — page-mktorgs.jsx  (จัดการสายการตลาด — CRUD orgs)
 * ========================================================================== */

function MktOrgsPage({ toast }) {
  const [rows,setRows]=useState([]),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [form,setForm]=useState(null),[busy,setBusy]=useState(false),[del,setDel]=useState(null);

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{ const d=await api("/marketing/orgs"); setRows(Array.isArray(d)?d:[]); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} setErr(e.message||"โหลดไม่สำเร็จ"); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(); },[load]);

  const save=async()=>{ setBusy(true);
    try{
      const body={name:form.name,url:form.url,commissionPercent:Number(form.commissionPercent)||0,ownerUsername:form.ownerUsername,ownerPassword:form.ownerPassword,enabled:form.enabled!==false};
      if(form._id){ await api("/marketing/orgs/"+form._id,{method:"PUT",body}); }
      else { await api("/marketing/orgs",{method:"POST",body}); }
      toast("บันทึกแล้ว"); setForm(null); load();
    }catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setBusy(false); } };

  const doDelete=async()=>{ setBusy(true);
    try{ await api("/marketing/orgs/"+del.id,{method:"DELETE"}); toast("ลบแล้ว"); setDel(null); load(); }
    catch(e){ toast(e.message||"ลบไม่สำเร็จ"); } finally{ setBusy(false); } };

  const toggleEnabled=async(r)=>{
    try{ await api("/marketing/orgs/"+r.id,{method:"PUT",body:{enabled:!r.enabled}}); load(); }
    catch(e){ toast(e.message||"ไม่สำเร็จ"); } };

  const copyUrl=(url)=>{ try{navigator.clipboard.writeText(url); toast("คัดลอกแล้ว");}catch{} };

  const newForm=()=>({name:"",url:"",commissionPercent:"0",ownerUsername:"",ownerPassword:"",enabled:true});
  const H=({children,extra=""})=>(<th className={"whitespace-nowrap px-3 py-2.5 text-left text-[13px] font-bold text-fg-2 "+extra}>{children}</th>);

  return (<div className="space-y-3">
    <div className="flex flex-wrap items-center gap-2">
      <button onClick={()=>window.open("/marketing-owner","_blank","noopener")} className="flex h-9 items-center gap-1.5 rounded-lg border border-line bg-surface px-3 text-sm font-medium text-fg-2 hover:bg-sunken"><Ic d={I.login2} size={15}/> เข้าหน้า Login สายการตลาด</button>
      <button onClick={load} className="flex h-9 items-center gap-1.5 rounded-lg border border-line bg-surface px-3 text-sm font-medium text-fg-2 hover:bg-sunken"><Ic d={I.refresh} size={16} cls={loading?"animate-spin":""}/> รีเฟรช</button>
      <button onClick={()=>setForm(newForm())} className="flex h-9 items-center gap-1.5 rounded-lg bg-accent px-3 text-sm font-medium text-accent-fg hover:bg-accent-h"><Ic d={I.plus} size={16}/> เพิ่มสายงาน</button>
      <div className="ml-auto text-xs text-muted tnum">{rows.length} สายงาน</div>
    </div>

    {err ? <HistErr msg={err} onRetry={load}/>
    : (<div className="overflow-hidden rounded-xl border border-line bg-surface shadow-sm"><div className="overflow-x-auto"><table className="w-full min-w-[700px] border-collapse text-sm">
      <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{H({children:"ชื่อ"})}{H({children:"Slug"})}{H({children:"ค่าคอม %",extra:"text-right"})}{H({children:"เจ้าของ"})}{H({children:"สถานะ"})}{H({children:"จัดการ",extra:"text-right pr-4"})}</tr></thead>
      <tbody>
        {loading ? Array.from({length:4}).map((_,i)=>(<tr key={i} className="border-b border-line-soft"><td className="px-3 py-3" colSpan="6"><div className="skel h-5 w-full"/></td></tr>))
        : rows.length===0 ? (<tr><td colSpan="6" className="px-4 py-16 text-center text-sm font-medium text-fg-2">ยังไม่มีสายงาน</td></tr>)
        : rows.map(r=>(<tr key={r.id} className="border-b border-line-soft last:border-0 hover:bg-sunken/50">
          <td className="px-3 py-2.5"><div className="font-medium text-fg">{r.name}</div>{r.tracking_url&&<div className="text-[11px] text-faint truncate max-w-[200px]">{r.tracking_url}</div>}</td>
          <td className="px-3 text-xs text-fg-2 mono">{r.slug}</td>
          <td className="px-3 text-right tnum text-fg-2">{r.commission_percent||0}%</td>
          <td className="px-3 text-xs text-fg-2">{r.owner_username||"-"}</td>
          <td className="px-3"><Badge tone={r.enabled?"success":"danger"}>{r.enabled?"เปิด":"ปิด"}</Badge></td>
          <td className="pr-4"><div className="flex items-center justify-end gap-1">
            {r.tracking_url&&<button title="คัดลอกลิงก์" onClick={()=>copyUrl(r.tracking_url)} className="grid h-7 w-7 place-items-center rounded-lg border border-line text-fg-2 hover:bg-sunken"><Ic d={I.copy} size={14}/></button>}
            <button title={r.enabled?"ปิด":"เปิด"} onClick={()=>toggleEnabled(r)} className={"grid h-7 w-7 place-items-center rounded-lg border border-line hover:bg-sunken "+(r.enabled?"text-success":"text-muted")}><Ic d={I.check} size={14}/></button>
            <button title="แก้ไข" onClick={()=>setForm({_id:r.id,name:r.name,url:r.url||"",commissionPercent:r.commission_percent||0,ownerUsername:r.owner_username||"",ownerPassword:"",enabled:r.enabled})} className="grid h-7 w-7 place-items-center rounded-lg border border-line text-fg-2 hover:bg-sunken"><Ic d={I.edit} size={14}/></button>
            <button title="ลบ" onClick={()=>setDel(r)} className="grid h-7 w-7 place-items-center rounded-lg border border-line text-danger hover:bg-sunken"><Ic d={I.trash} size={14}/></button>
          </div></td>
        </tr>))}
      </tbody>
    </table></div></div>)}

    {form&&(<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 fade-in" onClick={()=>setForm(null)}><div className="w-full max-w-md rounded-xl border border-line bg-surface p-5 shadow-lg pop" onClick={e=>e.stopPropagation()}>
      <h3 className="mb-4 text-base font-semibold">{form._id?"แก้ไขสายงาน":"เพิ่มสายงาน"}</h3>
      {[["ชื่อ","name"],["URL เว็บไซต์","url"],["ค่าคอมมิชชั่น (%)","commissionPercent","number"],["Username เจ้าของ","ownerUsername"],["Password เจ้าของ","ownerPassword","password"]].map(([l,k,t])=>
        <div key={k} className="mb-3"><label className="mb-1 block text-xs font-semibold text-fg-2">{l}</label><input type={t||"text"} value={form[k]||""} onChange={e=>setForm(f=>({...f,[k]:e.target.value}))} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" placeholder={k==="ownerPassword"&&form._id?"(ไม่เปลี่ยน)":""}/></div>)}
      <div className="flex justify-end gap-2 pt-2">
        <button onClick={()=>setForm(null)} className="rounded-lg border border-line px-4 py-2 text-sm font-medium text-fg-2 hover:bg-sunken">ยกเลิก</button>
        <button disabled={busy||!form.name} onClick={save} className="rounded-lg bg-accent px-4 py-2 text-sm font-medium text-accent-fg hover:bg-accent-h disabled:opacity-50">{busy?"กำลังบันทึก…":"บันทึก"}</button>
      </div>
    </div></div>)}

    {del&&<SimpleConfirmModal title="ลบสายงาน" msg={"ลบ \""+(del?.name||"")+"\"?"} onOk={doDelete} onCancel={()=>setDel(null)}/>}
  </div>);
}
