// MyBoost extras: Package Check, Health tab, Comment library (loaded after app.jsx)
/* ---------------- Package check (no orders, no spend) ---------------- */
const CHECK_PLATFORMS = ["instagram", "facebook", "youtube", "tiktok", "twitter", "telegram", "spotify", "website"];
const CHECK_TYPE = {
  followers: (n) => /follower|subscriber|page like|member/.test(n),
  likes: (n) => /like|reaction|heart/.test(n) && !/comment/.test(n),
  comments: (n) => /comment/.test(n) && !/reaction|comment like/.test(n),
  shares: (n) => /share|repost/.test(n),
};
function checkPackage(p, s, orders) {
  if (!p.smm_service_id) return { level: "unset", notes: ["No SMMFollows service chosen yet"] };
  if (!s) return { level: "bad", notes: [`Service #${p.smm_service_id} was not found at SMMFollows`] };
  const bad = [], warn = [];
  const name = `${s.category || ""} ${s.name || ""}`.toLowerCase();
  let first = null, firstAt = 1e9;
  CHECK_PLATFORMS.forEach((w) => { const i = name.indexOf(w); if (i >= 0 && i < firstAt) { first = w; firstAt = i; } });
  if (first && first !== p.platform) bad.push(`Service looks like ${first}, but this package is ${p.platform}`);
  if (!first) warn.push("Service name does not mention a platform");
  const rule = CHECK_TYPE[p.type];
  if (rule && !rule(name)) bad.push(`Service name does not look like ${p.type}`);
  if (p.qty < Number(s.min) || p.qty > Number(s.max)) bad.push(`Package size ${p.qty} is outside the service min ${s.min} / max ${s.max}`);
  const c = (Number(s.rate) * p.qty) / 1000;
  if (p.price - c <= 0) bad.push(`Selling at a loss (cost ${money(c)}, price ${money(p.price)})`);
  else if (c / p.price > 0.5) warn.push(`Cost is over half the price (cost ${money(c)})`);
  const mine = (orders || []).filter((o) => o.package_id === p.id && o.smm_order_id);
  if (mine.some((o) => o.status === "completed")) { /* proven */ }
  else if (mine.length) warn.push("Test order sent, still in progress");
  else warn.push("Not tested with a real order yet");
  return { level: bad.length ? "bad" : warn.length ? "warn" : "ok", notes: [...bad, ...warn] };
}


function PackageCheck({ packages, orders = [], toast }) {
  const [report, setReport] = useState(null);
  const [checking, setChecking] = useState(false);
  const runCheck = async () => {
    setChecking(true);
    try {
      const ids = packages.map((p) => p.smm_service_id).filter(Boolean);
      const m = {};
      if (ids.length) { const r = await admin("service_info", { ids }); r.results.forEach((s) => (m[s.service] = s)); }
      setReport({ at: new Date(), rows: packages.map((p) => ({ p, ...checkPackage(p, m[p.smm_service_id], orders) })) });
    } catch (e) { toast(e.message, "error"); }
    setChecking(false);
  };
  const n = (l) => (report ? report.rows.filter((r) => r.level === l).length : 0);
  const col = { ok: "#10b981", warn: "#f59e0b", bad: "#ef4444", unset: "#8888aa" };
  const lab = { ok: "✅ OK", warn: "⚠️ Check", bad: "❌ Fix", unset: "➖ Not set up" };
  const order = { bad: 0, warn: 1, ok: 2, unset: 3 };
  return <div style={S.card}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 10 }}>
      <div><b>🔍 Package check</b><div style={S.muted}>Checks every package against SMMFollows. It places no orders and spends nothing.</div></div>
      <button style={S.bsm} onClick={runCheck} disabled={checking}>{checking ? "Checking…" : "Run package check"}</button>
    </div>
    {report && <div style={{ marginTop: 12 }}>
      <div style={{ ...S.muted, marginBottom: 8 }}>{n("ok")} OK · {n("warn")} to check · {n("bad")} to fix · {n("unset")} not set up · run at {report.at.toLocaleTimeString()}</div>
      <div style={{ overflowX: "auto" }}><table style={S.tbl}>
        <thead><tr>{["Package", "Result", "Notes"].map((h) => <th key={h} style={S.th}>{h}</th>)}</tr></thead>
        <tbody>{[...report.rows].sort((a, b) => order[a.level] - order[b.level]).map((r) => <tr key={r.p.id}>
          <td style={S.td}>{PI[r.p.platform]} {r.p.name}<div style={S.muted}>{r.p.qty.toLocaleString()} {r.p.type}</div></td>
          <td style={{ ...S.td, color: col[r.level], fontWeight: 700, whiteSpace: "nowrap" }}>{lab[r.level]}</td>
          <td style={{ ...S.td, ...S.muted }}>{r.notes.join(" · ") || "Looks right"}</td>
        </tr>)}</tbody>
      </table></div>
    </div>}
  </div>;
}
/* ---------------- Health ---------------- */
function AdminHealth({ orders, packages, users = [], bal, reload, toast }) {
  const [busy, setBusy] = useState(false);
  const hrs = (t) => (Date.now() - new Date(t).getTime()) / 3600000;
  const items = [];
  orders.filter((o) => o.status === "pending" && hrs(o.created_at) > 1).forEach((o) =>
    items.push({ l: "warn", t: `Order #${o.id} has been waiting ${Math.floor(hrs(o.created_at))}h to be sent (tap Send in Orders)` }));
  orders.filter((o) => o.status === "processing" && hrs(o.updated_at || o.created_at) > 24).forEach((o) =>
    items.push({ l: "warn", t: `Order #${o.id} (SMM #${o.smm_order_id}) is still processing after ${Math.floor(hrs(o.created_at))}h. Check Remains at SMMFollows or send a ticket` }));
  orders.filter((o) => o.smm_error && !["cancelled", "completed"].includes(o.status)).forEach((o) =>
    items.push({ l: "bad", t: `Order #${o.id} has an error: ${o.smm_error}` }));
  if (!bal) items.push({ l: "warn", t: "SMMFollows balance has not loaded yet" });
  else if (bal.error) items.push({ l: "bad", t: `Cannot reach SMMFollows: ${bal.error}` });
  else if (Number(bal.balance) < 10) items.push({ l: "bad", t: `SMMFollows balance is low (${money(bal.balance)}). Add funds before sending orders` });
  const unset = packages.filter((p) => p.active && !p.smm_service_id);
  if (unset.length) items.push({ l: "info", t: `${unset.length} active package(s) have no service set, so members cannot order them (Packages tab)` });
  const memberTotal = users.reduce((a, u) => a + Number(u.balance || 0), 0);
  const today = orders.filter((o) => o.status !== "cancelled" && hrs(o.created_at) < 24);
  const col = { ok: "#10b981", warn: "#f59e0b", bad: "#ef4444", info: "#8888aa" };
  const ico = { ok: "✅", warn: "⚠️", bad: "❌", info: "ℹ️" };
  const doRefresh = async () => { setBusy(true); try { const r = await admin("refresh"); toast(`Checked SMMFollows. ${r.updated} order(s) updated`); } catch (e) { toast(e.message, "error"); } setBusy(false); reload(); };
  return <div style={S.card}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 10 }}>
      <div><b>🩺 Health check</b><div style={S.muted}>Updates every time you open this tab. Tap refresh to pull the newest order statuses from SMMFollows first.</div></div>
      <button style={S.bsm} onClick={doRefresh} disabled={busy}>{busy ? "Refreshing…" : "Refresh statuses"}</button>
    </div>
    <div style={{ marginTop: 14 }}>
      {items.length === 0 && <div style={{ color: col.ok, fontWeight: 700 }}>{ico.ok} Nothing needs attention right now.</div>}
      {items.map((i, k) => <div key={k} style={{ color: col[i.l], padding: "6px 0", fontSize: 14 }}>{ico[i.l]} {i.t}</div>)}
    </div>
    <div style={{ ...S.muted, marginTop: 14 }}>Last 24 hours: {today.length} order(s), {money(today.reduce((a, o) => a + Number(o.price), 0))} in order value · Open orders: {orders.filter((o) => ["pending", "processing"].includes(o.status)).length} · Total member balances: {money(memberTotal)} (bookkeeping, not cash)</div>
  </div>;
}


/* ---------------- Comment library ---------------- */
function buildComments(list, qty) {
  const lines = list.map((s) => s.trim()).filter(Boolean);
  if (!lines.length) return "";
  const shuffle = (a) => { const b = [...a]; for (let i = b.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [b[i], b[j]] = [b[j], b[i]]; } return b; };
  const out = [];
  while (out.length < qty) {
    const round = shuffle(lines);
    if (out.length && round.length > 1 && round[0] === out[out.length - 1]) round.push(round.shift());
    out.push(...round);
  }
  return out.slice(0, qty).join("\n");
}

function CommentPicker({ order, packages, onClose, onSend }) {
  const pkg = packages.find((p) => p.id === order.package_id);
  const [sets, setSets] = useState(null);
  const [svc, setSvc] = useState(null);
  const [mode, setMode] = useState("library");
  const [setId, setSetId] = useState("");
  const [own, setOwn] = useState("");
  useEffect(() => {
    (async () => {
      const { data } = await sb.from("myboost_comment_sets").select("*").order("name");
      setSets(data || []);
      if (data && data[0]) setSetId(String(data[0].id));
      if (pkg && pkg.smm_service_id) {
        try {
          const r = await admin("service_info", { ids: [pkg.smm_service_id] });
          const s = r.results && r.results[0];
          setSvc(s || null);
          const n = ((s && s.name) || "").toLowerCase();
          if (/random/.test(n) && !/custom/.test(n)) setMode("random");
        } catch (_) { /* service lookup is only a hint */ }
      }
    })();
  }, []);
  const chosen = (sets || []).find((x) => String(x.id) === setId);
  const lines = mode === "library" ? (chosen ? chosen.comments.split("\n") : []) : own.split(/\n|\|/);
  const clean = lines.map((l) => l.trim()).filter(Boolean);
  const ready = mode === "random" || clean.length > 0;
  const built = mode === "random" ? "" : buildComments(clean, order.qty);
  const modes = [["library", "From my library"], ["own", "Type my own"], ["random", "Supplier writes them"]];
  return <div style={S.ov} onClick={(e) => e.target === e.currentTarget && onClose()}>
    <div style={{ ...S.modal, maxWidth: 520, maxHeight: "88vh", overflowY: "auto" }}>
      <h3 style={{ marginBottom: 6 }}>Comments for order #{order.id}</h3>
      <div style={{ ...S.muted, marginBottom: 12 }}>{order.qty} comments · {pkg ? pkg.name : ""}{svc ? ` · service #${svc.service}: ${String(svc.name).slice(0, 70)}` : ""}</div>
      <div style={{ ...S.fr, marginBottom: 12 }}>{modes.map(([k, l]) => <button key={k} style={{ ...S.fb, ...(mode === k ? S.fba : {}) }} onClick={() => setMode(k)}>{l}</button>)}</div>
      {mode === "random" && <div style={{ ...S.muted, marginBottom: 12 }}>This service writes its own upbeat comments, so nothing is sent from your library. Use this for services named "Random Positive."</div>}
      {mode === "library" && (sets === null ? <div style={S.muted}>Loading your sets…</div> : sets.length === 0 ? <div style={S.muted}>No sets yet. Add one in Admin, Comments.</div> : <>
        <select style={{ ...S.sinp, width: "100%", marginBottom: 8 }} value={setId} onChange={(e) => setSetId(e.target.value)}>
          {sets.map((s) => <option key={s.id} value={s.id}>{s.name} ({s.comments.split("\n").filter(Boolean).length} comments)</option>)}
        </select>
        <div style={{ ...S.muted, marginBottom: 8 }}>{clean.length} comments in this set, {order.qty} needed{clean.length < order.qty ? ". Shorter than the order, so comments will repeat in shuffled order. A set of 50 or more looks more natural." : "."}</div></>)}
      {mode === "own" && <textarea style={{ ...S.sinp, width: "100%", height: 130, fontFamily: "inherit", marginBottom: 8 }} placeholder={"One comment per line, or separate with |\nLove this!\nSo good, thanks for sharing!"} value={own} onChange={(e) => setOwn(e.target.value)} />}
      {mode !== "random" && built && <div style={{ ...S.muted, marginBottom: 12 }}>Preview: {built.split("\n").slice(0, 4).join(" | ")} …</div>}
      <div style={{ display: "flex", gap: 8 }}>
        <button style={S.bsm} disabled={!ready} onClick={() => onSend(mode === "random" ? undefined : built)}>🚀 Send order</button>
        <button style={S.bgh} onClick={onClose}>Cancel</button>
      </div>
    </div>
  </div>;
}

function AdminComments({ toast }) {
  const [sets, setSets] = useState(null);
  const [draft, setDraft] = useState({});
  const [nn, setNn] = useState({ name: "", comments: "" });
  const load = useCallback(async () => {
    const { data, error } = await sb.from("myboost_comment_sets").select("*").order("name");
    if (error) toast(error.message, "error");
    setSets(data || []);
  }, []);
  useEffect(() => { load(); }, [load]);
  const tidy = (t) => t.split(/\n/).map((x) => x.trim()).filter(Boolean).join("\n");
  const save = async (s) => {
    const { error } = await sb.from("myboost_comment_sets").update({ comments: tidy(draft[s.id] !== undefined ? draft[s.id] : s.comments) }).eq("id", s.id);
    if (error) return toast(error.message, "error");
    toast("Saved"); setDraft({ ...draft, [s.id]: undefined }); load();
  };
  const del = async (s) => {
    if (!window.confirm(`Delete the set "${s.name}"?`)) return;
    const { error } = await sb.from("myboost_comment_sets").delete().eq("id", s.id);
    if (error) return toast(error.message, "error");
    toast("Deleted"); load();
  };
  const add = async () => {
    if (!nn.name.trim() || !tidy(nn.comments)) return toast("Add a name and at least one comment", "error");
    const { error } = await sb.from("myboost_comment_sets").insert({ name: nn.name.trim(), comments: tidy(nn.comments) });
    if (error) return toast(error.message, "error");
    toast("Set added"); setNn({ name: "", comments: "" }); load();
  };
  const box = { ...S.sinp, width: "100%", height: 140, fontFamily: "inherit" };
  return <>
    <div style={S.card}>
      <b>💬 Comment library</b>
      <div style={S.muted}>Saved comment sets for custom-comment services, one comment per line. When you tap Send on a comments order you pick a set, and MyBoost shuffles it to fill the order. Use short, positive, on-topic comments with no links or hashtags, and keep 50 or more per set so they do not repeat.</div>
    </div>
    {sets === null && <div style={S.muted}>Loading…</div>}
    {(sets || []).map((s) => <div key={s.id} style={S.card}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8, gap: 8, flexWrap: "wrap" }}>
        <b>{s.name} <span style={S.muted}>({(draft[s.id] !== undefined ? draft[s.id] : s.comments).split("\n").filter((x) => x.trim()).length} comments)</span></b>
        <div style={{ display: "flex", gap: 6 }}>
          {draft[s.id] !== undefined && <button style={S.bsm} onClick={() => save(s)}>Save</button>}
          <button style={S.bred} onClick={() => del(s)}>Delete</button>
        </div>
      </div>
      <textarea style={box} value={draft[s.id] !== undefined ? draft[s.id] : s.comments} onChange={(e) => setDraft({ ...draft, [s.id]: e.target.value })} />
    </div>)}
    <div style={S.card}>
      <b>Add a new set</b>
      <input style={{ ...S.sinp, width: "100%", margin: "8px 0" }} placeholder="Set name, for example: Friendly replies" value={nn.name} onChange={(e) => setNn({ ...nn, name: e.target.value })} />
      <textarea style={box} placeholder={"One comment per line"} value={nn.comments} onChange={(e) => setNn({ ...nn, comments: e.target.value })} />
      <div style={{ marginTop: 8 }}><button style={S.bsm} onClick={add}>Add set</button></div>
    </div>
  </>;
}

/* ---------------- Admin orders (adds the comment picker at Send) ---------------- */
function AdminOrders({ orders, packages = [], reload, toast }) {
  const [busy, setBusy] = useState(null);
  const [filter, setFilter] = useState("open");
  const shown = orders.filter((o) => filter === "all" || (filter === "open" ? ["pending", "processing"].includes(o.status) : o.status === filter));

  const run = async (id, fn) => { setBusy(id); try { await fn(); } catch (e) { toast(e.message, "error"); } setBusy(null); reload(); };
  const [sendFor, setSendFor] = useState(null);
  const doSend = (o, comments) => run(o.id, async () => {
    const r = await admin("send_order", { order_id: o.id, comments });
    toast(`Sent! SMMFollows order #${r.smm_order_id}`);
  });
  const send = (o) => (o.myboost_packages?.type === "comments" ? setSendFor(o) : doSend(o));
  const cancel = (o) => window.confirm(`Cancel order #${o.id} and refund ${money(o.price)}?`) &&
    run(o.id, async () => { const r = await admin("cancel_refund", { order_id: o.id }); toast(`Cancelled. Refunded ${money(r.refunded)}`); });
  const refresh = () => run("refresh", async () => { const r = await admin("refresh"); toast(`Checked SMMFollows — ${r.updated} order(s) updated`); });

  return <div style={S.card}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8, marginBottom: 12 }}>
      <div style={S.fr}>{["open", "completed", "partial", "cancelled", "all"].map((f) => (
        <button key={f} style={{ ...S.fb, ...(filter === f ? S.fba : {}) }} onClick={() => setFilter(f)}>{cap(f)}</button>))}</div>
      <button style={S.bsm} disabled={busy === "refresh"} onClick={refresh}>{busy === "refresh" ? "Checking…" : "🔄 Refresh statuses"}</button>
    </div>
    {shown.length === 0 ? <div style={{ textAlign: "center", color: "#6666aa", padding: 30 }}>No orders here.</div> :
      <table style={S.tbl}>
        <thead><tr>{["#", "Member", "Package", "Link", "Price", "Status", "SMM #", "Action"].map((h) => <th key={h} style={S.th}>{h}</th>)}</tr></thead>
        <tbody>{shown.map((o) => (
          <tr key={o.id}>
            <td style={S.td}>#{o.id}<div style={S.muted}>{o.created_at.slice(0, 10)}</div></td>
            <td style={S.td}>{o.myboost_profiles?.name}<div style={S.muted}>{o.myboost_profiles?.email}</div></td>
            <td style={S.td}>{PI[o.myboost_packages?.platform]} {o.myboost_packages?.name}<div style={S.muted}>{o.qty.toLocaleString()} units{o.note ? " · " + o.note : ""}</div></td>
            <td style={{ ...S.td, maxWidth: 180, wordBreak: "break-all" }}><a href={/^https?:/.test(o.link) ? o.link : "https://" + o.link} target="_blank" rel="noopener noreferrer" style={{ color: "#93c5fd" }}>{o.link}</a></td>
            <td style={S.td}>{money(o.price)}{Number(o.refunded) > 0 && <div style={{ ...S.muted, color: "#10b981" }}>refunded {money(o.refunded)}</div>}</td>
            <td style={S.td}><Status s={o.status} />{o.smm_error && <div style={{ ...S.muted, color: "#fca5a5", maxWidth: 180 }}>{o.smm_error}</div>}</td>
            <td style={S.td}>{o.smm_order_id || "—"}{o.smm_status && <div style={S.muted}>{o.smm_status}</div>}</td>
            <td style={S.td}>{o.status === "pending" && <div style={{ display: "flex", gap: 6 }}>
              <button style={S.bsm} disabled={busy === o.id} onClick={() => send(o)}>{busy === o.id ? "…" : "🚀 Send"}</button>
              <button style={S.bred} disabled={busy === o.id} onClick={() => cancel(o)}>Cancel</button>
            </div>}</td>
          </tr>))}</tbody>
      </table>}
    {sendFor && <CommentPicker order={sendFor} packages={packages} onClose={() => setSendFor(null)} onSend={(c) => { const o = sendFor; setSendFor(null); doSend(o, c); }} />}
  </div>;
}

function Admin(props) {
  const [tab, setTab] = useState("orders");
  const [bal, setBal] = useState(null);
  const loadBal = async () => { try { setBal(await admin("smm_balance")); } catch (e) { setBal({ error: e.message }); } };
  useEffect(() => { loadBal(); }, []);
  const pending = props.orders.filter((o) => o.status === "pending").length;
  return <>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 10 }}>
      <h1 style={S.h1}>⚙️ Admin Panel</h1>
      <div style={{ ...S.card, padding: "8px 14px", marginBottom: 0, display: "flex", gap: 10, alignItems: "center" }}>
        <span style={S.muted}>SMMFollows balance</span>
        <b style={{ color: bal?.error ? "#ef4444" : "#10b981" }}>{bal ? (bal.error ? "error" : money(bal.balance)) : "…"}</b>
        <button style={{ ...S.nb, padding: 2 }} onClick={loadBal} title="Refresh">🔄</button>
      </div>
    </div>
    <div style={{ ...S.fr, margin: "14px 0" }}>
      {[["orders", `📦 Orders${pending ? ` (${pending} pending)` : ""}`], ["users", "👥 Members"], ["packages", "🧩 Packages"], ["comments", "💬 Comments"], ["health", "🩺 Health"]].map(([t, l]) => (
        <button key={t} style={{ ...S.fb, ...(tab === t ? S.fba : {}) }} onClick={() => setTab(t)}>{l}</button>))}
    </div>
    {tab === "orders" && <AdminOrders {...props} />}
    {tab === "users" && <AdminUsers {...props} />}
    {tab === "packages" && <><PackageCheck {...props} /><AdminPackages {...props} /></>}
    {tab === "comments" && <AdminComments {...props} />}
    {tab === "health" && <AdminHealth {...props} bal={bal} />}
  </>;
}
