/* ==========================================================================
 * ADMIN NEXT — page-support.jsx  (แยกไฟล์ละหน้า; โหลดผ่าน <script type="text/nx-jsx">)
 * ========================================================================== */

/* ---------- สอบถามปัญหาระบบ — /support-assistant/* ---------- */
const SUPPORT_ERR_TEXT = {
  support_ai_not_configured: "ระบบผู้ช่วยยังไม่เปิดใช้งาน กรุณาติดต่อทีมพัฒนา",
  support_ai_unavailable: "ระบบผู้ช่วยไม่พร้อมใช้งานชั่วคราว ลองใหม่อีกครั้ง",
  support_ai_busy: "ระบบผู้ช่วยมีผู้ใช้งานมาก ลองใหม่ในอีกสักครู่",
  support_ai_rate_limited: "ถามถี่เกินไป รอ 1 นาทีแล้วลองใหม่",
  support_ai_one_at_a_time: "กรุณารอคำตอบก่อนหน้าให้เสร็จก่อน",
  support_ai_question_too_long: "คำถามยาวเกินไป (สูงสุด 2,000 ตัวอักษร)",
  support_ai_key_invalid: "คีย์ไม่ถูกต้อง ตรวจว่าคัดลอกครบ (ขึ้นต้น AIC1-)",
  support_ai_gateway_not_allowed: "คีย์นี้ไม่ใช่ของทีมพัฒนาเรา ติดต่อทีมพัฒนา",
  support_ai_locked: "ผู้ช่วยของเว็บนี้ถูกล็อกอยู่ กรุณาติดต่อทีมพัฒนา",
  support_ai_images_disabled: "ตอนนี้ปิดการแนบรูปอยู่ ส่งเป็นข้อความแทนได้",
  support_ai_invalid_image: "รูปนี้ใช้ไม่ได้ ลองถ่ายหรือแคปหน้าจอใหม่",
  support_ai_image_too_large: "รูปใหญ่เกินไป ลองแนบทีละรูป",
  support_ai_invalid_request: "ส่งคำถามไม่สำเร็จ ลองพิมพ์ใหม่อีกครั้ง",
};
const SUPPORT_EXAMPLES = ["0812345678 ฝากไม่เข้า", "user99 ทำไมถอนไม่ได้", "วิธีอนุมัติรายการถอน", "ร่างข้อความตอบลูกค้าที่ฝากไม่เข้า"];
const supportDate = (iso) => iso ? new Date(iso).toLocaleDateString("th-TH", { timeZone: "Asia/Bangkok", day: "numeric", month: "short", year: "numeric" }) : "-";

function supportStatusLabel(status) {
  if (status == null) return ["กำลังตรวจสอบ…", false];
  if (status.subscription_error === "support_ai_locked") return ["ล็อกอยู่ ติดต่อทีมพัฒนา", false];
  const sub = status.subscription;
  if (sub) return sub.active ? ["พร้อมใช้งาน", true] : ["ล็อกอยู่ ติดต่อทีมพัฒนา", false];
  return status.enabled ? ["พร้อมใช้งาน", true] : ["ยังไม่เปิดใช้งาน", false];
}

const SUPPORT_SEND_ICON = ["M5 12h14", "M13 6l6 6-6 6"];
const SUPPORT_BOT_ICON = ["M12 3l1.8 4.2L18 9l-4.2 1.8L12 15l-1.8-4.2L6 9l4.2-1.8z", "M19 15l.8 1.7 1.7.8-1.7.8L19 20l-.8-1.7-1.7-.8 1.7-.8z"];
const SUPPORT_CLIP_ICON = "M21 11.5l-8.6 8.6a5 5 0 0 1-7.1-7.1l8.6-8.6a3.3 3.3 0 0 1 4.7 4.7l-8.6 8.6a1.7 1.7 0 0 1-2.4-2.4l7.9-7.9";
const SUPPORT_CLOSE_ICON = ["M6 6l12 12", "M18 6L6 18"];
const SUPPORT_EXPAND_ICON = ["M15 3h6v6", "M9 21H3v-6", "M21 3l-7 7", "M3 21l7-7"];
const SUPPORT_MAX_IMAGE_EDGE = 1568;
const SUPPORT_MAX_IMAGE_FILE = 15 * 1024 * 1024;
const SUPPORT_WIDGET_MESSAGES = 50;
const supportTime = (iso) => { try { return new Date(iso).toLocaleTimeString("th-TH", { timeZone: "Asia/Bangkok", hour: "2-digit", minute: "2-digit" }); } catch { return ""; } };

/* ---------- สถานะแชท (ผูกกับ token แอดมิน ไม่เก็บข้อความลงเครื่อง) ----------
 * feed   = หน้า "สอบถามปัญหาระบบ": ถามตอบรวมของแอดมินทุกคนในเว็บ 100 ข้อความล่าสุด
 * widget = กล่องผู้ช่วยติดตาม: ของแอดมินคนนี้ รอบนี้ (ปิดกล่องแล้วเปิดใหม่ = รอบใหม่) แสดง 50 ข้อความล่าสุด */
const SUPPORT_FEED_POLL_MS = 30 * 1000;

function supportCreateChat(kind, limit) {
  return { kind, limit, owner: null, session: null, me: "", msgs: [], busy: false, loaded: false, loading: false, listeners: new Set() };
}
const supportFeedChat = supportCreateChat("feed", 100);
const supportWidgetChat = supportCreateChat("widget", SUPPORT_WIDGET_MESSAGES);
const supportStatusStore = { owner: null, status: null, loading: false, listeners: new Set() };

function supportOwner() {
  return typeof getToken === "function" ? getToken() : "";
}

function supportChatSession(chat) {
  const owner = supportOwner();
  if (chat.owner !== owner) Object.assign(chat, { owner, session: null, me: "", msgs: [], busy: false, loaded: false, loading: false });
  return chat;
}

function supportChatSnapshot(chat) {
  return { msgs: chat.msgs, busy: chat.busy, loaded: chat.loaded, me: chat.me };
}

function supportChatUpdate(chat, patch) {
  Object.assign(chat, patch);
  const snapshot = supportChatSnapshot(chat);
  chat.listeners.forEach(listener => listener(snapshot));
}

function useSupportChat(chat, load) {
  supportChatSession(chat);
  const [view, setView] = useState(() => supportChatSnapshot(chat));
  useEffect(() => {
    chat.listeners.add(setView);
    setView(supportChatSnapshot(chat));
    load();
    return () => { chat.listeners.delete(setView); };
  }, []);
  return view;
}

function supportLoadStatus() {
  const owner = supportOwner();
  if (supportStatusStore.owner === owner && (supportStatusStore.status || supportStatusStore.loading)) return;
  Object.assign(supportStatusStore, { owner, loading: true });
  api("/support-assistant/status")
    .then(status => status, () => ({ enabled: false }))
    .then(status => {
      if (supportStatusStore.owner !== owner) return;
      Object.assign(supportStatusStore, { status, loading: false });
      supportStatusStore.listeners.forEach(listener => listener(status));
    });
}

function useSupportStatus() {
  const [status, setStatus] = useState(() => (supportStatusStore.owner === supportOwner() ? supportStatusStore.status : null));
  useEffect(() => {
    supportStatusStore.listeners.add(setStatus);
    supportLoadStatus();
    return () => { supportStatusStore.listeners.delete(setStatus); };
  }, []);
  return status;
}

// โหลดหน้ารวม (เรียกซ้ำได้ ใช้ตอนเปิดหน้า/ทุก 30 วิ/หลังถามเสร็จ) ข้ามถ้ากำลังรอคำตอบ จะได้ไม่ทับข้อความที่กำลังส่ง
function supportLoadFeed(toast, force) {
  const chat = supportChatSession(supportFeedChat);
  if (chat.busy || chat.loading || (chat.loaded && !force)) return;
  const owner = chat.owner;
  chat.loading = true;
  api("/support-assistant/history").then(d => {
    if (supportFeedChat.owner !== owner || supportFeedChat.busy) { supportFeedChat.loading = false; return; }
    supportChatUpdate(supportFeedChat, { msgs: d.messages || [], me: d.me || "", loaded: true, loading: false });
  }, () => {
    if (supportFeedChat.owner !== owner) return;
    supportChatUpdate(supportFeedChat, { loaded: true, loading: false });
    if (!force) toast && toast("โหลดประวัติแชทไม่สำเร็จ");
  });
}

// กล่องผู้ช่วยติดตาม: รีเฟรชหน้าระหว่างกล่องเปิดอยู่ = โหลดรอบเดิมกลับมาจากเซิร์ฟ
function supportLoadWidget(sessionId) {
  const chat = supportChatSession(supportWidgetChat);
  if (!sessionId) return;
  if (chat.session === sessionId && (chat.loaded || chat.loading || chat.busy)) return;
  Object.assign(chat, { session: sessionId, msgs: [], busy: false, loaded: false, loading: true });
  const owner = chat.owner;
  api("/support-assistant/history?session=" + encodeURIComponent(sessionId)).then(d => {
    if (supportWidgetChat.owner !== owner || supportWidgetChat.session !== sessionId) return;
    supportChatUpdate(supportWidgetChat, { msgs: d.messages || [], loaded: true, loading: false });
  }, () => {
    if (supportWidgetChat.owner !== owner || supportWidgetChat.session !== sessionId) return;
    supportChatUpdate(supportWidgetChat, { loaded: true, loading: false });
  });
}

function supportNewSessionId() {
  const bytes = new Uint8Array(12);
  (window.crypto || window.msCrypto).getRandomValues(bytes);
  return "w-" + Array.from(bytes, b => (b % 36).toString(36)).join("");
}

function supportErrorText(e) {
  const code = e.data && e.data.error;
  return SUPPORT_ERR_TEXT[code] || (e.status === 403 ? "ไม่มีสิทธิ์ใช้เมนูนี้" : e.status === 413 ? SUPPORT_ERR_TEXT.support_ai_image_too_large : "ส่งคำถามไม่สำเร็จ ลองใหม่อีกครั้ง");
}

async function supportAsk(chat, { question, images, page, sessionId }) {
  const owner = chat.owner;
  const local = { role: "user", content: question || "(แนบรูป)", asked_by: chat.me, images: images.map(image => image.preview), created_at: new Date().toISOString() };
  supportChatUpdate(chat, { msgs: [...chat.msgs, local].slice(-chat.limit), busy: true });
  let answer;
  try {
    const body = { question, session_id: sessionId, images: images.map(({ media_type, data }) => ({ media_type, data })) };
    if (page && page.key) body.page = { key: page.key, label: String(page.label || page.key).slice(0, 60) };
    const d = await api("/support-assistant/ask", { method: "POST", body });
    answer = { role: "assistant", content: d.answer || "-", created_at: new Date().toISOString() };
  } catch (e) {
    if (e.status === 401) { window.__nxAuthFail && window.__nxAuthFail(); }
    answer = { role: "assistant", content: supportErrorText(e), error: true };
  }
  if (chat.owner !== owner || (chat.kind === "widget" && chat.session !== sessionId)) return;
  supportChatUpdate(chat, { msgs: [...chat.msgs, answer].slice(-chat.limit), busy: false });
}

/* ---------- รูปแนบ: ย่อในเบราว์เซอร์ก่อนส่ง (ด้านยาวไม่เกิน 1568px, JPEG) ---------- */
function supportPrepareImage(file) {
  return new Promise((resolve, reject) => {
    if (!file || !/^image\//.test(file.type)) return reject(new Error("รองรับเฉพาะไฟล์รูป"));
    if (file.size > SUPPORT_MAX_IMAGE_FILE) return reject(new Error("รูปใหญ่เกินไป (เกิน 15MB)"));
    const url = URL.createObjectURL(file);
    const img = new Image();
    img.onload = () => {
      const scale = Math.min(1, SUPPORT_MAX_IMAGE_EDGE / Math.max(img.width, img.height));
      const canvas = document.createElement("canvas");
      canvas.width = Math.max(1, Math.round(img.width * scale));
      canvas.height = Math.max(1, Math.round(img.height * scale));
      const ctx = canvas.getContext("2d");
      ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      URL.revokeObjectURL(url);
      const preview = canvas.toDataURL("image/jpeg", 0.85);
      resolve({ media_type: "image/jpeg", data: preview.slice(preview.indexOf(",") + 1), preview });
    };
    img.onerror = () => { URL.revokeObjectURL(url); reject(new Error("เปิดรูปไม่ได้")); };
    img.src = url;
  });
}

function useSupportComposer(toast, status) {
  const [text, setText] = useState("");
  const [images, setImages] = useState([]);
  const maxImages = (status && status.max_images) || 3;
  const imagesEnabled = !!(status && status.images_enabled !== false);
  const addFiles = async (fileList) => {
    const files = Array.from(fileList || []).filter(file => /^image\//.test(file.type));
    if (!files.length) return;
    if (!imagesEnabled) { toast("ตอนนี้ปิดการแนบรูปอยู่"); return; }
    const room = maxImages - images.length;
    if (room <= 0) { toast("แนบได้สูงสุด " + maxImages + " รูป"); return; }
    if (files.length > room) toast("แนบได้สูงสุด " + maxImages + " รูป");
    const prepared = await Promise.allSettled(files.slice(0, room).map(supportPrepareImage));
    prepared.filter(item => item.status === "rejected").slice(0, 1).forEach(item => toast(item.reason.message));
    const ready = prepared.filter(item => item.status === "fulfilled").map(item => item.value);
    setImages(current => [...current, ...ready].slice(0, maxImages));
  };
  const removeImage = (index) => setImages(current => current.filter((_, i) => i !== index));
  const take = () => { const payload = { question: text.trim(), images }; setText(""); setImages([]); return payload; };
  return { text, setText, images, addFiles, removeImage, take, imagesEnabled, maxImages };
}

/* ---------- ชิ้นส่วนแชท (ใช้ร่วมกันหน้าเต็ม + กล่องลอย) ---------- */
// รูปโปรไฟล์เอวา (โหลดไม่ได้ = ใช้ไอคอนดาวแทน)
const SUPPORT_AVATAR_SRC = "/admin/assets/eva-avatar.jpg";

function SupportAvatar({ small, large }) {
  const [failed, setFailed] = useState(false);
  const size = large ? "h-14 w-14" : small ? "h-7 w-7" : "h-8 w-8";
  if (failed) return (<div className={"grid shrink-0 place-items-center rounded-full bg-accent-soft text-accent " + size}><Ic d={SUPPORT_BOT_ICON} size={large ? 26 : small ? 14 : 16}/></div>);
  return (<img src={SUPPORT_AVATAR_SRC} alt="เอวา" onError={() => setFailed(true)} draggable={false} className={"shrink-0 rounded-full object-cover ring-2 ring-accent/30 " + size}/>);
}

function SupportBubble({ msg, onCopy, compact, feed, me }) {
  const mine = msg.role === "user";
  const fromOther = feed && mine && msg.asked_by && me && msg.asked_by !== me;
  const bubbleTone = fromOther ? "rounded-br-md border border-line bg-sunken text-fg" : mine ? "rounded-br-md bg-accent text-white" : msg.error ? "rounded-bl-md border text-fg" : "rounded-bl-md border border-line bg-surface text-fg";
  return (<div className={"flex items-end gap-2 " + (mine ? "justify-end" : "justify-start")}>
    {!mine && <SupportAvatar small={compact}/>}
    <div className={"flex flex-col " + (compact ? "max-w-[85%] " : "max-w-[80%] ") + (mine ? "items-end" : "items-start")}>
      {feed && mine && <div className="mb-0.5 px-1 text-[11px] font-semibold text-muted">{msg.asked_by && msg.asked_by === me ? "คุณ" : (msg.asked_by || "แอดมิน")}</div>}
      {mine && msg.images && msg.images.length > 0 && (<div className="mb-1 flex flex-wrap justify-end gap-1">{msg.images.map((src, i) => (<img key={i} src={src} alt="รูปที่แนบ" className={"rounded-lg border border-line object-cover " + (compact ? "h-14 w-14" : "h-20 w-20")}/>))}</div>)}
      <div className={"rounded-2xl text-sm shadow-sm " + (compact ? "px-3 py-2 " : "px-4 py-2.5 ") + bubbleTone} style={msg.error ? { borderColor: "var(--warn)", background: "var(--warn-soft)" } : null}>
        <div className="whitespace-pre-wrap break-words leading-relaxed">{msg.content}</div>
      </div>
      <div className="mt-1 flex items-center gap-2 px-1 text-[11px] text-faint">
        {msg.created_at && <span className="tnum">{supportTime(msg.created_at)}</span>}
        {!mine && !msg.error && (<button onClick={() => onCopy(msg.content)} className="flex items-center gap-1 rounded-md px-1 text-muted transition-colors hover:text-fg-2"><Ic d={I.copy} size={11}/> คัดลอก</button>)}
      </div>
    </div>
  </div>);
}

function SupportTyping({ compact }) {
  return (<div className="flex items-end gap-2">
    <SupportAvatar small={compact}/>
    <div className="flex items-center gap-2 rounded-2xl rounded-bl-md border border-line bg-surface px-4 py-3 shadow-sm">
      {[0, 150, 300].map(delay => (<span key={delay} className="h-1.5 w-1.5 animate-bounce rounded-full bg-accent" style={{ animationDelay: delay + "ms" }}/>))}
      <span className="ml-1 text-xs text-muted">กำลังตรวจสอบข้อมูล…</span>
    </div>
  </div>);
}

function SupportEmpty({ disabled, onPick, compact }) {
  return (<div className="flex h-full flex-col items-center justify-center px-4 py-8 text-center">
    <SupportAvatar large/>
    <div className="mt-3 text-base font-semibold text-fg">มีอะไรให้เอวาช่วยมั้ยคะ</div>
    <div className="mt-1 text-sm text-muted">ถามเรื่องลูกค้า วิธีใช้งานเมนู หรือให้ช่วยร่างข้อความตอบลูกค้า</div>
    {!compact && (<div className="mt-4 flex flex-wrap justify-center gap-2">{SUPPORT_EXAMPLES.map(ex => (<button key={ex} disabled={disabled} onClick={() => onPick(ex)} className="rounded-full border border-line bg-surface px-3 py-1.5 text-xs text-fg-2 transition-colors hover:border-accent hover:text-accent disabled:opacity-40">{ex}</button>))}</div>)}
  </div>);
}

function SupportMessages({ view, compact, onCopy, onPick, disabled, limit, feed }) {
  const scrollRef = useRef(null);
  const shown = limit ? view.msgs.slice(-limit) : view.msgs;
  useEffect(() => { const box = scrollRef.current; if (box) box.scrollTop = box.scrollHeight; }, [view.msgs, view.busy, view.loaded]);
  return (<div ref={scrollRef} className={"flex-1 overflow-y-auto overscroll-contain bg-sunken/30 " + (compact ? "px-3 py-4" : "px-4 py-5")}>
    {!view.loaded ? (<div className="space-y-4">{[0, 1, 2].map(i => (<div key={i} className={"skel h-12 rounded-2xl " + (i % 2 ? "ml-auto w-1/2" : "w-2/3")}/>))}</div>)
      : shown.length === 0 && !view.busy ? <SupportEmpty disabled={disabled} onPick={onPick} compact={compact}/>
      : (<div className={compact ? "space-y-3" : "space-y-4"}>
        {limit && view.msgs.length > limit && <div className="text-center text-[11px] text-faint">แสดง {limit} ข้อความล่าสุด</div>}
        {shown.map((m, i) => <SupportBubble key={m.id || "local-" + (view.msgs.length - shown.length + i)} msg={m} onCopy={onCopy} compact={compact} feed={feed} me={view.me}/>)}
        {view.busy && <SupportTyping compact={compact}/>}
      </div>)}
  </div>);
}

function SupportComposer({ composer, onSend, disabled, busy, placeholder, compact }) {
  const inputRef = useRef(null), fileRef = useRef(null);
  const { text, setText, images } = composer;
  useEffect(() => {
    const box = inputRef.current;
    if (!box) return;
    box.style.height = "auto";
    box.style.height = Math.min(box.scrollHeight, compact ? 110 : 160) + "px";
  }, [text]);
  useEffect(() => { if (!busy && !disabled && inputRef.current) inputRef.current.focus({ preventScroll: true }); }, [busy, disabled]);
  const canSend = !disabled && !busy && (text.trim() || images.length > 0);
  const onKey = (e) => { if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); if (canSend) onSend(); } };
  const onPaste = (e) => { const files = Array.from(e.clipboardData && e.clipboardData.files || []); if (files.some(file => /^image\//.test(file.type))) { e.preventDefault(); composer.addFiles(files); } };
  return (<div className={"border-t border-line bg-surface " + (compact ? "p-2" : "p-3")}>
    {images.length > 0 && (<div className="mb-2 flex flex-wrap gap-2 px-1">{images.map((image, i) => (<div key={i} className="relative">
      <img src={image.preview} alt="รูปที่จะส่ง" className="h-14 w-14 rounded-lg border border-line object-cover"/>
      <button onClick={() => composer.removeImage(i)} aria-label="เอารูปออก" className="absolute -right-1.5 -top-1.5 grid h-5 w-5 place-items-center rounded-full border border-line bg-surface text-fg-2 shadow-sm hover:text-fg"><Ic d={SUPPORT_CLOSE_ICON} size={10} sw={2.4}/></button>
    </div>))}</div>)}
    <div className="flex items-end gap-1.5 rounded-xl border border-line bg-sunken px-2 py-1.5 transition-colors focus-within:border-accent">
      {composer.imagesEnabled && (<>
        <input ref={fileRef} type="file" accept="image/*" multiple hidden onChange={e => { composer.addFiles(e.target.files); e.target.value = ""; }}/>
        <button onClick={() => fileRef.current && fileRef.current.click()} disabled={disabled || busy || images.length >= composer.maxImages} aria-label="แนบรูป" title={"แนบรูป (สูงสุด " + composer.maxImages + " รูป)"} className="grid h-9 w-9 shrink-0 place-items-center rounded-lg text-muted transition-colors hover:bg-surface hover:text-fg disabled:opacity-40"><Ic d={SUPPORT_CLIP_ICON} size={17}/></button>
      </>)}
      <textarea ref={inputRef} value={text} onChange={e => setText(e.target.value.slice(0, 2000))} onKeyDown={onKey} onPaste={onPaste} disabled={disabled} rows={1} enterKeyHint="send" placeholder={placeholder} className="min-h-[24px] flex-1 resize-none bg-transparent px-1 py-1.5 text-base leading-relaxed sm:text-sm text-fg outline-none placeholder:text-faint disabled:opacity-60"/>
      <button onClick={onSend} disabled={!canSend} aria-label="ส่งคำถาม" className="grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-accent text-white transition-opacity hover:opacity-90 disabled:opacity-40"><Ic d={SUPPORT_SEND_ICON} size={16} sw={2}/></button>
    </div>
    {!compact && (<div className="mt-1.5 flex justify-between px-1 text-[11px] text-faint">
      <span>Enter ส่ง · Shift+Enter ขึ้นบรรทัดใหม่{composer.imagesEnabled ? " · วางรูปด้วย Ctrl+V ได้" : ""}</span>
      {text.length > 1500 && <span className="tnum">{text.length}/2000</span>}
    </div>)}
  </div>);
}

// คัดลอกได้ทุกเบราว์เซอร์: ใช้ clipboard API ก่อน ถ้าไม่ได้ (เช่น เบราว์เซอร์เก่า/ไม่ใช่ https) ใช้ textarea ชั่วคราวแทน
function supportCopyFallback(text) {
  const box = document.createElement("textarea");
  box.value = text; box.setAttribute("readonly", ""); box.style.position = "fixed"; box.style.opacity = "0";
  document.body.appendChild(box); box.select(); box.setSelectionRange(0, text.length);
  const copied = document.execCommand("copy");
  document.body.removeChild(box);
  return copied;
}

function supportCopy(toast) {
  return (t) => {
    const done = () => toast("คัดลอกแล้ว");
    const fallback = () => (supportCopyFallback(t) ? done() : toast("คัดลอกไม่สำเร็จ"));
    try {
      if (navigator.clipboard && window.isSecureContext) navigator.clipboard.writeText(t).then(done, fallback);
      else fallback();
    } catch { fallback(); }
  };
}

function useSupportSend(view, status, composer, onAsk) {
  const disabled = !!(status && status.enabled === false);
  const send = (preset) => {
    if (disabled || view.busy) return;
    const payload = preset ? { question: preset, images: [] } : composer.take();
    if (!payload.question && !payload.images.length) return;
    onAsk(payload);
  };
  return { send, disabled };
}

function SupportStatusPill({ status }) {
  const [statusText, statusOk] = supportStatusLabel(status);
  return (<span className={"rounded-full px-2.5 py-1 text-[11px] font-semibold " + (status == null ? "bg-sunken text-muted" : statusOk ? "bg-accent-soft text-accent" : "text-warn")} style={status && !statusOk ? { background: "var(--warn-soft)" } : null}>{statusText}</span>);
}

// หน้ารวมอัปเดตเองทุก 30 วิ เฉพาะตอนแท็บนี้เปิดดูอยู่ (ไม่ดึงซ้ำตอนสลับไปแท็บอื่น)
function useSupportFeedPolling(toast) {
  useEffect(() => {
    const refresh = () => { if (document.visibilityState === "visible") supportLoadFeed(toast, true); };
    const timer = setInterval(refresh, SUPPORT_FEED_POLL_MS);
    document.addEventListener("visibilitychange", refresh);
    return () => { clearInterval(timer); document.removeEventListener("visibilitychange", refresh); };
  }, []);
}

/* ---------- หน้าเต็ม: เมนูสอบถามปัญหาระบบ (รวมทุกแอดมิน) ---------- */
function SupportAssistantPage({ toast }) {
  const view = useSupportChat(supportFeedChat, () => supportLoadFeed(toast, true));
  const status = useSupportStatus();
  const composer = useSupportComposer(toast, status);
  useSupportFeedPolling(toast);
  const { send, disabled } = useSupportSend(view, status, composer, (payload) => {
    supportAsk(supportFeedChat, { ...payload, sessionId: "page" }).then(() => supportLoadFeed(toast, true));
  });
  const [statusText] = supportStatusLabel(status);

  return (<div className="mx-auto flex h-[calc(100vh-210px)] min-h-[420px] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-line bg-surface shadow-sm supports-[height:100dvh]:h-[calc(100dvh-210px)]">
    <div className="flex items-center justify-between gap-3 border-b border-line px-4 py-3">
      <div className="flex min-w-0 items-center gap-3">
        <SupportAvatar/>
        <div className="min-w-0">
          <div className="text-sm font-semibold text-fg">เอวา · แชทรวมทีม</div>
          <div className="truncate text-xs text-muted">ถามตอบของแอดมินทุกคนในเว็บนี้ 100 ข้อความล่าสุด</div>
        </div>
      </div>
      <SupportStatusPill status={status}/>
    </div>
    <SupportMessages view={view} onCopy={supportCopy(toast)} onPick={send} disabled={disabled} feed/>
    <SupportComposer composer={composer} onSend={() => send()} disabled={disabled} busy={view.busy}
      placeholder={disabled ? "เอวา" + statusText : "พิมพ์ถามเอวาได้เลย เช่น 0812345678 ฝากไม่เข้า"}/>
  </div>);
}

/* ---------- กล่องผู้ช่วยติดตาม: ลากย้ายได้ ตามไปทุกเมนู ของใครของมัน ปิดแล้วเปิดใหม่ = เริ่มใหม่ ---------- */
const SUPPORT_WIDGET_KEY = "nx-support-widget";
const SUPPORT_WIDGET_SIZE = { w: 380, h: 560 };
const supportWidgetHeight = () => Math.max(320, Math.min(SUPPORT_WIDGET_SIZE.h, window.innerHeight - 16));
const supportWidgetState = (() => {
  let saved = {};
  try { saved = JSON.parse(localStorage.getItem(SUPPORT_WIDGET_KEY) || "{}") || {}; } catch {}
  const session = typeof saved.session === "string" && /^w-[a-z0-9]{8,32}$/.test(saved.session) ? saved.session : null;
  return { open: !!saved.open && !!session, session, x: Number.isFinite(saved.x) ? saved.x : null, y: Number.isFinite(saved.y) ? saved.y : null, listeners: new Set() };
})();

function supportWidgetSet(patch) {
  Object.assign(supportWidgetState, patch);
  const { open, session, x, y } = supportWidgetState;
  try { localStorage.setItem(SUPPORT_WIDGET_KEY, JSON.stringify({ open, session, x, y })); } catch {}
  supportWidgetState.listeners.forEach(listener => listener({ open, session, x, y }));
}

// เปิด = รอบใหม่ (กล่องว่าง เอวาเริ่มคุยใหม่) / ปิด = ทิ้งรอบนี้
function supportWidgetToggle(open) {
  const chat = supportChatSession(supportWidgetChat);
  const session = open ? supportNewSessionId() : null;
  Object.assign(chat, { session, msgs: [], busy: false, loaded: !!open, loading: false });
  supportChatUpdate(chat, {});
  supportWidgetSet({ open: !!open, session });
}

function useSupportWidget() {
  const [state, setState] = useState(() => ({ open: supportWidgetState.open, session: supportWidgetState.session, x: supportWidgetState.x, y: supportWidgetState.y }));
  useEffect(() => { supportWidgetState.listeners.add(setState); return () => { supportWidgetState.listeners.delete(setState); }; }, []);
  return state;
}

function supportClampPosition(x, y) {
  const maxX = Math.max(8, window.innerWidth - SUPPORT_WIDGET_SIZE.w - 8);
  const maxY = Math.max(8, window.innerHeight - supportWidgetHeight() - 8);
  const fallbackX = window.innerWidth - SUPPORT_WIDGET_SIZE.w - 24;
  const fallbackY = window.innerHeight - supportWidgetHeight() - 24;
  return { x: Math.min(Math.max(8, x == null ? fallbackX : x), maxX), y: Math.min(Math.max(8, y == null ? fallbackY : y), maxY) };
}

function SupportLiveDot({ ok }) {
  return (<span className="relative flex h-2.5 w-2.5">
    {ok && <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75"/>}
    <span className={"relative inline-flex h-2.5 w-2.5 rounded-full " + (ok ? "bg-emerald-500" : "bg-amber-500")}/>
  </span>);
}

function SupportWidgetLauncher() {
  const widget = useSupportWidget();
  if (!can("tool_support_assistant")) return null;
  return (<button onClick={() => supportWidgetToggle(!widget.open)} title={widget.open ? "ปิดผู้ช่วยติดตาม" : "เรียกผู้ช่วยติดตาม (เอวา)"} aria-pressed={widget.open}
    className={"flex h-10 shrink-0 items-center gap-2 rounded-xl border px-4 text-sm font-semibold shadow-sm transition-colors " + (widget.open ? "border-accent bg-accent text-white" : "border-accent bg-accent-soft text-accent hover:bg-accent hover:text-white")}>
    <Ic d={SUPPORT_BOT_ICON} size={17}/><span>ผู้ช่วยติดตาม</span>
  </button>);
}

// มือถือ (กว้าง < 640): กล่องเป็นแผ่นล่างจอ ยกขึ้นตามคีย์บอร์ด (visualViewport) และเว้นขอบ safe-area ของ iPhone
function supportViewportBox() {
  const vv = window.visualViewport;
  const viewHeight = vv ? vv.height : window.innerHeight;
  const keyboardGap = vv ? Math.max(0, window.innerHeight - (vv.offsetTop + vv.height)) : 0;
  return {
    isMobile: window.innerWidth < 640,
    bottom: keyboardGap > 0 ? keyboardGap + 8 : "calc(8px + env(safe-area-inset-bottom, 0px))",
    sheetHeight: Math.round(Math.min(viewHeight - 16, Math.max(320, viewHeight * (keyboardGap > 0 ? 0.92 : 0.72)))),
  };
}

function useSupportViewport() {
  const [box, setBox] = useState(supportViewportBox);
  useEffect(() => {
    let frameId = 0;
    const update = () => { cancelAnimationFrame(frameId); frameId = requestAnimationFrame(() => setBox(supportViewportBox())); };
    const vv = window.visualViewport;
    window.addEventListener("resize", update);
    window.addEventListener("orientationchange", update);
    if (vv) { vv.addEventListener("resize", update); vv.addEventListener("scroll", update); }
    return () => {
      cancelAnimationFrame(frameId);
      window.removeEventListener("resize", update);
      window.removeEventListener("orientationchange", update);
      if (vv) { vv.removeEventListener("resize", update); vv.removeEventListener("scroll", update); }
    };
  }, []);
  return box;
}

function useSupportWidgetDrag(widget, isMobile) {
  const [pos, setPos] = useState(() => supportClampPosition(widget.x, widget.y));
  const dragRef = useRef(null), posRef = useRef(pos);
  posRef.current = pos;
  useEffect(() => {
    const onResize = () => setPos(current => supportClampPosition(current.x, current.y));
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);
  const onPointerDown = (e) => {
    if (isMobile || e.button !== 0 || e.target.closest("button")) return;
    dragRef.current = { dx: e.clientX - posRef.current.x, dy: e.clientY - posRef.current.y };
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onPointerMove = (e) => {
    if (!dragRef.current) return;
    posRef.current = supportClampPosition(e.clientX - dragRef.current.dx, e.clientY - dragRef.current.dy);
    setPos(posRef.current);
  };
  const onPointerUp = () => { if (!dragRef.current) return; dragRef.current = null; supportWidgetSet({ x: posRef.current.x, y: posRef.current.y }); };
  return { pos, handlers: { onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp } };
}

function SupportWidgetPanel({ page, pageTitle, toast, onNav }) {
  const widget = useSupportWidget();
  const view = useSupportChat(supportWidgetChat, () => supportLoadWidget(widget.session));
  const status = useSupportStatus();
  const composer = useSupportComposer(toast, status);
  const { send, disabled } = useSupportSend(view, status, composer, (payload) => {
    supportAsk(supportWidgetChat, { ...payload, sessionId: widget.session, page: { key: page, label: pageTitle } });
  });
  const box = useSupportViewport();
  const isMobile = box.isMobile;
  const { pos, handlers } = useSupportWidgetDrag(widget, isMobile);
  const [statusText, statusOk] = supportStatusLabel(status);
  const frame = isMobile ? { left: 8, right: 8, bottom: box.bottom, height: box.sheetHeight } : { left: pos.x, top: pos.y, width: SUPPORT_WIDGET_SIZE.w, height: supportWidgetHeight() };

  return (<div role="dialog" aria-label="เอวา ผู้ช่วยติดตาม" className="pop fixed z-[70] flex flex-col overflow-hidden rounded-2xl border border-line bg-surface shadow-lg" style={frame}>
    <div {...handlers} className={"flex select-none items-center gap-2.5 border-b border-line px-3 py-2.5 " + (isMobile ? "" : "cursor-move")} style={{ touchAction: "none" }}>
      <SupportAvatar small/>
      <div className="min-w-0 flex-1">
        <div className="text-sm font-semibold leading-tight text-fg">เอวา</div>
        <div className="flex items-center gap-1.5 text-[11px] text-muted"><SupportLiveDot ok={statusOk}/><span className="truncate">{statusOk ? "ทำงานอยู่" : statusText} · {pageTitle}</span></div>
      </div>
      <button onClick={() => onNav && onNav("support")} title="ดูแชทรวมทีม (เมนูสอบถามปัญหาระบบ)" aria-label="ดูแชทรวมทีม" className="grid h-8 w-8 place-items-center rounded-lg text-muted transition-colors hover:bg-sunken hover:text-fg"><Ic d={SUPPORT_EXPAND_ICON} size={15}/></button>
      <button onClick={() => supportWidgetToggle(false)} title="ปิด (เปิดใหม่จะเริ่มแชทใหม่)" aria-label="ปิดผู้ช่วยติดตาม" className="grid h-8 w-8 place-items-center rounded-lg text-muted transition-colors hover:bg-sunken hover:text-fg"><Ic d={SUPPORT_CLOSE_ICON} size={16}/></button>
    </div>
    <SupportMessages view={view} onCopy={supportCopy(toast)} onPick={send} disabled={disabled} compact limit={SUPPORT_WIDGET_MESSAGES}/>
    <SupportComposer composer={composer} onSend={() => send()} disabled={disabled} busy={view.busy} compact placeholder={"ถามเอวาเรื่องหน้า " + pageTitle + " หรือเรื่องลูกค้า…"}/>
  </div>);
}

function SupportAssistantWidget({ page, pageTitle, toast, onNav }) {
  const widget = useSupportWidget();
  if (!widget.open || !widget.session || !can("tool_support_assistant")) return null;
  return <SupportWidgetPanel key={widget.session} page={page} pageTitle={pageTitle} toast={toast} onNav={onNav}/>;
}

/* ---------- ตั้งค่า AI ตอบปัญหา — /support-assistant/config|connect ----------
 * หน้าเดียวจบ: สถานะ + ช่องวางคีย์เชื่อมต่อที่ได้จากทีมพัฒนา */
const SUPPORT_INPUT = "w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm";

function SupportAiSettingsPage({ toast }) {
  const [saved, setSaved] = useState(null), [keyText, setKeyText] = useState(""), [busy, setBusy] = useState(false), [err, setErr] = useState(null), [result, setResult] = useState("");
  const load = useCallback(async () => {
    setErr(null);
    try { setSaved(await api("/support-assistant/config")); }
    catch (e) { if (e.status === 401) { window.__nxAuthFail && window.__nxAuthFail(); } setErr(e.status === 403 ? "ไม่มีสิทธิ์ใช้เมนูนี้" : (e.message || "โหลดไม่สำเร็จ")); }
  }, []);
  useEffect(() => { load(); }, [load]);
  const connect = async () => {
    setBusy(true); setResult("");
    try {
      setSaved(await api("/support-assistant/connect", { method: "POST", body: { connection_key: keyText.trim() } }));
      setKeyText("");
      const r = await api("/support-assistant/config/test", { method: "POST", body: {} });
      const text = r.ok && r.subscription ? (r.subscription.active ? "เชื่อมต่อสำเร็จ พร้อมใช้งาน" : "เชื่อมต่อแล้ว แต่เว็บนี้ถูกระงับ ติดต่อทีมพัฒนา") : "บันทึกคีย์แล้ว แต่เชื่อมต่อไม่สำเร็จ ติดต่อทีมพัฒนา";
      setResult(text); toast(text);
    } catch (e) { toast(SUPPORT_ERR_TEXT[e.data && e.data.error] || "เชื่อมต่อไม่สำเร็จ"); }
    finally { setBusy(false); }
  };
  if (err) return <HistErr msg={err} onRetry={load}/>;
  if (!saved) return <div className="flex items-center justify-center gap-2 py-16 text-sm text-muted"><Ic d={I.refresh} size={16} cls="animate-spin"/> กำลังโหลด…</div>;
  const connected = saved.mode !== "off";
  return (<div className="mx-auto max-w-2xl space-y-3 rounded-xl border border-line bg-surface p-5 shadow-sm">
    <div className="text-sm text-fg-2">สถานะ: <span className={"font-semibold " + (connected ? "text-success" : "text-warn")}>{connected ? "เชื่อมต่อแล้ว" : "ยังไม่ได้เชื่อมต่อ"}</span></div>
    <textarea value={keyText} onChange={e => setKeyText(e.target.value)} rows={3} autoComplete="off" spellCheck={false} placeholder="วางคีย์ที่ได้จากทีมพัฒนา (AIC1-...)" className={SUPPORT_INPUT + " mono resize-none break-all"}/>
    {result && <div className="text-xs text-muted">{result}</div>}
    <div className="flex justify-end"><button onClick={connect} disabled={busy || !keyText.trim().startsWith("AIC1-")} className="h-9 rounded-lg bg-accent px-5 text-sm font-semibold text-white hover:opacity-90 disabled:opacity-50">{busy ? "กำลังเชื่อมต่อ…" : "เชื่อมต่อ"}</button></div>
  </div>);
}
