/* ==========================================================================
 * ADMIN NEXT — page-popupcontact.jsx  (Popup / ช่องทางติดต่อ)
 * ========================================================================== */

function PopupContactPage({ toast }) {
  const [cfg,setCfg]=useState({}),[loading,setLoading]=useState(true),[saving,setSaving]=useState(false),[err,setErr]=useState(null);
  const [tab,setTab]=useState("popup");
  const [contacts,setContacts]=useState([]);

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

  const save=async()=>{ setSaving(true);
    try{ await api("/settings",{method:"POST",body:{...cfg,contact_channels:JSON.stringify(contacts)}}); toast("บันทึกแล้ว"); }
    catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setSaving(false); } };
  const set=(k,v)=>setCfg(c=>({...c,[k]:v}));

  const uploadPopupImage=async(file)=>{
    if(!file) return;
    if(file.size>10*1024*1024){ toast("ไฟล์ต้องไม่เกิน 10MB"); return; }
    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:"site_popup",fileName:file.name,mimeType:file.type,dataUrl}});
      if(r.url) set("site_popup_image",r.url);
      toast("อัปโหลดรูปแล้ว");
    }catch(e){ toast(e.message||"อัปโหลดไม่สำเร็จ"); }
  };

  const addContact=()=>setContacts(c=>[...c,{type:"line",label:"",url:""}]);
  const updateContact=(i,k,v)=>setContacts(c=>c.map((ch,j)=>j===i?{...ch,[k]:v}:ch));
  const removeContact=(i)=>setContacts(c=>c.filter((_,j)=>j!==i));

  if(loading) return <div className="flex items-center gap-2 py-16 justify-center text-sm text-muted"><Ic d={I.refresh} size={16} cls="animate-spin"/> กำลังโหลด…</div>;
  if(err) return <HistErr msg={err} onRetry={load}/>;

  const Lb=({children})=><label className="mb-1 block text-xs font-semibold text-fg-2">{children}</label>;
  const In=({k,ph="",type="text"})=><input type={type} value={cfg[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 contactTypes=["line","telegram","facebook","twitter","youtube","tiktok","phone","other"];

  return (<div className="space-y-4">
    <div className="flex gap-1 rounded-lg bg-sunken p-1">
      {[["popup","Popup"],["contact","ช่องทางติดต่อ"]].map(([k,l])=><button key={k} onClick={()=>setTab(k)} className={"rounded-md px-3 py-1.5 text-sm font-medium transition-colors "+(tab===k?"bg-surface text-fg shadow-sm":"text-muted hover:text-fg")}>{l}</button>)}
    </div>

    {tab==="popup"&&<div className="space-y-5">
      <div className="rounded-xl border border-line bg-surface p-5 shadow-sm space-y-4">
        <h3 className="text-sm font-semibold text-fg">Popup เว็บไซต์</h3>
        <label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={cfg.site_popup_enabled==="1"} onChange={e=>set("site_popup_enabled",e.target.checked?"1":"0")} className="h-4 w-4 rounded border-line accent-accent"/><span className="text-sm text-fg-2">แสดง Popup เมื่อเปิดเว็บ</span></label>
        <div>
          <Lb>URL รูป Popup <span className="text-xs font-normal text-muted">(แนะนำ 900×1200px อัตราส่วน 3:4)</span></Lb>
          {In({k:"site_popup_image",ph:"https://example.com/popup.webp"})}
          {cfg.site_popup_image&&<img src={cfg.site_popup_image} className="mt-2 mx-auto max-h-40 rounded-lg border border-line object-contain" onError={e=>{e.target.style.display="none"}}/>}
          <label className="mt-2 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}/> อัปโหลดรูป<input type="file" accept="image/*" className="hidden" onChange={e=>uploadPopupImage(e.target.files[0])}/></label>
        </div>
        <div><Lb>ลิงก์เมื่อกด Popup</Lb>{In({k:"site_popup_url",ph:"https://..."})}</div>
        <div><Lb>URL วิดีโอ/เพลง Popup <span className="text-xs font-normal text-muted">(YouTube embed หรือ .mp4 — ถ้ามีจะแสดงแทนรูป)</span></Lb>{In({k:"site_popup_video",ph:"https://www.youtube.com/embed/VIDEO_ID"})}</div>
        <div><Lb>ข้อความ Popup <span className="text-xs font-normal text-muted">(ถ้าไม่มีรูปและไม่มีวิดีโอ)</span></Lb><textarea value={cfg.site_popup_text||""} onChange={e=>set("site_popup_text",e.target.value)} rows={3} placeholder="ข้อความโปรโมชั่น..." className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
      </div>
    </div>}

    {tab==="contact"&&<div className="space-y-5">
      <div className="rounded-xl border border-line bg-surface p-5 shadow-sm space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-semibold text-fg">ช่องทางติดต่อ</h3>
          <button onClick={addContact} className="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"><Ic d={I.plus} size={14}/> เพิ่มช่องทาง</button>
        </div>
        <p className="text-xs text-muted">เพิ่มได้ไม่จำกัด เช่น LINE 3 ช่อง, Telegram 2 ช่อง ฯลฯ</p>
        <div className="space-y-2">
          {contacts.map((ch,i)=>(
            <div key={i} className="flex items-center gap-2 rounded-lg border border-line-soft p-3">
              <select value={ch.type||"line"} onChange={e=>updateContact(i,"type",e.target.value)} className="w-28 rounded-lg border border-line bg-surface px-2 py-1.5 text-sm">
                {contactTypes.map(t=><option key={t} value={t}>{t}</option>)}
              </select>
              <input type="text" value={ch.label||""} onChange={e=>updateContact(i,"label",e.target.value)} placeholder="Label / ชื่อช่องทาง" className="flex-1 rounded-lg border border-line bg-surface px-2 py-1.5 text-sm"/>
              <input type="text" value={ch.url||""} onChange={e=>updateContact(i,"url",e.target.value)} placeholder="URL หรือ ID" className="flex-[2] rounded-lg border border-line bg-surface px-2 py-1.5 text-sm"/>
              <button onClick={()=>removeContact(i)} 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>))}
          {contacts.length===0&&<div className="rounded-lg bg-sunken p-4 text-center text-xs text-muted">ยังไม่มีช่องทางติดต่อ</div>}
        </div>
      </div>
    </div>}

    <div className="flex justify-end">
      <button disabled={saving} onClick={save} className="rounded-lg bg-accent px-6 py-2.5 text-sm font-medium text-accent-fg hover:bg-accent-h disabled:opacity-50">{saving?"กำลังบันทึก…":"บันทึกทั้งหมด"}</button>
    </div>
  </div>);
}
