/* ---------- ตั้งค่า bot สรุปยอดรายวันแจ้งเตือน Telegram — /daily-report/* ----------
 * บอท/กลุ่มแยกจากหน้า "การแจ้งเตือน" ส่งยอดเมื่อวานวันละครั้งตามเวลาที่ตั้ง
 * ติ๊กเลือกหัวข้อที่จะแสดงได้ (รายการหัวข้อมาจากเซิร์ฟ groups) + พรีวิวข้อความจากยอดจริงของเมื่อวานทันทีที่ติ๊ก
 * ชื่อ global ในไฟล์นี้ขึ้นต้นด้วย dailyReport / DailyReport กันชนกับไฟล์อื่น (ทุกไฟล์ nx อยู่ scope เดียวกัน) */
const DAILY_REPORT_ERR_TEXT = {
  daily_report_time_invalid: "เวลาไม่ถูกต้อง (รูปแบบ 00:00–23:59)",
  daily_report_chat_id_invalid: "Chat ID ไม่ถูกต้อง ต้องเป็นตัวเลข เช่น -1001234567890 หรือ @ชื่อช่อง",
  daily_report_token_invalid: "Bot Token ไม่ถูกต้อง ตรวจว่าคัดลอกจาก @BotFather มาครบ",
  daily_report_missing_target: "ต้องใส่ Bot Token และ Chat ID ก่อนเปิดใช้งาน",
  daily_report_fields_empty: "ต้องติ๊กหัวข้อที่จะแสดงอย่างน้อย 1 หัวข้อ",
  daily_report_telegram_unreachable: "เชื่อมต่อ Telegram ไม่ได้ ลองใหม่อีกครั้ง",
  daily_report_telegram_rejected: "Telegram ปฏิเสธข้อความ",
  invalid_request: "ข้อมูลไม่ครบ",
};
const DAILY_REPORT_PREVIEW_DELAY_MS = 350;

function dailyReportErrText(code, detail) {
  const text = DAILY_REPORT_ERR_TEXT[code] || code || "ทำรายการไม่สำเร็จ";
  return detail ? `${text} (${detail})` : text;
}

function dailyReportSameFields(left, right) {
  return left.length === right.length && left.every(key => right.includes(key));
}

function DailyReportFieldGroup({ group, picked, onToggle, onToggleGroup }) {
  const keys = group.fields.map(field => field.key);
  const allOn = keys.every(key => picked.includes(key));
  return (<div className="rounded-xl border border-line bg-surface p-4 shadow-sm">
    <div className="mb-3 flex items-center gap-2">
      <span className="text-base leading-none">{group.icon}</span>
      <div className="text-sm font-semibold text-fg">{group.title}</div>
      {keys.length > 1 && <button type="button" onClick={() => onToggleGroup(keys, !allOn)} className="ml-auto rounded-md px-2 py-1 text-[11px] font-medium text-accent transition-colors duration-150 hover:bg-sunken">{allOn ? "ไม่เลือกทั้งหมด" : "เลือกทั้งหมด"}</button>}
    </div>
    <div className="grid gap-2 sm:grid-cols-2">
      {group.fields.map(field => {
        const on = picked.includes(field.key);
        return (<label key={field.key} className={"flex cursor-pointer items-start gap-2.5 rounded-lg border px-3 py-2 transition-colors duration-150 " + (on ? "border-accent/60 bg-accent/10" : "border-line hover:bg-sunken/60")}>
          <input type="checkbox" checked={on} onChange={() => onToggle(field.key)} className="mt-0.5 h-4 w-4 shrink-0 accent-[var(--accent)]"/>
          <span className="min-w-0"><span className="block text-sm text-fg">{field.label}</span>{field.hint && <span className="block text-[11px] text-muted">{field.hint}</span>}</span>
        </label>);
      })}
    </div>
  </div>);
}

const DAILY_REPORT_HOWTO_STEPS = [
  ["สร้างบอท", <>ใน Telegram ค้นหา <b className="text-fg">@BotFather</b> พิมพ์ <code className="mono text-fg">/newbot</code> ตั้งชื่อบอท แล้วคัดลอก <b className="text-fg">Bot Token</b> (หน้าตาแบบ 123456789:AAH...) มาวางช่อง Token</>],
  ["เอาบอทเข้ากลุ่ม", <>สร้างกลุ่มหรือใช้กลุ่มเจ้าของ เพิ่มบอทเข้ากลุ่ม แล้วพิมพ์ข้อความอะไรก็ได้ในกลุ่ม 1 ครั้ง</>],
  ["หา Chat ID", <>เปิดในเบราว์เซอร์ <code className="mono break-all text-fg">https://api.telegram.org/bot&lt;TOKEN&gt;/getUpdates</code> (ใส่ token แทน &lt;TOKEN&gt;) ดูตัวเลขหลัง <code className="mono text-fg">"chat":{"{"}"id":</code> กลุ่มมักขึ้นต้นด้วย <b className="text-fg">-100</b> มาวางช่อง Chat ID</>],
  ["บันทึก", <>ตั้งเวลาส่ง ติ๊กหัวข้อที่ต้องการ ดูตัวอย่างด้านขวา แล้วกด <b className="text-fg">บันทึก</b></>],
  ["ทดสอบแล้วเปิดใช้", <>กด <b className="text-fg">ส่งทดสอบตอนนี้</b> (ยอดวันนี้ 00:00 ถึงตอนนี้) หรือ <b className="text-fg">ส่งทดสอบ (ยอดเมื่อวาน)</b> ระบบส่งเข้ากลุ่มทันที ข้อความเข้ากลุ่มแล้ว เปิดสวิตช์ <b className="text-fg">เปิดส่งสรุปยอดรายวัน</b> ระบบส่งทุกวันตามเวลาที่ตั้ง</>],
];

function DailyReportHowTo({ defaultOpen }) {
  const [open, setOpen] = useState(!!defaultOpen);
  return (<div className="rounded-lg border border-line bg-sunken/40">
    <button type="button" onClick={() => setOpen(!open)} aria-expanded={open} className="flex w-full items-center gap-2 px-3 py-2.5 text-left transition-colors duration-150 hover:bg-sunken/60">
      <span className="grid h-6 w-6 place-items-center rounded-full bg-accent/15 text-xs font-bold text-accent">?</span>
      <span className="text-sm font-medium text-fg">วิธีเชื่อมต่อ Telegram</span>
      <span className="text-[11px] text-muted">5 ขั้นตอน</span>
      <span className={"ml-auto text-muted transition-transform duration-200 " + (open ? "rotate-180" : "")}><Ic d={I.chevD} size={16}/></span>
    </button>
    {open && <div className="space-y-3 border-t border-line px-3 py-3 text-xs text-muted">
      <ol className="space-y-2.5">
        {DAILY_REPORT_HOWTO_STEPS.map(([title, body], index) => (<li key={title} className="flex gap-2.5">
          <span className="grid h-5 w-5 shrink-0 place-items-center rounded-full bg-accent text-[11px] font-bold text-accent-fg">{index + 1}</span>
          <div className="min-w-0 leading-relaxed"><span className="font-semibold text-fg">{title}:</span> {body}</div>
        </li>))}
      </ol>
      <div className="rounded-lg border border-line bg-surface px-3 py-2 leading-relaxed">
        <div className="mb-1 font-semibold text-fg">ส่งไม่เข้า? ดู "ส่งไม่สำเร็จล่าสุด" ด้านบน</div>
        <div>• <code className="mono text-fg">401</code> = Token ผิด</div>
        <div>• <code className="mono text-fg">chat not found</code> = Chat ID ผิด หรือบอทยังไม่อยู่ในกลุ่ม</div>
      </div>
      <div>สิทธิ์: owner เห็นเมนูนี้อัตโนมัติ แอดมินคนอื่นต้องติ๊กสิทธิ์ "ตั้งค่า bot สรุปยอดรายวันแจ้งเตือน Telegram" ก่อน</div>
    </div>}
  </div>);
}

function DailyReportPreview({ preview, loading }) {
  return (<div className="overflow-hidden rounded-xl border border-line shadow-sm lg:sticky lg:top-4">
    <div className="flex items-center gap-2.5 bg-[#17212B] px-4 py-3 text-white">
      <span className="grid h-8 w-8 place-items-center rounded-full bg-[#2AABEE] text-sm font-bold">B</span>
      <div className="min-w-0"><div className="truncate text-sm font-semibold">ตัวอย่างข้อความ Telegram</div><div className="text-[11px] text-white/60">{preview.date ? `ยอดจริงของวันที่ ${preview.date} (เมื่อวาน)` : "กำลังเตรียมตัวอย่าง…"}</div></div>
      {loading && <Ic d={I.refresh} size={14} cls="ml-auto animate-spin text-white/70"/>}
    </div>
    <div className="max-h-[70vh] overflow-auto bg-[#0E1621] p-3">
      <div className="max-w-full rounded-2xl rounded-tl-md bg-[#182533] px-3.5 py-2.5 text-white shadow">
        <pre className="whitespace-pre-wrap break-words font-sans text-[13px] leading-relaxed">{preview.text || " "}</pre>
        <div className="mt-1 text-right text-[10px] text-white/45">บอทสรุปยอด</div>
      </div>
    </div>
    <div className="bg-surface px-4 py-2 text-[11px] text-muted">เปลี่ยนตามช่องที่ติ๊กทันที (ยังไม่บันทึกก็ดูได้) ไม่ได้ส่งไป Telegram</div>
  </div>);
}

function useDailyReportPreview(fields) {
  const [preview, setPreview] = useState({ date: "", text: "" }), [loading, setLoading] = useState(false);
  const fieldsKey = fields ? fields.join(",") : null;
  useEffect(() => {
    if (fieldsKey == null) return undefined;
    let cancelled = false;
    setLoading(true);
    const timer = setTimeout(async () => {
      try {
        const result = await api("/daily-report/preview", { method: "POST", body: { fields: fieldsKey ? fieldsKey.split(",") : [] } });
        if (!cancelled) setPreview(result);
      } catch (_) {
        if (!cancelled) setPreview(current => ({ ...current, text: "โหลดตัวอย่างไม่สำเร็จ" }));
      } finally {
        if (!cancelled) setLoading(false);
      }
    }, DAILY_REPORT_PREVIEW_DELAY_MS);
    return () => { cancelled = true; clearTimeout(timer); };
  }, [fieldsKey]);
  return { preview, loading };
}

function DailyReportSettingsPage({ toast }) {
  const [saved, setSaved] = useState(null), [form, setForm] = useState(null), [err, setErr] = useState(null), [busy, setBusy] = useState("");
  const { preview, loading: previewLoading } = useDailyReportPreview(form && form.fields);
  const load = useCallback(async () => {
    setErr(null);
    try {
      const config = await api("/daily-report/config");
      setSaved(config);
      setForm({ enabled: config.enabled, time: config.time, chat_id: config.chat_id, token: "", fields: config.fields || [] });
    } catch (e) {
      if (e.status === 401) { window.__nxAuthFail && window.__nxAuthFail(); }
      setErr(e.status === 403 ? "ไม่มีสิทธิ์ใช้เมนูนี้" : (e.message || "โหลดไม่สำเร็จ"));
    }
  }, []);
  useEffect(() => { load(); }, [load]);
  const set = (field, value) => setForm(current => ({ ...current, [field]: value }));
  const toggleField = key => setForm(current => ({ ...current, fields: current.fields.includes(key) ? current.fields.filter(item => item !== key) : [...current.fields, key] }));
  const toggleGroup = (keys, on) => setForm(current => ({ ...current, fields: on ? [...new Set([...current.fields, ...keys])] : current.fields.filter(item => !keys.includes(item)) }));

  const save = async () => {
    setBusy("save");
    try {
      const config = await api("/daily-report/config", { method: "POST", body: { enabled: form.enabled, time: form.time, chat_id: form.chat_id.trim(), token: form.token.trim(), fields: form.fields } });
      setSaved(config); setForm(current => ({ ...current, token: "", fields: config.fields })); toast("บันทึกแล้ว");
    } catch (e) { toast(dailyReportErrText(e.data && e.data.error)); }
    finally { setBusy(""); }
  };
  const testSend = async range => {
    setBusy("test_" + range);
    try {
      const sent = await api("/daily-report/test", { method: "POST", body: { range } });
      const okText = range === "today" ? "ส่งยอดวันนี้ (ถึงตอนนี้) เข้า Telegram แล้ว" : "ส่งยอดเมื่อวานเข้า Telegram แล้ว";
      toast(sent.ok ? okText : dailyReportErrText(sent.error, sent.detail));
    } catch (e) { toast(dailyReportErrText(e.data && e.data.error)); }
    finally { setBusy(""); }
  };

  if (err) return <HistErr msg={err} onRetry={load}/>;
  if (!form) 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 dirty = form.enabled !== saved.enabled || form.time !== saved.time || form.chat_id !== saved.chat_id || !!form.token || !dailyReportSameFields(form.fields, saved.fields);
  const noField = !form.fields.some(key => key !== "compare");
  const label = "mb-1 block text-xs font-semibold text-fg-2";
  const input = "w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm";
  return (<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_400px] lg:items-start">
    <div className="space-y-4">
      <div className="space-y-4 rounded-xl border border-line bg-surface p-5 shadow-sm">
        <label className="flex cursor-pointer items-center justify-between gap-3 rounded-lg border border-line bg-sunken/40 px-3 py-2.5 hover:bg-sunken/60">
          <div><span className="text-sm font-medium text-fg">เปิดส่งสรุปยอดรายวัน</span><div className="text-[11px] text-muted">ส่งยอดของเมื่อวานเต็มวัน (00:00–23:59) วันละ 1 ครั้ง</div></div>
          <button type="button" role="switch" aria-checked={form.enabled} onClick={() => set("enabled", !form.enabled)} className={"relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors duration-150 " + (form.enabled ? "bg-accent" : "bg-line")}><span className={"inline-block h-5 w-5 rounded-full bg-white shadow transition-transform duration-150 " + (form.enabled ? "translate-x-5" : "translate-x-0.5")}/></button>
        </label>
        <div className="grid gap-4 sm:grid-cols-[160px_minmax(0,1fr)]">
          <div><label className={label}>เวลาส่ง (เวลาไทย)</label><input type="time" value={form.time} onChange={e => set("time", e.target.value)} className={input}/></div>
          <div><label className={label}>Telegram Chat ID</label><input value={form.chat_id} onChange={e => set("chat_id", e.target.value)} spellCheck={false} placeholder="-1001234567890" className={"mono " + input}/></div>
        </div>
        <div>
          <label className={label}>Telegram Bot Token</label>
          <input type="password" value={form.token} onChange={e => set("token", e.target.value)} autoComplete="new-password" spellCheck={false} placeholder={saved.has_token ? `บันทึกไว้แล้ว (${saved.token_hint}) เว้นว่าง = ใช้ค่าเดิม` : "123456789:AA..."} className={"mono " + input}/>
        </div>
        <div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-t border-line pt-3 text-xs">
          <span className="text-fg-2">ส่งล่าสุด: <span className="font-semibold text-fg">{saved.last_sent ? `ยอดวันที่ ${saved.last_sent}` : "ยังไม่เคยส่ง"}</span></span>
          {saved.last_error && <span className="text-danger">ส่งไม่สำเร็จล่าสุด: {saved.last_error}</span>}
        </div>
        <DailyReportHowTo defaultOpen={!saved.has_token}/>
      </div>

      <div>
        <div className="mb-2 flex items-baseline gap-2 px-1"><div className="text-sm font-semibold text-fg">หัวข้อที่จะแสดงในข้อความ</div><div className="text-xs text-muted">ติ๊กแล้วดูตัวอย่างด้านขวา (มือถือ: ด้านล่าง) แล้วกดบันทึก</div></div>
        <div className="space-y-3">
          {(saved.groups || []).map(group => <DailyReportFieldGroup key={group.key} group={group} picked={form.fields} onToggle={toggleField} onToggleGroup={toggleGroup}/>)}
        </div>
      </div>

      <div className="sticky bottom-0 z-10 -mx-1 flex flex-wrap items-center justify-end gap-2 rounded-xl border border-line bg-surface/95 px-4 py-3 shadow-lg backdrop-blur">
        {noField && <span className="mr-auto text-xs text-danger">ต้องติ๊กอย่างน้อย 1 หัวข้อ</span>}
        {!noField && dirty && <span className="mr-auto text-xs text-warn">มีการเปลี่ยนแปลงที่ยังไม่บันทึก</span>}
        {[["today", "ส่งทดสอบตอนนี้ (ยอดวันนี้)"], ["yesterday", "ส่งทดสอบ (ยอดเมื่อวาน)"]].map(([range, text]) => (
          <button key={range} onClick={() => testSend(range)} disabled={!!busy || dirty || !saved.has_token || !saved.chat_id} title={dirty ? "บันทึกก่อนแล้วค่อยทดสอบ" : (!saved.has_token || !saved.chat_id) ? "ใส่ Bot Token และ Chat ID แล้วบันทึกก่อน" : "ส่งเข้า Telegram ทันที ไม่นับเป็นรอบส่งประจำวัน"} className="h-9 rounded-lg border border-line bg-surface px-4 text-sm font-medium text-fg-2 transition-colors duration-150 hover:bg-sunken disabled:opacity-50">{busy === "test_" + range ? "กำลังส่ง…" : text}</button>
        ))}
        <button onClick={save} disabled={!!busy || !dirty || noField} className="h-9 rounded-lg bg-accent px-5 text-sm font-semibold text-accent-fg transition-opacity duration-150 hover:opacity-90 disabled:opacity-50">{busy === "save" ? "กำลังบันทึก…" : "บันทึก"}</button>
      </div>
    </div>

    <DailyReportPreview preview={preview} loading={previewLoading}/>
  </div>);
}
