/* ==========================================================================
 * ADMIN NEXT — page-prediction2.jsx  (จัดการทายผล — CRUD + lifecycle)
 * ========================================================================== */

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

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{ const d=await api("/predictions"); 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 STATUS_MAP={draft:["ร่าง","info"],pending:["รอเปิด","info"],active:["เปิดรับ","success"],closed:["ปิดแล้ว","warn"],announced:["ประกาศผล","accent"],distributed:["แจกรางวัลแล้ว","muted"]};
  const stBadge=(s)=>{ const [l,t]=STATUS_MAP[s]||[s,"info"]; return <Badge tone={t}>{l}</Badge>; };
  const REWARD_LABEL={none:"ไม่มีรางวัล",all_winners:"แจกทุกคน",random_draw:"สุ่มรางวัล"};

  const action=async(id,act,body={})=>{
    setBusy(true);
    try{ await api("/predictions/"+id+"/"+act,{method:"POST",body}); toast("สำเร็จ"); load(); }
    catch(e){ toast(e.message||"ไม่สำเร็จ"); } finally{ setBusy(false); } };

  const del=async(id)=>{ if(!window.confirm("ลบรายการทายผลนี้?"))return; setBusy(true);
    try{ await api("/predictions/"+id,{method:"DELETE"}); toast("ลบแล้ว"); load(); }
    catch(e){ toast(e.message||"ไม่สำเร็จ"); } finally{ setBusy(false); } };

  const announce=async(row)=>{
    const choices=row.choices||[];
    const isText=(row.answer_type||"choice")==="text";
    if(isText){
      const txt=window.prompt("ใส่คำตอบที่ถูกต้อง:");
      if(txt===null)return;
      action(row.id,"announce",{correctAnswerText:txt});
    } else {
      const idx=window.prompt("ใส่ลำดับตัวเลือกที่ถูก (0-"+(choices.length-1)+"):\n"+choices.map((c,i)=>i+": "+c).join("\n"));
      if(idx===null)return;
      action(row.id,"announce",{correctChoice:Number(idx)});
    }
  };

  const sat2b=(v)=>Number(v||0)/100;

  const openEdit=(r)=>setForm({
    _id:r.id, title:r.title||"", description:r.description||"",
    answerType:r.answer_type||"choice",
    choicesText:(r.choices||[]).join("\n"),
    imageUrl:r.image_url||"",
    startDate:r.start_at?toThaiDate(r.start_at):"", startTime:r.start_at?toThaiTime(r.start_at):"00:00",
    endDate:r.end_at?toThaiDate(r.end_at):"", endTime:r.end_at?toThaiTime(r.end_at):"23:59",
    minDepositAmount:String(sat2b(r.min_deposit_amount)),
    rewardType:r.reward_type||"none",
    rewardAmount:String(sat2b(r.reward_amount)),
    winnerCount:String(r.winner_count||1),
    showPopup:!!r.show_popup, popupImageUrl:r.popup_image_url||""
  });

  const openCreate=()=>setForm({
    title:"", description:"", answerType:"choice", choicesText:"", imageUrl:"",
    startDate:"", startTime:"00:00", endDate:"", endTime:"23:59",
    minDepositAmount:"0", rewardType:"none", rewardAmount:"0", winnerCount:"1",
    showPopup:false, popupImageUrl:""
  });

  const save=async(f)=>{ setBusy(true);
    const startAt=f.startDate?new Date(f.startDate+"T"+f.startTime+":00+07:00").toISOString():"";
    const endAt=f.endDate?new Date(f.endDate+"T"+f.endTime+":00+07:00").toISOString():"";
    const body={
      title:f.title, description:f.description, answerType:f.answerType,
      choices:(f.choicesText||"").split("\n").map(s=>s.trim()).filter(Boolean),
      imageUrl:f.imageUrl, startAt, endAt,
      minDepositAmount:Math.round(Number(f.minDepositAmount||0)*100),
      rewardType:f.rewardType,
      rewardAmount:Math.round(Number(f.rewardAmount||0)*100),
      winnerCount:parseInt(f.winnerCount,10)||1,
      showPopup:!!f.showPopup, popupImageUrl:f.popupImageUrl
    };
    try{
      if(f._id){ await api("/predictions/"+f._id,{method:"PUT",body}); }
      else { await api("/predictions",{method:"POST",body}); }
      toast("บันทึกแล้ว"); setForm(null); load();
    }catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setBusy(false); } };

  if(form) return <PredForm init={form} onSave={save} onCancel={()=>setForm(null)} busy={busy} toast={toast}/>;

  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={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={openCreate} 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-[750px] border-collapse text-sm">
      <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{H({children:"หัวข้อ"})}{H({children:"ประเภท"})}{H({children:"รางวัล"})}{H({children:"เริ่ม"})}{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="7"><div className="skel h-5 w-full"/></td></tr>))
        : rows.length===0 ? (<tr><td colSpan="7" 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 transition-colors last:border-0 hover:bg-sunken/50">
          <td className="px-3 py-2.5">
            <div className="flex items-center gap-2">
              {r.image_url&&<img src={r.image_url} className="h-8 w-8 rounded object-cover bg-sunken" onError={e=>{e.target.style.display="none"}}/>}
              <div><div className="font-medium text-fg">{r.title||"-"}</div><div className="text-[11px] text-muted truncate max-w-[200px]">{r.description||""}</div></div>
            </div>
          </td>
          <td className="px-3 text-xs text-fg-2">{(r.answer_type||"choice")==="text"?"กรอกคำตอบ":"ตัวเลือก ("+(r.choices||[]).length+")"}</td>
          <td className="px-3 text-xs text-fg-2">{REWARD_LABEL[r.reward_type]||"-"}{r.reward_type!=="none"&&r.reward_amount?<div className="font-medium tnum">{baht(r.reward_amount)}</div>:null}{r.reward_distributed&&<div className="text-success text-[10px]">แจกแล้ว</div>}</td>
          <td className="px-3 text-xs text-fg-2">{r.start_at?fmtDT(r.start_at):"-"}</td>
          <td className="px-3 text-xs text-fg-2">{r.end_at?fmtDT(r.end_at):"-"}</td>
          <td className="px-3">{stBadge(r.status)}</td>
          <td className="pr-4"><div className="flex items-center justify-end gap-1">
            {r.status==="draft"||r.status==="pending" ? <button disabled={busy} title="เปิดรับ" onClick={()=>action(r.id,"activate")} className="grid h-7 w-7 place-items-center rounded-lg border border-line text-success hover:bg-sunken disabled:opacity-50"><Ic d={I.check} size={14}/></button>:null}
            {r.status==="active" ? <button disabled={busy} title="ปิด" onClick={()=>action(r.id,"close")} className="grid h-7 w-7 place-items-center rounded-lg border border-line text-warn hover:bg-sunken disabled:opacity-50"><Ic d={I.ban} size={14}/></button>:null}
            {r.status==="closed" ? <button disabled={busy} title="ประกาศผล" onClick={()=>announce(r)} className="grid h-7 w-7 place-items-center rounded-lg border border-line text-accent hover:bg-sunken disabled:opacity-50"><Ic d={I.star} size={14}/></button>:null}
            {r.status==="announced"&&r.reward_type!=="none"&&!r.reward_distributed ? <button disabled={busy} title="แจกรางวัล" onClick={()=>action(r.id,"distribute-reward")} className="grid h-7 w-7 place-items-center rounded-lg border border-line text-success hover:bg-sunken disabled:opacity-50"><Ic d={I.gift} size={14}/></button>:null}
            <button title="แก้ไข" onClick={()=>openEdit(r)} 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 disabled={busy} title="ลบ" onClick={()=>del(r.id)} className="grid h-7 w-7 place-items-center rounded-lg border border-line text-danger hover:bg-sunken disabled:opacity-50"><Ic d={I.trash} size={14}/></button>
          </div></td>
        </tr>))}
      </tbody>
    </table></div></div>)}
  </div>);
}

function toThaiDate(iso){ if(!iso)return""; const d=new Date(new Date(iso).getTime()+7*3600000); return d.toISOString().slice(0,10); }
function toThaiTime(iso){ if(!iso)return"00:00"; const d=new Date(new Date(iso).getTime()+7*3600000); return d.toISOString().slice(11,16); }

function PredForm({init,onSave,onCancel,busy,toast}){
  const [f,setF]=useState(init);
  const [uploading,setUploading]=useState(null);
  const set=(k,v)=>setF(o=>({...o,[k]:v}));

  const uploadImage=async(file,targetKey)=>{
    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("/predictions/upload-image",{method:"POST",body:{dataUrl}});
      if(r.url) set(targetKey,r.url);
      toast("อัปโหลดรูปแล้ว");
    }catch(e){ toast(e.message||"อัปโหลดไม่สำเร็จ"); }
    finally{ setUploading(null); }
  };

  const Lb=({children})=><label className="mb-1 block text-xs font-semibold text-fg-2">{children}</label>;
  const In=({k,type="text",ph=""})=><input type={type} value={f[k]||""} onChange={e=>set(k,e.target.value)} placeholder={ph} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/>;
  const Section=({title,children})=><div className="rounded-xl border border-line bg-surface p-5 shadow-sm space-y-4"><h3 className="text-sm font-semibold text-fg">{title}</h3>{children}</div>;
  const UploadBtn=({targetKey})=><label className="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)}/></label>;

  return (<div className="mx-auto max-w-2xl space-y-4">
    <button onClick={onCancel} className="flex items-center gap-1 text-sm text-muted hover:text-fg"><Ic d={I.back} size={16}/> กลับ</button>

    {Section({title:f._id?"แก้ไขทายผล":"สร้างทายผล",children:<>
      <div><Lb>ชื่อกิจกรรม *</Lb>{In({k:"title",ph:"เช่น ทายผลบอล คู่ A vs B"})}</div>
      <div><Lb>รายละเอียด / กติกา</Lb><textarea value={f.description||""} onChange={e=>set("description",e.target.value)} rows={2} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
      <div>
        <Lb>รูปภาพกิจกรรม <span className="text-xs font-normal text-muted">(1040×1040px, ไม่เกิน 10MB)</span></Lb>
        <div className="flex gap-2 items-center"><input type="text" value={f.imageUrl||""} onChange={e=>set("imageUrl",e.target.value)} placeholder="https://..." className="flex-1 rounded-lg border border-line bg-surface px-3 py-2 text-sm"/>{UploadBtn({targetKey:"imageUrl"})}</div>
        {f.imageUrl&&<img src={f.imageUrl} className="mt-2 max-h-24 rounded-lg border border-line object-contain" onError={e=>{e.target.style.display="none"}}/>}
      </div>
    </>})}

    {Section({title:"ประเภทคำตอบ",children:<>
      <div className="flex gap-2">
        <button type="button" onClick={()=>set("answerType","choice")} className={"flex-1 rounded-lg border-2 px-4 py-3 text-sm font-medium text-center transition-colors "+(f.answerType==="choice"?"border-accent bg-accent-soft text-accent":"border-line bg-sunken text-fg-2 hover:border-accent/40")}><Ic d={I.grid||I.list} size={18} cls="mx-auto mb-1"/> เลือกจากตัวเลือก</button>
        <button type="button" onClick={()=>set("answerType","text")} className={"flex-1 rounded-lg border-2 px-4 py-3 text-sm font-medium text-center transition-colors "+(f.answerType==="text"?"border-accent bg-accent-soft text-accent":"border-line bg-sunken text-fg-2 hover:border-accent/40")}><Ic d={I.edit||I.pen} size={18} cls="mx-auto mb-1"/> กรอกข้อความ</button>
      </div>
      {f.answerType!=="text"&&<div><Lb>ตัวเลือก * <span className="text-xs font-normal text-muted">(บรรทัดละ 1 อย่างน้อย 2 ตัวเลือก)</span></Lb><textarea value={f.choicesText||""} onChange={e=>set("choicesText",e.target.value)} rows={4} placeholder={"ทีม A ชนะ\nเสมอ\nทีม B ชนะ"} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm mono"/></div>}
    </>})}

    {Section({title:"ช่วงเวลากิจกรรม (เวลาไทย)",children:<>
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <div><Lb>วันเริ่ม *</Lb><input type="date" value={f.startDate||""} onChange={e=>set("startDate",e.target.value)} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
        <div><Lb>เวลาเริ่ม</Lb><input type="time" value={f.startTime||"00:00"} onChange={e=>set("startTime",e.target.value)} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
        <div><Lb>วันสิ้นสุด *</Lb><input type="date" value={f.endDate||""} onChange={e=>set("endDate",e.target.value)} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
        <div><Lb>เวลาสิ้นสุด</Lb><input type="time" value={f.endTime||"23:59"} onChange={e=>set("endTime",e.target.value)} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
      </div>
    </>})}

    {Section({title:"เงื่อนไขการเข้าร่วม",children:<>
      <div><Lb>ยอดฝากขั้นต่ำต่อรายการ (บาท) <span className="text-xs font-normal text-muted">0 = ไม่กำหนด</span></Lb><input type="number" min="0" value={f.minDepositAmount||""} onChange={e=>set("minDepositAmount",e.target.value)} placeholder="0" className="w-40 rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
    </>})}

    {Section({title:"ตั้งค่ารางวัล",children:<>
      <div><Lb>ประเภทรางวัล</Lb>
        <select value={f.rewardType||"none"} onChange={e=>set("rewardType",e.target.value)} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm">
          <option value="none">ไม่มีรางวัล</option>
          <option value="all_winners">แจกทุกคนที่ทายถูก</option>
          <option value="random_draw">สุ่มจับรางวัล (จากคนถูก)</option>
        </select>
      </div>
      {f.rewardType!=="none"&&<div className="grid grid-cols-2 gap-3">
        <div><Lb>รางวัลต่อคน (บาท) *</Lb><input type="number" min="0" value={f.rewardAmount||""} onChange={e=>set("rewardAmount",e.target.value)} placeholder="100" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
        {f.rewardType==="random_draw"&&<div><Lb>จำนวนผู้โชคดี</Lb><input type="number" min="1" value={f.winnerCount||""} onChange={e=>set("winnerCount",e.target.value)} placeholder="1" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>}
      </div>}
    </>})}

    {Section({title:"Popup หน้าแรก",children:<>
      <label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={!!f.showPopup} onChange={e=>set("showPopup",e.target.checked)} className="h-4 w-4 rounded border-line accent-accent"/><span className="text-sm text-fg-2">แสดง Popup เมื่อเข้าหน้าแรก</span></label>
      <div>
        <Lb>รูป Popup <span className="text-xs font-normal text-muted">(600×800px, ไม่เกิน 10MB)</span></Lb>
        <div className="flex gap-2 items-center"><input type="text" value={f.popupImageUrl||""} onChange={e=>set("popupImageUrl",e.target.value)} placeholder="https://..." className="flex-1 rounded-lg border border-line bg-surface px-3 py-2 text-sm"/>{UploadBtn({targetKey:"popupImageUrl"})}</div>
        {f.popupImageUrl&&<img src={f.popupImageUrl} className="mt-2 max-h-24 rounded-lg border border-line object-contain" onError={e=>{e.target.style.display="none"}}/>}
      </div>
    </>})}

    <div className="flex justify-end gap-2 pt-2">
      <button onClick={onCancel} className="rounded-lg border border-line px-4 py-2 text-sm font-medium text-fg-2 hover:bg-sunken">ยกเลิก</button>
      <button disabled={busy||!f.title} onClick={()=>onSave(f)} 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>);
}
