// MyBoost: suggests SMMFollows services for packages that have none (loaded after ext.jsx)
class SetupBoundary extends React.Component {
  constructor(p) { super(p); this.state = { bad: false }; }
  static getDerivedStateFromError() { return { bad: true }; }
  render() { return this.state.bad ? null : this.props.children; }
}

const setupWord = (p) => ({ followers: p.platform === "youtube" ? "subscriber" : "follower", likes: "like", comments: "comment", shares: "share" }[p.type]);
const setupQuery = (p) => `${p.platform} ${setupWord(p)}`;
// The panel returns only the 60 cheapest matches, so ask for USA directly (two spellings) and merge.
async function setupSearch(p) {
  const base = setupQuery(p);
  const seen = {}; const out = [];
  for (const extra of ["usa", "united states"]) {
    const r = (await admin("search_services", { q: `${base} ${extra}` })).results || [];
    for (const s of r) if (!seen[s.service]) { seen[s.service] = 1; out.push(s); }
  }
  return out;
}
const SETUP_BAD = /story|stories|\blive\b|premiere|watch ?time|\bviews?\b|subscription|monthly|\bauto\b|repl(y|ies)|comment likes?|\bpoll\b|\bvotes?\b|\bgroup\b|member/i;

// Reads the refill guarantee from the service name ("Refill: 30 Days", "Refill Button: 365 Days", "Lifetime"). "" = none.
function refillInfo(s) {
  const n = `${s.name} ${s.category}`;
  if (/no.?refill/i.test(n)) return "";
  if (/lifetime/i.test(n)) return "Lifetime refill";
  const m = n.match(/refill[^|]*?(\d+)\s*(d|day)/i);
  if (m) return `${m[1]}-day refill`;
  if (/refill|guarantee/i.test(n) || s.refill === true || s.refill === 1 || s.refill === "1") return "Refill guarantee";
  return "";
}

function setupRank(list, p) {
  const ok = list.filter((s) => {
    if (SETUP_BAD.test(`${s.name} ${s.category}`)) return false;
    const t = String(s.type || "default").toLowerCase();
    if (!/^(default|custom comments)$/.test(t)) return false;
    return Number(s.min) <= p.qty && p.qty <= Number(s.max);
  });
  const score = (s) => {
    const n = `${s.name} ${s.category}`.toLowerCase();
    let v = 0;
    if (/real|high.?quality|premium|\bhq\b/.test(n)) v += 3;
    if (/no.?drop|non.?drop/.test(n)) v += 2;
    if (refillInfo(s)) v += 6; // a refill guarantee beats a cheaper service without one
    if (/instant|fast/.test(n)) v += 1;
    if (p.type === "comments" && /random|positive/.test(n)) v += 2;
    if (/\bbot\b|bots|fake|low.?quality|cheap|drip|slow|test|unstable|india|mixed|old accounts/.test(n)) v -= 3;
    return v;
  };
  // US only: keep services that say USA / United States and are not mixed with other countries
  const us = ok.filter((s) => {
    const n = `${s.name} ${s.category}`.toLowerCase();
    return /\busa\b|\bus\b|u\.s\.|united states|🇺🇸/.test(n) && !/canada|& more|&amp; more|worldwide|global|mixed|europe|india/.test(n);
  });
  return us.map((s) => ({ s, v: score(s) })).filter((x) => x.v >= 0).sort((a, b) => b.v - a.v || Number(a.s.rate) - Number(b.s.rate)).map((x) => x.s);
}

function SetupHelper({ packages, reload, toast }) {
  const unset = packages.filter((p) => !p.smm_service_id);
  const [found, setFound] = useState(null);
  const [busy, setBusy] = useState(false);
  const [saving, setSaving] = useState(null);
  if (!unset.length) return null;

  const run = async () => {
    setBusy(true);
    try {
      const out = {}; const cache = {};
      for (const p of unset) {
        const q = setupQuery(p);
        if (!cache[q]) cache[q] = await setupSearch(p);
        out[p.id] = setupRank(cache[q], p).slice(0, 4);
      }
      setFound(out);
    } catch (e) { toast(e.message, "error"); }
    setBusy(false);
  };

  const apply = async (p, s) => {
    await admin("set_service", { package_id: p.id, smm_service_id: Number(s.service) });
    const up = await sb.from("myboost_package_costs").upsert({ package_id: p.id, cost_per_1000: Number(s.rate), updated_at: new Date().toISOString() });
    if (up.error) throw new Error(up.error.message);
    await admin("update_package", { package_id: p.id, active: true });
  };
  const use = async (p, s) => {
    setSaving(p.id);
    try {
      await apply(p, s);
      toast(`${p.name} is set up with service #${s.service} and switched on`);
      setFound((f) => { const c = { ...f }; delete c[p.id]; return c; });
    } catch (e) { toast(e.message, "error"); }
    setSaving(null); reload();
  };
  const doable = found ? unset.filter((p) => (found[p.id] || []).some((s) => Number(p.price) - Number(s.rate) * p.qty / 1000 >= 0)) : [];
  const useAll = async () => {
    setSaving("all");
    let ok = 0;
    try {
      for (const p of doable) {
        const s = found[p.id].find((x) => Number(p.price) - Number(x.rate) * p.qty / 1000 >= 0);
        await apply(p, s); ok++;
      }
      toast(`${ok} packages set up and switched on`);
      setFound(null);
    } catch (e) { toast(`Stopped after ${ok}: ${e.message}`, "error"); }
    setSaving(null); reload();
  };

  return <div style={S.card}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
      <div>
        <div style={{ fontWeight: 700, fontSize: 16 }}>🧩 Set up the rest</div>
        <div style={S.muted}>{unset.length} packages have no SMMFollows service. It shows USA-only matches and prefers services with a refill guarantee. You tap Use to confirm each one.</div>
      </div>
      <button style={S.bsm} disabled={busy} onClick={run}>{busy ? "Searching…" : found ? "Search again" : "Find services"}</button>
    </div>
    {found && doable.length > 0 && <div style={{ marginTop: 12 }}><button style={S.btn} disabled={saving === "all"} onClick={useAll}>{saving === "all" ? "Setting up…" : `✅ Set up all ${doable.length} automatically (best USA match each)`}</button></div>}
    {found && unset.map((p) => {
      const list = found[p.id];
      if (!list) return null;
      return <div key={p.id} style={{ marginTop: 14, paddingTop: 12, borderTop: "1px solid #2a2a4a" }}>
        <div style={{ fontWeight: 700 }}>{PI[p.platform]} {p.name} <span style={S.muted}>· {p.qty.toLocaleString()} {p.type} · sells at {money(p.price)}</span></div>
        {list.length === 0 && <div style={{ ...S.muted, marginTop: 6 }}>No USA-only service found for this one. Leave it off for now.</div>}
        {list.map((s) => {
          const cost = Number(s.rate) * p.qty / 1000;
          const profit = Number(p.price) - cost;
          return <div key={s.service} style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center", marginTop: 8, flexWrap: "wrap" }}>
            <div style={{ flex: 1, minWidth: 220 }}>
              <div style={{ fontSize: 13 }}><b>#{s.service}</b> {s.name}</div>
              <div style={S.muted}>Cost {money(cost)} for {p.qty.toLocaleString()} · you would keep {money(profit)} · min {Number(s.min).toLocaleString()}, max {Number(s.max).toLocaleString()}{refillInfo(s) ? " · ♻ " + refillInfo(s) : " · no refill"}</div>
            </div>
            <button style={S.bsm} disabled={saving === p.id || profit < 0} onClick={() => use(p, s)}>{profit < 0 ? "Costs more than price" : saving === p.id ? "…" : "Use this"}</button>
          </div>;
        })}
      </div>;
    })}
  </div>;
}


const USA_TIERS = { followers: [250, 1000], likes: [100, 500], comments: [10, 25] };
const USA_LABEL = { followers: "Followers", likes: "Likes", comments: "Comments" };
const usaPrice = (cost) => Math.max(0.99, Math.ceil(cost * 4) - 0.01);

function UsaAdder({ packages, reload, toast }) {
  const [plan, setPlan] = useState(null);
  const [busy, setBusy] = useState(false);
  const [making, setMaking] = useState(false);
  const [prices, setPrices] = useState({});

  const find = async () => {
    setBusy(true);
    try {
      const cache = {}; const rows = [];
      for (const platform of ["instagram", "facebook", "youtube", "tiktok"]) {
        for (const type of ["followers", "likes", "comments"]) {
          const q = setupQuery({ platform, type });
          if (!cache[q]) cache[q] = await setupSearch({ platform, type });
          for (const qty of USA_TIERS[type]) {
            const svc = setupRank(cache[q], { qty, type })[0];
            if (!svc) continue;
            const name = `${platform === "youtube" && type === "followers" ? "Subscribers" : USA_LABEL[type]} USA ${qty.toLocaleString()}`;
            if (packages.some((p) => p.platform === platform && p.name.toLowerCase() === name.toLowerCase())) continue;
            const cost = Number(svc.rate) * qty / 1000;
            rows.push({ key: `${platform}-${type}-${qty}`, platform, type, qty, svc, name, cost });
          }
        }
      }
      const pr = {}; rows.forEach((r) => { pr[r.key] = usaPrice(r.cost).toFixed(2); });
      setPrices(pr); setPlan(rows);
    } catch (e) { toast(e.message, "error"); }
    setBusy(false);
  };

  const create = async () => {
    setMaking(true); let ok = 0;
    try {
      for (const r of plan) {
        const price = Number(prices[r.key]);
        if (!(price >= r.cost)) continue;
        const { error } = await sb.rpc("myboost_add_package", { p_platform: r.platform, p_type: r.type, p_name: r.name, p_qty: r.qty, p_price: price, p_service: Number(r.svc.service), p_cost_per_1000: Number(r.svc.rate), p_delivery: "Starts within hours" });
        if (error) throw new Error(error.message);
        ok++;
      }
      toast(`${ok} USA packages created and switched on`);
      setPlan(null);
    } catch (e) { toast(`Stopped after ${ok}: ${e.message}`, "error"); }
    setMaking(false); reload();
  };

  return <div style={S.card}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
      <div>
        <div style={{ fontWeight: 700, fontSize: 16 }}>🇺🇸 Add USA packages</div>
        <div style={S.muted}>Finds USA-only services with a refill guarantee when one exists, for followers, likes and comments on Instagram, Facebook, YouTube and TikTok, and adds new packages next to your current ones. Nothing existing is changed.</div>
      </div>
      <button style={S.bsm} disabled={busy} onClick={find}>{busy ? "Searching…" : plan ? "Search again" : "Find USA services"}</button>
    </div>
    {plan && plan.length === 0 && <div style={{ ...S.muted, marginTop: 10 }}>No new USA-only services found, or they are already added.</div>}
    {plan && plan.length > 0 && <>
      <div style={{ ...S.muted, marginTop: 10 }}>You can change a price before creating. Prices start at about 4 times your cost.</div>
      {plan.map((r) => <div key={r.key} style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center", marginTop: 8, flexWrap: "wrap", paddingTop: 8, borderTop: "1px solid #2a2a4a" }}>
        <div style={{ flex: 1, minWidth: 220 }}>
          <div style={{ fontSize: 13 }}>{PI[r.platform]} <b>{r.name}</b> <span style={S.muted}>· service #{r.svc.service}</span></div>
          <div style={S.muted}>{r.svc.name} · your cost {money(r.cost)} · {refillInfo(r.svc) ? "♻ " + refillInfo(r.svc) : "no refill"}</div>
        </div>
        <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
          <span style={S.muted}>Price $</span>
          <input style={{ ...S.inp, width: 80, padding: 6 }} value={prices[r.key]} onChange={(e) => setPrices({ ...prices, [r.key]: e.target.value })} />
          <button style={S.bred} onClick={() => setPlan(plan.filter((x) => x.key !== r.key))}>Skip</button>
        </div>
      </div>)}
      <div style={{ marginTop: 12 }}><button style={S.btn} disabled={making} onClick={create}>{making ? "Creating…" : `✅ Create ${plan.length} USA packages`}</button></div>
    </>}
  </div>;
}

// Shows refill + country for every package you already have (reads SMMFollows, changes nothing).
const countryOf = (s) => {
  const n = `${s.name} ${s.category}`.toLowerCase();
  if (/canada|& more|&amp; more|worldwide|global|mixed|europe/.test(n)) return "mixed countries";
  if (/\busa\b|\bus\b|u\.s\.|united states|🇺🇸/.test(n)) return "USA";
  return "country not stated";
};

function RefillCheck({ packages, toast }) {
  const [info, setInfo] = useState(null);
  const [busy, setBusy] = useState(false);
  const withSvc = packages.filter((p) => p.smm_service_id);
  if (!withSvc.length) return null;

  const run = async () => {
    setBusy(true);
    try {
      const ids = [...new Set(withSvc.map((p) => Number(p.smm_service_id)))];
      const r = (await admin("service_info", { ids })).results || [];
      const m = {}; r.forEach((x) => { m[Number(x.service)] = x; });
      setInfo(m);
    } catch (e) { toast(e.message, "error"); }
    setBusy(false);
  };

  const rows = info ? withSvc.map((p) => {
    const svc = info[Number(p.smm_service_id)];
    const refill = svc ? refillInfo(svc) : "";
    const country = svc ? countryOf(svc) : "unknown";
    return { p, svc, refill, country, good: !!svc && !!refill && country === "USA" };
  }) : [];
  const good = rows.filter((r) => r.good).length;

  return <div style={S.card}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
      <div>
        <div style={{ fontWeight: 700, fontSize: 16 }}>♻ Refill check</div>
        <div style={S.muted}>Shows which of your packages have a refill guarantee and whether the service is USA-only. It only reads. It changes nothing.</div>
      </div>
      <button style={S.bsm} disabled={busy} onClick={run}>{busy ? "Checking…" : info ? "Check again" : "Check my packages"}</button>
    </div>
    {info && <div style={{ ...S.muted, marginTop: 10 }}>{good} of {rows.length} packages have a refill guarantee and are USA-only.</div>}
    {rows.map(({ p, svc, refill, country, good: ok }) => <div key={p.id} style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center", marginTop: 8, paddingTop: 8, borderTop: "1px solid #2a2a4a", flexWrap: "wrap" }}>
      <div style={{ flex: 1, minWidth: 200 }}>
        <div style={{ fontSize: 13 }}>{PI[p.platform]} <b>{p.name}</b> <span style={S.muted}>· {p.qty.toLocaleString()} · service #{p.smm_service_id}{p.active ? "" : " · off"}</span></div>
        <div style={S.muted}>{svc ? svc.name : "Service not found at SMMFollows"}</div>
      </div>
      <div style={{ fontSize: 12, textAlign: "right" }}>
        <div style={{ color: refill ? "#10b981" : "#f59e0b" }}>{refill ? "♻ " + refill : "no refill"}</div>
        <div style={{ color: country === "USA" ? "#10b981" : "#f59e0b" }}>{country}</div>
      </div>
    </div>)}
  </div>;
}

const __BaseAdminPackages = window.AdminPackages;
if (typeof __BaseAdminPackages === "function") window.AdminPackages = function AdminPackagesWithSetup(props) {
  return <>
    <SetupBoundary><SetupHelper {...props} /></SetupBoundary>
    <SetupBoundary><UsaAdder {...props} /></SetupBoundary>
    <SetupBoundary><RefillCheck {...props} /></SetupBoundary>
    <__BaseAdminPackages {...props} />
  </>;
};
