/* ==========================================================================
 * ADMIN NEXT — page-manual.jsx  (คู่มือการใช้งานระบบ: GET /system-manual)
 * ฝั่งแอดมิน = หัวข้อเดียวกับที่ผู้ช่วยใช้ (src/services/supportAssistantGuide.js)
 * ฝั่งผู้เล่น = src/services/playerGuide.js + รูปใน admin/assets/manual/player/
 * ========================================================================== */

const MANUAL_GENERAL_CHAPTER = "เริ่มต้นใช้งาน";
const MANUAL_IMAGE_BASE = "/admin/assets/manual/player/";

function manualNavIndex() {
  const index = {};
  for (const sec of NAV) for (const it of sec.items) {
    if (it.page) { index[it.page] = { section: sec.g, group: it, child: null, chapter: sec.g }; continue; }
    for (const c of it.children) index[c[1]] = { section: sec.g, group: it, child: c, chapter: it.label };
  }
  return index;
}

function manualMatches(topic, needle) {
  if (!needle) return true;
  const hay = [topic.title, topic.path, topic.summary, ...(topic.steps || []), ...(topic.notes || [])].join(" ").toLowerCase();
  return needle.split(/\s+/).filter(Boolean).every((w) => hay.includes(w));
}

function manualAdminChapters(topics, navIndex) {
  const order = [MANUAL_GENERAL_CHAPTER];
  const byChapter = { [MANUAL_GENERAL_CHAPTER]: [] };
  for (const sec of NAV) for (const it of sec.items) {
    const name = it.page ? sec.g : it.label;
    if (!byChapter[name]) { byChapter[name] = []; order.push(name); }
  }
  topics.forEach((topic, i) => {
    const loc = navIndex[topic.page];
    const name = loc ? loc.chapter : MANUAL_GENERAL_CHAPTER;
    byChapter[name].push({ ...topic, id: "a-" + i, loc });
  });
  return order.filter((name) => byChapter[name].length).map((name) => ({ name, topics: byChapter[name] }));
}

function manualPlayerChapters(topics) {
  const order = [];
  const byChapter = {};
  for (const topic of topics) {
    const name = topic.group || "ทั่วไป";
    if (!byChapter[name]) { byChapter[name] = []; order.push(name); }
    byChapter[name].push({ ...topic, id: "p-" + topic.id });
  }
  return order.map((name) => ({ name, topics: byChapter[name] }));
}

function manualFilterChapters(chapters, needle) {
  return chapters.map((ch) => ({ ...ch, topics: ch.topics.filter((t) => manualMatches(t, needle)) })).filter((ch) => ch.topics.length);
}

function manualJump(id) {
  const el = document.getElementById("manual-" + id);
  if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
}

/* ภาพประกอบ: เมนูด้านซ้ายจำลอง ชี้ตำแหน่งที่ต้องกด */
function ManualMenuMap({ loc }) {
  const { section, group, child } = loc;
  const target = "rounded-md px-2 py-1 font-semibold text-accent ring-2 ring-[var(--accent)]";
  return (<div className="w-full rounded-xl border border-line bg-surface p-3 shadow-sm sm:w-56">
    <div className="mb-2 flex items-center gap-1.5 text-[10px] font-semibold tracking-wider text-faint"><span className="h-1.5 w-1.5 rounded-full bg-accent"/>เมนูด้านซ้าย</div>
    <div className="px-1 pb-1 text-[10px] font-semibold tracking-wider text-faint">{section}</div>
    <div className={"flex items-center gap-2 text-xs " + (child ? "rounded-md px-2 py-1 font-medium text-fg-2" : target)} style={child ? null : { background: "var(--accent-soft)" }}>
      <NavChip icon={group.icon} col={group.col} active={false}/><span className="min-w-0 flex-1 truncate">{group.label}</span>
      {child ? <Ic d={I.chevD} size={13} cls="rotate-180 text-faint"/> : <span className="shrink-0 rounded-full bg-accent px-1.5 py-0.5 text-[9px] font-bold text-accent-fg">กดที่นี่</span>}
    </div>
    {child && <div className="ml-5 mt-1 space-y-0.5 border-l border-line pl-2.5">
      {group.children.map((c) => c[1] === child[1]
        ? <div key={c[1]} className={"flex items-center gap-1.5 text-[11px] " + target} style={{ background: "var(--accent-soft)" }}><span className="min-w-0 flex-1 truncate">{c[0]}</span><span className="shrink-0 rounded-full bg-accent px-1.5 py-0.5 text-[9px] font-bold text-accent-fg">กดที่นี่</span></div>
        : <div key={c[1]} className="truncate px-2 py-0.5 text-[11px] text-muted">{c[0]}</div>)}
    </div>}
  </div>);
}

function ManualSteps({ steps }) {
  if (!steps.length) return null;
  return (<ol className="min-w-0 flex-1 space-y-2">
    {steps.map((step, i) => (<li key={i} className="flex gap-3 text-sm leading-relaxed text-fg-2">
      <span className="grid h-6 w-6 shrink-0 place-items-center rounded-full text-[11px] font-bold text-white" style={{ background: "var(--accent)" }}>{i + 1}</span>
      <span className="min-w-0 pt-0.5">{step}</span>
    </li>))}
  </ol>);
}

function ManualNotes({ notes }) {
  if (!notes.length) return null;
  return (<div className="mt-4 rounded-lg border border-line p-3" style={{ background: "var(--warn-soft)" }}>
    <div className="mb-1.5 flex items-center gap-1.5 text-xs font-bold" style={{ color: "var(--warn)" }}><Ic d={I.warn2} size={14}/>ข้อควรรู้</div>
    <ul className="space-y-1 text-[13px] leading-relaxed text-fg-2">{notes.map((n, i) => <li key={i} className="flex gap-2"><span className="mt-2 h-1 w-1 shrink-0 rounded-full" style={{ background: "var(--warn)" }}/><span>{n}</span></li>)}</ul>
  </div>);
}

function ManualPhoneShot({ src, title, onZoom }) {
  return (<button type="button" onClick={() => onZoom(src)} className="group mx-auto block w-48 shrink-0 sm:mx-0" title="แตะเพื่อขยาย">
    <div className="overflow-hidden rounded-[26px] border-[5px] border-[#14161c] bg-black shadow-lg transition-transform duration-200 group-hover:-translate-y-0.5">
      <img src={src} alt={title} loading="lazy" className="block w-full" onError={(e) => { e.currentTarget.closest("button").style.display = "none"; }}/>
    </div>
    <div className="mt-1.5 flex items-center justify-center gap-1 text-[11px] text-muted"><Ic d={I.search} size={11}/>แตะเพื่อขยาย</div>
  </button>);
}

function ManualTopicCard({ topic, side, onNav, onZoom }) {
  const canOpen = side === "admin" && topic.page && topic.loc && nxPageAllowed(topic.page);
  const locked = side === "admin" && topic.page && topic.loc && !nxPageAllowed(topic.page);
  const image = side === "player" && topic.image ? MANUAL_IMAGE_BASE + topic.image : "";
  return (<article id={"manual-" + topic.id} className="scroll-mt-4 rounded-xl border border-line bg-surface p-4 shadow-sm sm:p-5">
    <div className="flex flex-wrap items-start gap-2">
      <h3 className="min-w-0 flex-1 text-base font-bold tracking-tight text-fg">{topic.title}</h3>
      {canOpen && <button type="button" onClick={() => onNav(topic.page, topic.title)} className="inline-flex items-center gap-1 rounded-lg border border-line px-2.5 py-1 text-xs font-semibold text-accent transition-colors hover:bg-accent-soft">เปิดหน้านี้<Ic d={I.chevR} size={13}/></button>}
      {locked && <Badge tone="warn">ยังไม่มีสิทธิ์เมนูนี้</Badge>}
    </div>
    {topic.path && <div className="mt-1.5 flex flex-wrap items-center gap-1 text-[11px] text-muted">{topic.path.split(">").map((part, i) => <React.Fragment key={i}>{i > 0 && <Ic d={I.chevR} size={11} cls="text-faint"/>}<span className="rounded bg-sunken px-1.5 py-0.5">{part.trim()}</span></React.Fragment>)}</div>}
    {topic.summary && <p className="mt-2.5 text-sm leading-relaxed text-fg-2">{topic.summary}</p>}
    <div className="mt-4 flex flex-col gap-4 sm:flex-row sm:items-start">
      {topic.loc && <ManualMenuMap loc={topic.loc}/>}
      {image && <ManualPhoneShot src={image} title={topic.title} onZoom={onZoom}/>}
      <ManualSteps steps={topic.steps}/>
    </div>
    <ManualNotes notes={topic.notes}/>
  </article>);
}

function ManualToc({ chapters }) {
  return (<nav className="rounded-xl border border-line bg-surface p-2 shadow-sm">
    {chapters.map((ch) => (<div key={ch.name} className="mb-1">
      <button type="button" onClick={() => manualJump("ch-" + ch.name)} className={"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] font-semibold transition-colors " + "text-fg-2 hover:bg-sunken"}>
        <span className="min-w-0 flex-1 truncate">{ch.name}</span><span className="text-[11px] font-medium text-faint">{ch.topics.length}</span>
      </button>
    </div>))}
  </nav>);
}

function ManualZoom({ src, onClose }) {
  useEffect(() => { const k = (e) => { if (e.key === "Escape") onClose(); }; window.addEventListener("keydown", k); return () => window.removeEventListener("keydown", k); }, [onClose]);
  return (<div className="fixed inset-0 z-[80] flex items-center justify-center p-4 fade-in" onMouseDown={onClose}>
    <div className="absolute inset-0 bg-black/75"/>
    <div className="pop relative" onMouseDown={(e) => e.stopPropagation()}>
      <button type="button" onClick={onClose} className="absolute -right-2 -top-2 z-10 grid h-8 w-8 place-items-center rounded-full border border-line bg-surface text-muted shadow"><Ic d={I.x} size={15}/></button>
      <img src={src} alt="ภาพประกอบ" className="max-h-[88vh] w-auto rounded-2xl border-[6px] border-[#14161c] shadow-2xl"/>
    </div>
  </div>);
}

function ManualSideSwitch({ side, setSide, counts }) {
  const tabs = [["admin", "ฝั่งแอดมิน (หลังบ้าน)", counts.admin], ["player", "ฝั่งผู้เล่น (หน้าเว็บ)", counts.player]];
  return (<div className="inline-flex rounded-xl border border-line bg-sunken p-1">
    {tabs.map(([key, label, n]) => (<button key={key} type="button" onClick={() => setSide(key)} className={"rounded-lg px-3 py-1.5 text-sm font-semibold transition-colors " + (side === key ? "bg-surface text-accent shadow-sm" : "text-muted hover:text-fg")}>
      {label}<span className="ml-1.5 text-[11px] font-medium text-faint">{n}</span>
    </button>))}
  </div>);
}

function ManualPage({ onNav }) {
  const [manual, setManual] = useState(null);
  const [failed, setFailed] = useState(false);
  const [side, setSide] = useState("admin");
  const [query, setQuery] = useState("");
  const [zoom, setZoom] = useState("");
  const navIndex = useMemo(manualNavIndex, []);

  const load = useCallback(() => {
    setFailed(false);
    api("/system-manual").then(setManual).catch(() => setFailed(true));
  }, []);
  useEffect(load, [load]);

  const chapters = useMemo(() => {
    if (!manual) return [];
    const all = side === "admin" ? manualAdminChapters(manual.admin, navIndex) : manualPlayerChapters(manual.player);
    return manualFilterChapters(all, query.trim().toLowerCase());
  }, [manual, side, query, navIndex]);

  if (failed) return (<div className="rounded-xl border border-dashed border-line bg-surface px-4 py-14 text-center"><div className="text-sm text-fg-2">โหลดคู่มือไม่สำเร็จ</div><button type="button" onClick={load} className="mt-3 rounded-lg border border-line px-3 py-1.5 text-xs font-semibold text-accent hover:bg-accent-soft">ลองอีกครั้ง</button></div>);
  if (!manual) return (<div className="flex items-center gap-2 py-10 text-sm text-muted"><Ic d={I.refresh} size={16} cls="animate-spin"/>กำลังโหลดคู่มือ…</div>);

  const counts = { admin: manual.admin.length, player: manual.player.length };
  return (<div>
    <div className="mb-4 flex flex-wrap items-center gap-3">
      <ManualSideSwitch side={side} setSide={setSide} counts={counts}/>
      <div className="relative min-w-[200px] flex-1 sm:max-w-sm">
        <Ic d={I.search} size={15} cls="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-faint"/>
        <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="ค้นหาในคู่มือ เช่น ถอน, สลิป, โปร" className="h-9 w-full rounded-lg border border-line bg-surface pl-9 pr-3 text-sm text-fg placeholder:text-faint focus:border-[var(--accent)] focus:outline-none"/>
      </div>
    </div>
    {side === "player" && <div className="mb-4 rounded-lg border border-line p-3 text-[13px] leading-relaxed text-fg-2" style={{ background: "var(--info-soft)" }}>ภาพประกอบถ่ายจากหน้าเว็บเทมเพลตแบบ 1 บนมือถือ ถ้าเว็บตั้งแบบ 2 หรือ 3 หน้าตาและตำแหน่งปุ่มจะต่างไปเล็กน้อย แต่ขั้นตอนเหมือนกัน</div>}
    {!chapters.length ? <div className="rounded-xl border border-dashed border-line bg-surface px-4 py-14 text-center text-sm text-muted">ไม่พบหัวข้อที่ตรงกับ “{query}”</div> : (
      <div className="grid gap-5 lg:grid-cols-[240px_minmax(0,1fr)]">
        <aside className="hidden lg:block"><div className="sticky top-0 max-h-[calc(100vh-180px)] overflow-y-auto"><ManualToc chapters={chapters}/></div></aside>
        <div className="min-w-0 space-y-8">
          <div className="-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 lg:hidden">{chapters.map((ch) => <button key={ch.name} type="button" onClick={() => manualJump("ch-" + ch.name)} className="shrink-0 rounded-full border border-line bg-surface px-3 py-1 text-xs font-semibold text-fg-2">{ch.name}</button>)}</div>
          {chapters.map((ch) => (<section key={ch.name} id={"manual-ch-" + ch.name} className="scroll-mt-4">
            <h2 className="mb-3 flex items-center gap-2 text-lg font-bold tracking-tight"><span className="h-5 w-1.5 rounded-full bg-accent"/>{ch.name}<span className="text-xs font-medium text-faint">{ch.topics.length} หัวข้อ</span></h2>
            <div className="space-y-3">{ch.topics.map((topic) => <ManualTopicCard key={topic.id} topic={topic} side={side} onNav={onNav} onZoom={setZoom}/>)}</div>
          </section>))}
        </div>
      </div>)}
    {zoom && <ManualZoom src={zoom} onClose={() => setZoom("")}/>}
  </div>);
}
