// MyBoost: admin pays wholesale cost in the Store (loaded after ext.jsx)
/* ---------------- Store (admin pays wholesale cost) ---------------- */
PI.tiktok = PI.tiktok || "🎵";
TI.views = TI.views || "👁";

const ACCT_HOST = {
  instagram: /^https?:\/\/([a-z0-9-]+\.)*(instagram\.com|instagr\.am)([\/?]|$)/i,
  facebook: /^https?:\/\/([a-z0-9-]+\.)*(facebook\.com|fb\.com|fb\.me)([\/?]|$)/i,
  youtube: /^https?:\/\/([a-z0-9-]+\.)*(youtube\.com|youtu\.be)([\/?]|$)/i,
  tiktok: /^https?:\/\/([a-z0-9-]+\.)*tiktok\.com([\/?]|$)/i,
};

function MyAccountsCard({ profile, accounts, reload, toast }) {
  const [open, setOpen] = useState(accounts.length === 0);
  const [pf, setPf] = useState("instagram");
  const [url, setUrl] = useState("");
  const [busy, setBusy] = useState(false);
  const add = async () => {
    let u = url.trim();
    if (u && !/^https?:\/\//i.test(u)) u = "https://" + u;
    if (!ACCT_HOST[pf].test(u)) return toast(`That is not a ${pf} link. Paste your profile or page link.`, "error");
    setBusy(true);
    const { error } = await sb.from("myboost_accounts").insert({ user_id: profile.id, platform: pf, url: u });
    setBusy(false);
    if (error) return toast(/duplicate|unique/i.test(error.message) ? "That account is already saved" : error.message, "error");
    setUrl(""); toast("Account saved"); reload();
  };
  const del = async (a) => {
    const { error } = await sb.from("myboost_accounts").delete().eq("id", a.id);
    if (error) return toast(error.message, "error");
    reload();
  };
  return <div style={{ ...S.card, marginBottom: 16 }}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, cursor: "pointer" }} onClick={() => setOpen(!open)}>
      <div style={{ fontWeight: 700 }}>🔗 My accounts <span style={S.muted}>· {accounts.length ? `${accounts.length} saved. Follower orders fill in your link for you.` : "Save your profile links once and skip pasting them every time."}</span></div>
      <span style={S.muted}>{open ? "Hide" : "Show"}</span>
    </div>
    {open && <div style={{ marginTop: 12 }}>
      {accounts.map((a) => <div key={a.id} style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center", padding: "6px 0", borderTop: "1px solid #2a2a4a" }}>
        <div style={{ fontSize: 13, wordBreak: "break-all" }}>{PI[a.platform]} {a.url}</div>
        <button style={S.bred} onClick={() => del(a)}>Remove</button>
      </div>)}
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 10 }}>
        <select style={{ ...S.inp, width: 130 }} value={pf} onChange={(e) => setPf(e.target.value)}>
          <option value="instagram">Instagram</option><option value="facebook">Facebook</option><option value="youtube">YouTube</option><option value="tiktok">TikTok</option>
        </select>
        <input style={{ ...S.inp, flex: 1, minWidth: 200 }} placeholder="paste your profile or page link" value={url} onChange={(e) => setUrl(e.target.value)} />
        <button style={S.bsm} disabled={busy} onClick={add}>Save account</button>
      </div>
      <div style={{ ...S.muted, marginTop: 8 }}>Likes, comments, views and shares still need the link to the one post or video you want boosted.</div>
    </div>}
  </div>;
}

function Store({ packages, profile, onOrdered, toast }) {
  const [fp, setFp] = useState("all");
  const [ft, setFt] = useState("all");
  const [sp, setSp] = useState(null);
  const [cd, setCd] = useState({ url: "", note: "" });
  const [busy, setBusy] = useState(false);
  const isAdmin = profile.role === "admin";
  const [costs, setCosts] = useState({});
  useEffect(() => { if (!isAdmin) return; sb.from("myboost_package_costs").select("package_id, cost_per_1000").then(({ data }) => { const m = {}; (data || []).forEach((r) => { m[r.package_id] = Number(r.cost_per_1000); }); setCosts(m); }); }, [isAdmin]);
  const [accounts, setAccounts] = useState([]);
  const loadAccounts = () => sb.from("myboost_accounts").select("*").eq("user_id", profile.id).order("id").then(({ data }) => setAccounts(data || []));
  useEffect(() => { loadAccounts(); }, [profile.id]);
  const eff = (p) => (isAdmin && costs[p.id] != null ? Math.max(0.01, Math.round(costs[p.id] * p.qty / 10) / 100) : Number(p.price));
  const list = packages.filter((p) => p.active && (fp === "all" || p.platform === fp) && (ft === "all" || p.type === ft));

  const place = async () => {
    if (!cd.url.trim()) return toast("Please enter your profile/post URL", "error");
    if (Number(profile.balance) < eff(sp)) return toast("Insufficient balance. Ask the admin to top up.", "error");
    setBusy(true);
    const { data, error } = await sb.rpc("myboost_place_order", { p_package_id: sp.id, p_link: cd.url, p_note: cd.note });
    setBusy(false);
    if (error) return toast(error.message, "error");
    toast(`Order #${data.id} placed! Delivery: ${sp.delivery}`);
    setSp(null); onOrdered();
  };

  return <>
    {typeof Welcome === "function" && <Welcome profile={profile} />}
    <h1 style={S.h1}>🚀 Growth Packages</h1>
    <p style={{ color: "#6666aa", marginBottom: 18, fontSize: 13 }}>Boost your Instagram, Facebook, YouTube & TikTok{isAdmin ? " · Admin pricing: you pay what SMMFollows charges (members pay the package price)" : ""}</p>
    <MyAccountsCard profile={profile} accounts={accounts} reload={loadAccounts} toast={toast} />
    <div style={S.fr}>{["all", "instagram", "facebook", "youtube", "tiktok"].map((f) => (
      <button key={f} style={{ ...S.fb, ...(fp === f ? S.fba : {}) }} onClick={() => setFp(f)}>{f === "all" ? "All Platforms" : PI[f] + " " + cap(f)}</button>))}</div>
    <div style={S.fr}>{["all", "followers", "likes", "comments", "views", "shares"].map((t) => (
      <button key={t} style={{ ...S.fb, ...(ft === t ? S.fba : {}) }} onClick={() => setFt(t)}>{t === "all" ? "All Types" : TI[t] + " " + cap(t)}</button>))}</div>
    <div style={S.grid}>{list.map((pkg) => (
      <div key={pkg.id} style={S.pc}>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 6 }}>
          <span style={{ ...S.chip, background: pkg.color + "22", color: pkg.color }}>{PI[pkg.platform]} {pkg.platform}</span>
          <span style={{ ...S.chip, background: "#ffffff11", color: "#a0a0c0" }}>{TI[pkg.type]} {pkg.type}</span>
        </div>
        <div style={{ fontWeight: 700, fontSize: 15 }}>{pkg.name}</div>
        <div style={{ fontSize: 26, fontWeight: 900, color: pkg.color }}>{pkg.qty.toLocaleString()}</div>
        <div style={{ color: "#6666aa", fontSize: 12 }}>⏱ {pkg.delivery}</div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 6 }}>
          <span style={{ fontSize: 20, fontWeight: 800, color: "#10b981" }}>{money(eff(pkg))}{isAdmin && costs[pkg.id] != null && <span style={{ fontSize: 11, color: "#6666aa", marginLeft: 6 }}>at cost</span>}</span>
          <button style={S.bsm} onClick={() => { setSp(pkg); setCd({ url: "", note: "" }); }}>Buy Now</button>
        </div>
      </div>))}</div>

    {sp && <div style={S.ov} onClick={(e) => e.target === e.currentTarget && setSp(null)}>
      <div style={S.modal}>
        <h2 style={{ fontSize: 18, fontWeight: 700, marginBottom: 14 }}>🛒 Place Order</h2>
        <div style={{ ...S.card, marginBottom: 14, padding: 12 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10 }}>
            <div>
              <div style={{ fontWeight: 700 }}>{sp.name}</div>
              <div style={{ color: "#6666aa", fontSize: 12 }}>{PI[sp.platform]} {sp.platform} · {TI[sp.type]} {sp.type} · {sp.qty.toLocaleString()} units</div>
              <div style={{ color: "#a0a0c0", fontSize: 12 }}>⏱ {sp.delivery}</div>
            </div>
            <div style={{ fontSize: 22, fontWeight: 800, color: "#10b981" }}>{money(eff(sp))}</div>
          </div>
        </div>
        {sp.type === "followers" && accounts.filter((a) => a.platform === sp.platform).length > 0 && <div style={{ marginBottom: 12 }}><label style={S.label}>Choose one of your saved accounts</label>
          <select style={S.inp} value="" onChange={(e) => e.target.value && setCd({ ...cd, url: e.target.value })}>
            <option value="">Pick an account…</option>
            {accounts.filter((a) => a.platform === sp.platform).map((a) => <option key={a.id} value={a.url}>{a.url}</option>)}
          </select></div>}
        <div style={{ marginBottom: 12 }}><label style={S.label}>{sp.type === "followers" ? "Your profile / channel URL *" : "The post / video URL *"}</label>
          <input style={S.inp} placeholder={sp.type === "followers" ? "e.g. instagram.com/yourhandle" : "paste the full post link"} value={cd.url} onChange={(e) => setCd({ ...cd, url: e.target.value })} /></div>
        <div style={{ ...S.muted, marginBottom: 12 }}>Your account must be <b>public</b>, or the order will be cancelled.</div>
        <div style={{ marginBottom: 16 }}><label style={S.label}>Notes (optional)</label>
          <input style={S.inp} placeholder="Any special instructions..." value={cd.note} onChange={(e) => setCd({ ...cd, note: e.target.value })} /></div>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 14, fontSize: 13 }}>
          <span style={{ color: "#6666aa" }}>Balance: <strong style={{ color: "#10b981" }}>{money(profile.balance)}</strong></span>
          <span style={{ color: "#6666aa" }}>After: <strong style={{ color: "#f59e0b" }}>{money(Math.max(0, profile.balance - eff(sp)))}</strong></span>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button style={{ ...S.bgh, flex: 1, padding: 10 }} onClick={() => setSp(null)}>Cancel</button>
          <button style={{ ...S.btn, flex: 2, opacity: busy ? 0.6 : 1 }} disabled={busy} onClick={place}>✅ Confirm Order</button>
        </div>
      </div>
    </div>}
  </>;
}
