/* ==========================================================================
 * ADMIN NEXT — page-promo.jsx  (จัดการโปรโมชั่น)
 * ========================================================================== */
const PROMO_CATS=["slot","casino","sport","fish","lotto","poker","esport","keno"];

function PromoPage({ toast }) {
  const [rows,setRows]=useState([]),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [editing,setEditing]=useState(null);
  const [busy,setBusy]=useState(false);

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

  const toggle=async(p)=>{ const next=!p.is_active;
    try{ await api("/promotions/"+p.id+"/toggle",{method:"POST",body:{isActive:next}}); setRows(rs=>rs.map(r=>r.id===p.id?{...r,is_active:next}:r)); toast(next?"เปิดโปรโมชั่นแล้ว":"ปิดโปรโมชั่นแล้ว"); }catch(e){ toast(e.message||"ไม่สำเร็จ"); } };

  const del=async(p)=>{ if(!window.confirm("ลบโปรโมชั่น \""+p.name+"\" ถาวร?"))return; setBusy(true);
    try{ await api("/promotions/"+p.id,{method:"DELETE"}); toast("ลบโปรโมชั่นแล้ว"); load(); }catch(e){ toast(e.message||"ไม่สำเร็จ"); }finally{ setBusy(false); } };

  const saved=()=>{ setEditing(null); load(); };

  if(editing!==null) return <PromoForm item={editing==="new"?null:editing} onBack={()=>setEditing(null)} onDone={saved} toast={toast}/>;

  if(err) return <HistErr msg={err} onRetry={load}/>;

  const turnLabel=(p)=>{
    const factor=Number(p.turnover_factor||0);
    if(factor>0) return factor+"x";
    if(Number(p.turnover_amount||0)>0) return baht(p.turnover_amount);
    return Number(p.turnover_multiplier||1)+"x";
  };

  return (<div className="space-y-3">
    <div className="flex flex-wrap items-center gap-2">
      <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={()=>setEditing("new")} className="flex h-9 items-center gap-1.5 rounded-lg bg-accent px-3.5 text-sm font-semibold text-accent-fg shadow-sm hover:bg-accent-h"><Ic d={I.plus} size={17} sw={2}/> สร้างโปรโมชั่น</button>
      <span className="ml-auto text-xs text-muted tnum">{rows.length} รายการ</span>
    </div>
    {loading ? <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">{Array.from({length:6}).map((_,i)=><div key={i} className="skel h-44 w-full"/>)}</div>
    : rows.length===0 ? <div className="rounded-xl border border-dashed border-line py-16 text-center text-sm text-muted">ยังไม่มีโปรโมชั่น</div>
    : <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">{rows.map(p=>(
      <article key={p.id} className={"rounded-xl border border-line bg-surface p-4 shadow-sm transition-opacity"+(p.is_active?"":" opacity-60")}>
        <div className="flex items-start gap-3">
          {p.image_url ? <img src={p.image_url} className="h-14 w-14 shrink-0 rounded-lg object-cover bg-sunken" onError={e=>{e.target.style.display="none"}}/> : <div className="grid h-14 w-14 shrink-0 place-items-center rounded-lg bg-sunken"><Ic d={I.gift||I.star||I.grid} size={22} cls="text-faint"/></div>}
          <div className="min-w-0 flex-1">
            <div className="flex items-center gap-2"><span className="truncate text-sm font-semibold">{p.name||"-"}</span><Badge tone={p.is_active?"success":"danger"}>{p.is_active?"เปิด":"ปิด"}</Badge></div>
            <div className="mt-0.5 mono text-xs text-muted">{p.code||"-"}</div>
          </div>
        </div>
        <div className="mt-3 grid grid-cols-3 gap-2 text-center text-[11px]">
          <div className="rounded-lg bg-sunken px-2 py-1.5"><div className="text-faint">โบนัส</div><div className="mt-0.5 font-semibold tnum">{p.bonus_type==="percent"?(Number(p.bonus_value||0)+"%"):baht(p.bonus_value||0)}</div></div>
          <div className="rounded-lg bg-sunken px-2 py-1.5"><div className="text-faint">เทิร์น</div><div className="mt-0.5 font-semibold tnum">{turnLabel(p)}</div></div>
          <div className="rounded-lg bg-sunken px-2 py-1.5"><div className="text-faint">ลำดับ</div><div className="mt-0.5 font-semibold tnum">{Number(p.sort_order||0)}</div></div>
        </div>
        <div className="mt-3 flex items-center gap-1.5">
          <button onClick={()=>toggle(p)} className={"h-7 rounded-full border px-2.5 text-[11px] font-medium transition-colors "+(p.is_active?"text-white border-transparent":"border-line text-fg-2 hover:bg-sunken")} style={p.is_active?{background:"var(--success)"}:{}}>{p.is_active?"เปิด":"ปิด"}</button>
          <div className="flex-1"/>
          <button onClick={()=>setEditing(p)} className="grid h-7 w-7 place-items-center rounded-lg border border-line text-fg-2 hover:bg-sunken" title="แก้ไข"><Ic d={I.edit||I.pen} size={14}/></button>
          <button disabled={busy} onClick={()=>del(p)} className="grid h-7 w-7 place-items-center rounded-lg border hover:bg-sunken disabled:opacity-50" style={{borderColor:"var(--danger)",color:"var(--danger)"}} title="ลบ"><Ic d={I.trash} size={14}/></button>
        </div>
      </article>))}</div>}
  </div>);
}

/* ── PromoForm (create / edit) ───────────────────────────────────────────── */
/* ต้องประกาศนอก PromoForm — ถ้าอยู่ข้างใน ทุกครั้งที่พิมพ์จะได้ component ใหม่ แล้ว input หลุดโฟกัส */
const PromoLbl=({children})=><span className="text-xs font-medium text-fg-2">{children}</span>;
const PromoSec=({title,children})=>(<section className="rounded-xl border border-line bg-surface p-4 shadow-sm"><div className="mb-3 text-sm font-semibold">{title}</div>{children}</section>);

function PromoForm({ item, onBack, onDone, toast }) {
  const isEdit=!!item;
  const sat2b=(v)=>Number(v||0)/100;
  const detectTurnoverMode=(p)=>{
    if(Number(p.turnover_amount||0)>0&&Number(p.turnover_factor||0)<=0) return "fixed";
    return "factor";
  };

  const init=item?{
    code:item.code||"", name:item.name||"", description:item.description||"",
    is_active:!!item.is_active, popup_visible:!!item.popup_visible,
    bonus_type:item.bonus_type||"percent",
    bonus_value:item.bonus_type==="percent"?String(item.bonus_value||""):String(sat2b(item.bonus_value)),
    max_bonus:String(sat2b(item.max_bonus)), min_deposit:String(sat2b(item.min_deposit)),
    max_deposit:String(sat2b(item.max_deposit)), deposit_behavior:item.deposit_behavior||"every_deposit",
    turnover_type:item.turnover_type==="credit"?"credit":"deposit",
    turnover_mode:detectTurnoverMode(item),
    turn_amount:detectTurnoverMode(item)==="fixed"?String(sat2b(item.turnover_amount)):String(item.turnover_factor||""),
    withdraw_type:item.withdraw_type||"max_by_turnover",
    max_withdraw:String(sat2b(item.max_withdraw)),
    max_claims_per_user:String(item.max_claims_per_user||""), sort_order:String(item.sort_order||"0"),
    image_url:item.image_url||"", mobile_image_url:item.mobile_image_url||"",
    starts_at:item.starts_at?item.starts_at.slice(0,16):"", ends_at:item.ends_at?item.ends_at.slice(0,16):"",
    allowed_categories:(()=>{ try{ return JSON.parse(item.allowed_categories||"null")||[]; }catch{return [];} })()
  }:{
    code:"", name:"", description:"", is_active:true, popup_visible:false,
    bonus_type:"percent", bonus_value:"", max_bonus:"", min_deposit:"", max_deposit:"",
    deposit_behavior:"every_deposit", turnover_type:"deposit", turnover_mode:"factor",
    turn_amount:"", withdraw_type:"max_by_turnover", max_withdraw:"",
    max_claims_per_user:"1", sort_order:"0", image_url:"", mobile_image_url:"",
    starts_at:"", ends_at:"", allowed_categories:[]
  };
  const [f,setF]=useState(init);
  const [busy,setBusy]=useState(false);
  const [uploading,setUploading]=useState(null);
  const set=(k,v)=>setF(o=>({...o,[k]:v}));

  const uploadImage=async(file,targetKey,kind)=>{
    if(!file)return;
    if(file.size>10*1024*1024){ toast("ไฟล์ต้องไม่เกิน 10MB"); return; }
    setUploading(targetKey);
    try{
      const dataUrl=await new Promise((res,rej)=>{ const r=new FileReader(); r.onload=()=>res(r.result); r.onerror=rej; r.readAsDataURL(file); });
      const r=await api("/branding/upload",{method:"POST",body:{kind,fileName:file.name,mimeType:file.type,dataUrl}});
      if(r.url) set(targetKey,r.url);
      toast("อัปโหลดรูปแล้ว");
    }catch(e){ toast(e.message||"อัปโหลดไม่สำเร็จ"); }
    finally{ setUploading(null); }
  };

  const toggleCat=(cat)=>{
    const cats=f.allowed_categories||[];
    set("allowed_categories",cats.includes(cat)?cats.filter(c=>c!==cat):[...cats,cat]);
  };

  const submit=async()=>{
    if(!f.code.trim()){ toast("กรุณากรอกรหัสโปรโมชั่น"); return; }
    if(!f.name.trim()){ toast("กรุณากรอกชื่อโปรโมชั่น"); return; }
    const b2s=(v)=>Math.round(Number(v||0)*100);
    const isFixed=f.turnover_mode==="fixed";
    const turnVal=Number(f.turn_amount||0);
    const body={
      code:f.code.trim(), name:f.name.trim(), description:f.description.trim(),
      bonusType:f.bonus_type,
      bonusValue:f.bonus_type==="percent"?Math.round(Number(f.bonus_value||0)):b2s(f.bonus_value),
      minDeposit:b2s(f.min_deposit), maxDeposit:b2s(f.max_deposit), maxBonus:b2s(f.max_bonus),
      turnoverType:f.turnover_type,
      turnoverAmount:isFixed?b2s(f.turn_amount):0,
      turnoverFactor:isFixed?0:Math.max(0,Math.round(turnVal)),
      turnoverMultiplier:1,
      withdrawType:f.withdraw_type,
      maxWithdraw:b2s(f.max_withdraw),
      depositBehavior:f.deposit_behavior,
      maxClaimsPerUser:parseInt(f.max_claims_per_user,10)||0,
      isActive:!!f.is_active, imageUrl:f.image_url.trim()||"",
      mobileImageUrl:f.mobile_image_url.trim()||"",
      popupVisible:!!f.popup_visible, sortOrder:parseInt(f.sort_order,10)||0,
      startsAt:f.starts_at?new Date(f.starts_at).toISOString():null,
      endsAt:f.ends_at?new Date(f.ends_at).toISOString():null,
      revolvingMaxWin:0, revolvingMaxLoss:0,
      allowedCategories:(f.allowed_categories||[]).length?f.allowed_categories:null
    };
    setBusy(true);
    try{
      if(isEdit){ await api("/promotions/"+item.id,{method:"PUT",body}); toast("บันทึกโปรโมชั่นแล้ว"); }
      else{ await api("/promotions",{method:"POST",body}); toast("สร้างโปรโมชั่นแล้ว"); }
      onDone&&onDone();
    }catch(e){ toast(e.data&&e.data.error==="validation_error"?"ข้อมูลไม่ถูกต้อง":(e.message||"ไม่สำเร็จ")); }
    finally{ setBusy(false); }
  };

  const inp="h-9 w-full rounded-lg border border-line bg-sunken px-3 text-sm text-fg focus:border-accent focus:bg-surface focus:outline-none";
  const UploadBtn=({targetKey,kind})=><label className="mt-1 inline-flex items-center gap-1.5 rounded-lg border border-line bg-surface px-3 py-1.5 text-xs font-medium text-fg-2 hover:bg-sunken cursor-pointer"><Ic d={I.upload||I.plus} size={14}/> {uploading===targetKey?"กำลังอัปโหลด…":"อัปโหลด"}<input type="file" accept="image/*" className="hidden" onChange={e=>uploadImage(e.target.files[0],targetKey,kind)}/></label>;

  return (<div className="space-y-4">
    <div className="flex items-center gap-2">
      <button onClick={onBack} className="flex h-8 items-center gap-1.5 rounded-lg border border-line px-2.5 text-xs font-medium text-fg-2 hover:bg-sunken"><Ic d={I.back} size={14}/> ย้อนกลับ</button>
      <span className="text-sm font-semibold">{isEdit?"แก้ไขโปรโมชั่น":"สร้างโปรโมชั่น"}</span>
    </div>

    <PromoSec title="ข้อมูลหลัก">
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
        <label className="block"><PromoLbl>รหัส (code) *</PromoLbl><input className={inp+" mt-1"} value={f.code} onChange={e=>set("code",e.target.value)} placeholder="PROMO100"/></label>
        <label className="block"><PromoLbl>ชื่อ *</PromoLbl><input className={inp+" mt-1"} value={f.name} onChange={e=>set("name",e.target.value)} placeholder="โปรสมาชิกใหม่"/></label>
        <label className="block sm:col-span-2"><PromoLbl>รายละเอียด</PromoLbl><input className={inp+" mt-1"} value={f.description} onChange={e=>set("description",e.target.value)}/></label>
        <div className="flex items-center gap-4">
          <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={f.is_active} onChange={e=>set("is_active",e.target.checked)} className="h-4 w-4 accent-[var(--accent)]"/><span className="text-fg-2">เปิดใช้งาน</span></label>
          <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={f.popup_visible} onChange={e=>set("popup_visible",e.target.checked)} className="h-4 w-4 accent-[var(--accent)]"/><span className="text-fg-2">แสดง Popup</span></label>
        </div>
      </div>
    </PromoSec>

    <PromoSec title="ประเภทโบนัส">
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
        <label className="block"><PromoLbl>ประเภท</PromoLbl><select className={inp+" mt-1"} value={f.bonus_type} onChange={e=>set("bonus_type",e.target.value)}><option value="percent">เปอร์เซ็นต์ (%)</option><option value="fixed">คงที่ (บาท)</option></select></label>
        <label className="block"><PromoLbl>ค่าโบนัส {f.bonus_type==="percent"?"(%)":"(บาท)"}</PromoLbl><input type="number" min="0" className={inp+" mt-1 tnum"} value={f.bonus_value} onChange={e=>set("bonus_value",e.target.value)}/></label>
        <label className="block"><PromoLbl>โบนัสสูงสุด (บาท)</PromoLbl><input type="number" min="0" className={inp+" mt-1 tnum"} value={f.max_bonus} onChange={e=>set("max_bonus",e.target.value)} placeholder="0 = ไม่จำกัด"/></label>
        <label className="block"><PromoLbl>ฝากขั้นต่ำ (บาท)</PromoLbl><input type="number" min="0" className={inp+" mt-1 tnum"} value={f.min_deposit} onChange={e=>set("min_deposit",e.target.value)}/></label>
        <label className="block"><PromoLbl>ฝากสูงสุด (บาท)</PromoLbl><input type="number" min="0" className={inp+" mt-1 tnum"} value={f.max_deposit} onChange={e=>set("max_deposit",e.target.value)} placeholder="0 = ไม่จำกัด"/></label>
        <label className="block"><PromoLbl>รูปแบบการฝาก</PromoLbl><select className={inp+" mt-1"} value={f.deposit_behavior} onChange={e=>set("deposit_behavior",e.target.value)}><option value="every_deposit">ทุกยอดฝาก</option><option value="new_member">สมาชิกใหม่</option><option value="free">แจกฟรี</option></select></label>
      </div>
    </PromoSec>

    <PromoSec title="เทิร์น">
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
        <label className="block"><PromoLbl>ประเภทเทิร์น</PromoLbl><select className={inp+" mt-1"} value={f.turnover_type} onChange={e=>set("turnover_type",e.target.value)}><option value="deposit">เทิร์นโอเวอร์ (ยอดฝาก)</option><option value="credit">เทิร์นเครดิต</option></select></label>
        <label className="block"><PromoLbl>วิธีตั้งยอดเทิร์น</PromoLbl><select className={inp+" mt-1"} value={f.turnover_mode} onChange={e=>set("turnover_mode",e.target.value)}><option value="factor">คำนวณเป็นเท่า</option><option value="fixed">ระบุจำนวน (บาท)</option></select></label>
        <label className="block"><PromoLbl>{f.turnover_mode==="fixed"?"ยอดเทิร์นที่ต้องเล่นครบ (บาท)":"จำนวนเทิร์น (เท่า)"}</PromoLbl><input type="number" min="0" className={inp+" mt-1 tnum"} value={f.turn_amount} onChange={e=>set("turn_amount",e.target.value)} placeholder="0"/></label>
      </div>
      <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
        <label className="block"><PromoLbl>วิธีคำนวณถอนสูงสุด</PromoLbl><select className={inp+" mt-1"} value={f.withdraw_type} onChange={e=>set("withdraw_type",e.target.value)}><option value="max_by_turnover">อิงตามยอดเทิร์นเล่น</option><option value="fixed_max_withdraw">จำกัดถอนสูงสุด (บาท)</option></select></label>
        <label className="block"><PromoLbl>ถอนสูงสุด (บาท)</PromoLbl><input type="number" min="0" className={inp+" mt-1 tnum"} value={f.max_withdraw} onChange={e=>set("max_withdraw",e.target.value)} placeholder="0 = ไม่จำกัด"/></label>
      </div>
    </PromoSec>

    <PromoSec title="หมวดเกมที่อนุญาต">
      <p className="text-xs text-muted mb-2">ไม่เลือก = อนุญาตทุกหมวด</p>
      <div className="flex flex-wrap gap-2">
        {PROMO_CATS.map(cat=>(
          <label key={cat} className={"flex cursor-pointer items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs transition-colors "+((f.allowed_categories||[]).includes(cat)?"border-accent/40 bg-accent-soft text-accent font-medium":"border-line bg-sunken text-fg-2 hover:bg-surface")}>
            <input type="checkbox" checked={(f.allowed_categories||[]).includes(cat)} onChange={()=>toggleCat(cat)} className="hidden"/>{cat}
          </label>
        ))}
      </div>
    </PromoSec>

    <PromoSec title="รูปภาพ">
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
        <div>
          <PromoLbl>รูปโปรโมชั่น (Desktop)</PromoLbl>
          <input type="url" className={inp+" mt-1"} value={f.image_url} onChange={e=>set("image_url",e.target.value)} placeholder="https://…"/>
          {UploadBtn({targetKey:"image_url",kind:"promo_image"})}
          {f.image_url&&<img src={f.image_url} className="mt-2 max-h-20 rounded-lg border border-line object-contain" onError={e=>{e.target.style.display="none"}}/>}
        </div>
        <div>
          <PromoLbl>รูปโปรโมชั่น (Mobile)</PromoLbl>
          <input type="url" className={inp+" mt-1"} value={f.mobile_image_url} onChange={e=>set("mobile_image_url",e.target.value)} placeholder="https://…"/>
          {UploadBtn({targetKey:"mobile_image_url",kind:"promo_mobile_image"})}
          {f.mobile_image_url&&<img src={f.mobile_image_url} className="mt-2 max-h-20 rounded-lg border border-line object-contain" onError={e=>{e.target.style.display="none"}}/>}
        </div>
      </div>
    </PromoSec>

    <PromoSec title="อื่นๆ">
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
        <label className="block"><PromoLbl>ใช้ได้กี่ครั้ง/คน</PromoLbl><input type="number" min="0" className={inp+" mt-1 tnum"} value={f.max_claims_per_user} onChange={e=>set("max_claims_per_user",e.target.value)} placeholder="0 = ไม่จำกัด"/></label>
        <label className="block"><PromoLbl>ลำดับการแสดง</PromoLbl><input type="number" min="0" className={inp+" mt-1 tnum"} value={f.sort_order} onChange={e=>set("sort_order",e.target.value)}/></label>
        <label className="block"><PromoLbl>เริ่มต้น</PromoLbl><input type="datetime-local" className={inp+" mt-1"} value={f.starts_at} onChange={e=>set("starts_at",e.target.value)}/></label>
        <label className="block"><PromoLbl>สิ้นสุด</PromoLbl><input type="datetime-local" className={inp+" mt-1"} value={f.ends_at} onChange={e=>set("ends_at",e.target.value)}/></label>
      </div>
    </PromoSec>

    <div className="flex items-center gap-2">
      <button onClick={onBack} className="h-9 rounded-lg border border-line bg-surface px-4 text-sm font-medium text-fg-2 hover:bg-sunken">ยกเลิก</button>
      <button disabled={busy} onClick={submit} className="h-9 rounded-lg bg-accent px-5 text-sm font-semibold text-accent-fg shadow-sm hover:bg-accent-h disabled:opacity-50">{busy?"กำลังบันทึก…":(isEdit?"บันทึก":"สร้างโปรโมชั่น")}</button>
    </div>
  </div>);
}
