// MyBoost — private social growth platform (a SoHo Media House build)
const { useState, useEffect, useCallback } = React;

const SB_URL = "https://tjbtqmncefbrxqlpbcfc.supabase.co";
const SB_KEY = "sb_publishable_IsQpBcXT7KTXs63V8JooGw__pNLchfH";
const sb = window.supabase.createClient(SB_URL, SB_KEY);

const PI = { instagram: "📸", facebook: "👥", youtube: "▶️" };
const TI = { followers: "👤", likes: "❤️", comments: "💬", shares: "🔁" };
const SC = { pending: "#f59e0b", processing: "#3b82f6", completed: "#10b981", partial: "#a78bfa", cancelled: "#ef4444" };
const money = (n) => "$" + Number(n || 0).toFixed(2);
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);

const S = {
  app: { minHeight: "100vh", background: "#0a0a0f", color: "#f0f0f0" },
  nav: { background: "linear-gradient(135deg,#1a1a2e,#16213e)", borderBottom: "1px solid #2a2a4a", padding: "8px 16px", display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 8, position: "sticky", top: 0, zIndex: 100 },
  logo: { fontSize: 20, fontWeight: 800, background: "linear-gradient(90deg,#a78bfa,#60a5fa,#34d399)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent" },
  nb: { background: "none", border: "none", color: "#a0a0c0", cursor: "pointer", padding: "6px 10px", borderRadius: 8, fontSize: 13 },
  nba: { background: "rgba(167,139,250,0.15)", color: "#a78bfa" },
  badge: { background: "linear-gradient(135deg,#a78bfa,#60a5fa)", borderRadius: 20, padding: "2px 10px", fontSize: 12, color: "#fff", fontWeight: 700 },
  main: { maxWidth: 1150, margin: "0 auto", padding: "24px 16px" },
  card: { background: "linear-gradient(135deg,#1a1a2e,#16213e)", border: "1px solid #2a2a4a", borderRadius: 16, padding: 18, marginBottom: 16, overflowX: "auto" },
  pc: { background: "#12122a", border: "1px solid #2a2a4a", borderRadius: 14, padding: 16, display: "flex", flexDirection: "column", gap: 8 },
  grid: { display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(220px,1fr))", gap: 14, marginTop: 18 },
  h1: { fontSize: 24, fontWeight: 800, marginBottom: 6 },
  label: { fontSize: 13, color: "#8888aa", marginBottom: 4, display: "block" },
  inp: { width: "100%", background: "#0d0d1f", border: "1px solid #2a2a4a", borderRadius: 10, padding: "10px 14px", color: "#f0f0f0", fontSize: 14, outline: "none" },
  sinp: { background: "#0d0d1f", border: "1px solid #2a2a4a", borderRadius: 8, padding: "6px 8px", color: "#f0f0f0", fontSize: 12, outline: "none" },
  btn: { background: "linear-gradient(135deg,#7c3aed,#2563eb)", border: "none", color: "#fff", borderRadius: 10, padding: "11px 20px", fontWeight: 700, fontSize: 15, cursor: "pointer", width: "100%" },
  bsm: { background: "linear-gradient(135deg,#7c3aed,#2563eb)", border: "none", color: "#fff", borderRadius: 8, padding: "6px 12px", fontWeight: 600, fontSize: 12, cursor: "pointer", whiteSpace: "nowrap" },
  bgh: { background: "#1f1f3a", border: "1px solid #2a2a4a", color: "#c0c0e0", borderRadius: 8, padding: "6px 12px", fontWeight: 600, fontSize: 12, cursor: "pointer", whiteSpace: "nowrap" },
  bred: { background: "#3a1420", border: "1px solid #ef444466", color: "#fca5a5", borderRadius: 8, padding: "6px 12px", fontWeight: 600, fontSize: 12, cursor: "pointer", whiteSpace: "nowrap" },
  chip: { display: "inline-flex", alignItems: "center", gap: 4, borderRadius: 20, padding: "3px 10px", fontSize: 12, fontWeight: 600, whiteSpace: "nowrap" },
  fr: { display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 8 },
  fb: { background: "#12122a", border: "1px solid #2a2a4a", color: "#a0a0c0", borderRadius: 20, padding: "5px 14px", fontSize: 12, cursor: "pointer", fontWeight: 600 },
  fba: { background: "linear-gradient(135deg,#7c3aed44,#2563eb44)", border: "1px solid #7c3aed", color: "#a78bfa" },
  tbl: { width: "100%", borderCollapse: "collapse", minWidth: 640 },
  th: { textAlign: "left", padding: "9px 10px", color: "#6666aa", fontSize: 12, borderBottom: "1px solid #2a2a4a", whiteSpace: "nowrap" },
  td: { padding: "10px", borderBottom: "1px solid #1a1a2e", fontSize: 13, verticalAlign: "top" },
  ov: { position: "fixed", inset: 0, background: "rgba(0,0,0,0.75)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 200, padding: 16 },
  modal: { background: "#12122a", border: "1px solid #2a2a4a", borderRadius: 20, padding: 24, maxWidth: 440, width: "100%" },
  toast: { position: "fixed", bottom: 20, right: 20, left: 20, maxWidth: 420, marginLeft: "auto", background: "#1a1a2e", border: "1px solid #2a2a4a", borderRadius: 12, padding: "12px 18px", fontSize: 13, fontWeight: 600, zIndex: 999, boxShadow: "0 8px 32px rgba(0,0,0,0.4)" },
  muted: { color: "#8888aa", fontSize: 12 },
};

async function admin(action, body = {}) {
  const { data, error } = await sb.functions.invoke("myboost-admin", { body: { action, ...body } });
  if (error) {
    let msg = error.message;
    try { const j = await error.context.json(); msg = j.error || msg; } catch (_) {}
    throw new Error(msg);
  }
  if (data && data.error) throw new Error(data.error);
  return data;
}

function Status({ s }) {
  return <span style={{ ...S.chip, background: (SC[s] || "#888") + "22", color: SC[s] || "#888" }}>{s}</span>;
}

/* ---------------- Auth ---------------- */
function AuthScreen({ toast }) {
  const [mode, setMode] = useState("in");
  const [f, setF] = useState({ name: "", email: "", pass: "" });
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState("");

  const go = async () => {
    setMsg(""); setBusy(true);
    try {
      if (mode === "in") {
        const { error } = await sb.auth.signInWithPassword({ email: f.email.trim(), password: f.pass });
        if (error) throw error;
      } else if (mode === "up") {
        if (f.pass.length < 8) throw new Error("Password must be at least 8 characters.");
        const { data, error } = await sb.auth.signUp({
          email: f.email.trim(), password: f.pass,
          options: { data: { name: f.name.trim() }, emailRedirectTo: window.location.origin },
        });
        if (error) throw error;
        if (!data.session) setMsg("Check your email to confirm your account, then sign in.");
      } else {
        const { error } = await sb.auth.resetPasswordForEmail(f.email.trim(), { redirectTo: window.location.origin });
        if (error) throw error;
        setMsg("If that email has an account, a reset link is on its way.");
      }
    } catch (e) { setMsg(e.message); }
    setBusy(false);
  };
  const key = (e) => e.key === "Enter" && go();

  return (
    <div style={{ ...S.app, display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
      <div style={{ ...S.modal, maxWidth: 380, textAlign: "center" }}>
        <div style={{ fontSize: 44, marginBottom: 10 }}>⚡</div>
        <div style={{ ...S.logo, fontSize: 26, display: "block", marginBottom: 4 }}>MyBoost</div>
        <div style={{ color: "#6666aa", marginBottom: 20, fontSize: 13 }}>Private Social Growth Platform</div>
        <div style={{ ...S.fr, justifyContent: "center" }}>
          {[["in", "Sign in"], ["up", "Create account"]].map(([m, l]) => (
            <button key={m} style={{ ...S.fb, ...(mode === m ? S.fba : {}) }} onClick={() => { setMode(m); setMsg(""); }}>{l}</button>
          ))}
        </div>
        {mode === "up" && <div style={{ textAlign: "left", marginBottom: 12 }}>
          <label style={S.label}>Your name</label>
          <input style={S.inp} value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} onKeyDown={key} />
        </div>}
        <div style={{ textAlign: "left", marginBottom: 12 }}>
          <label style={S.label}>Email</label>
          <input style={S.inp} type="email" autoComplete="email" value={f.email} onChange={(e) => setF({ ...f, email: e.target.value })} onKeyDown={key} />
        </div>
        {mode !== "reset" && <div style={{ textAlign: "left", marginBottom: 16 }}>
          <label style={S.label}>Password</label>
          <input style={S.inp} type="password" autoComplete={mode === "up" ? "new-password" : "current-password"} value={f.pass} onChange={(e) => setF({ ...f, pass: e.target.value })} onKeyDown={key} />
        </div>}
        {msg && <div style={{ color: "#fbbf24", fontSize: 12, marginBottom: 10 }}>{msg}</div>}
        <button style={{ ...S.btn, opacity: busy ? 0.6 : 1 }} disabled={busy} onClick={go}>
          {mode === "in" ? "Sign In →" : mode === "up" ? "Create Account →" : "Send reset link"}
        </button>
        <div style={{ marginTop: 12 }}>
          <button style={{ ...S.nb, fontSize: 12 }} onClick={() => { setMode(mode === "reset" ? "in" : "reset"); setMsg(""); }}>
            {mode === "reset" ? "Back to sign in" : "Forgot password?"}
          </button>
        </div>
      </div>
    </div>
  );
}

function SetPassword({ done, toast }) {
  const [p, setP] = useState("");
  const save = async () => {
    if (p.length < 8) return toast("Password must be at least 8 characters.", "error");
    const { error } = await sb.auth.updateUser({ password: p });
    if (error) return toast(error.message, "error");
    toast("Password updated"); done();
  };
  return (
    <div style={S.ov}><div style={S.modal}>
      <h2 style={{ fontSize: 18, fontWeight: 700, marginBottom: 14 }}>Set a new password</h2>
      <input style={{ ...S.inp, marginBottom: 14 }} type="password" autoComplete="new-password" value={p} onChange={(e) => setP(e.target.value)} />
      <button style={S.btn} onClick={save}>Save password</button>
    </div></div>
  );
}

/* ---------------- Store ---------------- */
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 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) < Number(sp.price)) 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 <>
    <h1 style={S.h1}>🚀 Growth Packages</h1>
    <p style={{ color: "#6666aa", marginBottom: 18, fontSize: 13 }}>Boost your Instagram, Facebook & YouTube</p>
    <div style={S.fr}>{["all", "instagram", "facebook", "youtube"].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", "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(pkg.price)}</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(sp.price)}</div>
          </div>
        </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 - sp.price))}</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>}
  </>;
}

/* ---------------- My Orders ---------------- */
function MyOrders({ orders, profile }) {
  const mine = orders.filter((o) => o.user_id === profile.id);
  return <>
    <h1 style={S.h1}>📦 My Orders</h1>
    {mine.length === 0
      ? <div style={{ ...S.card, textAlign: "center", color: "#6666aa", padding: 40 }}>No orders yet — head to the Store!</div>
      : <div style={S.card}><table style={S.tbl}>
        <thead><tr>{["#", "Package", "Qty", "Link", "Price", "Status", "Date"].map((h) => <th key={h} style={S.th}>{h}</th>)}</tr></thead>
        <tbody>{mine.map((o) => (
          <tr key={o.id}>
            <td style={S.td}>#{o.id}</td>
            <td style={S.td}>{PI[o.myboost_packages?.platform]} {o.myboost_packages?.name}</td>
            <td style={S.td}>{o.qty.toLocaleString()}</td>
            <td style={{ ...S.td, maxWidth: 160, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{o.link}</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} /></td>
            <td style={S.td}>{o.created_at.slice(0, 10)}</td>
          </tr>))}</tbody>
      </table></div>}
  </>;
}

/* ---------------- Guide ---------------- */
function Guide() {
  const Step = ({ n, t, d, c }) => (
    <div style={{ display: "flex", gap: 14, marginBottom: 14, alignItems: "flex-start" }}>
      <div style={{ minWidth: 30, height: 30, borderRadius: "50%", background: c, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 13, color: "#fff" }}>{n}</div>
      <div><div style={{ fontWeight: 700, fontSize: 14, marginBottom: 3 }}>{t}</div><div style={{ color: "#a0a0c0", fontSize: 13, lineHeight: 1.6, whiteSpace: "pre-line" }}>{d}</div></div>
    </div>);
  const faq = [
    ["How long does delivery take?", "Most orders start within a few hours. Each package card shows its expected delivery time."],
    ["How do I add money to my balance?", "Pay the admin via Cash App, Venmo, Zelle, or PayPal. Once received, they top up your balance and you'll see it update."],
    ["Will my account get banned?", "Instagram, Facebook and YouTube rules don't allow bought engagement, so there is always some risk. Order small amounts, spread orders over time, and keep posting real content."],
    ["What if my order is cancelled or only partly delivered?", "The unused amount is refunded to your MyBoost balance automatically when the admin refreshes order statuses."],
    ["Can I order for someone else's account?", "Only for accounts you own or have permission to boost."],
  ];
  return <>
    <h1 style={S.h1}>📖 How-To Guide</h1>
    <div style={{ ...S.card, borderLeft: "4px solid #a78bfa" }}>
      <div style={{ fontSize: 16, fontWeight: 800, color: "#a78bfa", marginBottom: 12 }}>🚀 Getting Started</div>
      <Step n="1" c="#7c3aed" t="Create your account" d="Use 'Create account' on the sign-in screen with your email and a password. Confirm your email if asked." />
      <Step n="2" c="#7c3aed" t="Get a balance" d="Pay the admin (Cash App, Venmo, Zelle, or PayPal). They add it to your balance (💰 top right)." />
      <Step n="3" c="#7c3aed" t="Browse the Store" d="Filter by platform or type, then click Buy Now." />
    </div>
    <div style={{ ...S.card, borderLeft: "4px solid #10b981" }}>
      <div style={{ fontSize: 16, fontWeight: 800, color: "#10b981", marginBottom: 12 }}>🛒 Placing an Order</div>
      <Step n="1" c="#059669" t="Pick a package" d="Click Buy Now on the package you want." />
      <Step n="2" c="#059669" t="Paste the right link" d={"Followers / subscribers → your profile or channel link\n• instagram.com/yourhandle\n• facebook.com/yourpage\n• youtube.com/@yourchannel\nLikes / comments / shares → the link to that one post or video"} />
      <Step n="3" c="#059669" t="Make sure the account is public" d="Private accounts can't receive orders and will be cancelled (and refunded)." />
      <Step n="4" c="#059669" t="Confirm" d="The price comes off your balance and the order shows in 📦 Orders." />
    </div>
    <div style={{ ...S.card, borderLeft: "4px solid #3b82f6" }}>
      <div style={{ fontSize: 16, fontWeight: 800, color: "#3b82f6", marginBottom: 12 }}>📦 Order Statuses</div>
      {[["pending", "Received — waiting for the admin to send it"], ["processing", "Sent — delivery in progress"], ["completed", "Done — check your account"], ["partial", "Only part delivered — the rest is refunded to your balance"], ["cancelled", "Not delivered — refunded to your balance"]].map(([s, d]) => (
        <div key={s} style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 10 }}><span style={{ minWidth: 90 }}><Status s={s} /></span><span style={{ color: "#a0a0c0", fontSize: 13 }}>{d}</span></div>))}
    </div>
    <div style={{ ...S.card, borderLeft: "4px solid #f59e0b" }}>
      <div style={{ fontSize: 16, fontWeight: 800, color: "#f59e0b", marginBottom: 14 }}>❓ FAQ</div>
      {faq.map(([q, a]) => <div key={q} style={{ marginBottom: 14 }}><div style={{ fontWeight: 700, fontSize: 14, marginBottom: 4 }}>Q: {q}</div><div style={{ color: "#a0a0c0", fontSize: 13, lineHeight: 1.6 }}>A: {a}</div></div>)}
    </div>
  </>;
}

/* ---------------- Admin ---------------- */
function AdminOrders({ orders, 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 send = (o) => run(o.id, async () => {
    let comments;
    if (o.myboost_packages?.type === "comments" && window.confirm("Is this a CUSTOM comments service (you supply the text)? Click OK to enter comments, Cancel to skip.")) {
      comments = window.prompt("Type the comments separated by |  (example: Love this! | So cute | Great video)");
      if (comments) comments = comments.split("|").map((s) => s.trim()).filter(Boolean).join("\n");
    }
    const r = await admin("send_order", { order_id: o.id, comments });
    toast(`Sent! SMMFollows order #${r.smm_order_id}`);
  });
  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>}
  </div>;
}

function AdminUsers({ users, me, reload, toast }) {
  const [amt, setAmt] = useState({});
  const top = async (u, a) => {
    const n = Number(a);
    if (!(n > 0)) return toast("Enter an amount", "error");
    try { await admin("topup", { user_id: u.id, amount: n }); toast(`Added ${money(n)} to ${u.name}`); setAmt({ ...amt, [u.id]: "" }); }
    catch (e) { toast(e.message, "error"); }
    reload();
  };
  const role = async (u) => {
    const r = u.role === "admin" ? "member" : "admin";
    if (!window.confirm(`Make ${u.name} ${r === "admin" ? "an admin" : "a member"}?`)) return;
    try { await admin("set_role", { user_id: u.id, role: r }); toast("Role updated"); } catch (e) { toast(e.message, "error"); }
    reload();
  };
  return <div style={S.card}>
    <p style={{ ...S.muted, marginBottom: 12 }}>Members appear here after they create an account on this site. Top up only after you've received their payment.</p>
    <table style={S.tbl}>
      <thead><tr>{["Name", "Email", "Role", "Balance", "Top up"].map((h) => <th key={h} style={S.th}>{h}</th>)}</tr></thead>
      <tbody>{users.map((u) => (
        <tr key={u.id}>
          <td style={S.td}>{u.name}</td>
          <td style={S.td}>{u.email}</td>
          <td style={S.td}><span style={{ ...S.chip, background: u.role === "admin" ? "#a78bfa22" : "#10b98122", color: u.role === "admin" ? "#a78bfa" : "#10b981" }}>{u.role}</span>
            {u.id !== me.id && <div><button style={{ ...S.nb, fontSize: 11, padding: "4px 0" }} onClick={() => role(u)}>change</button></div>}</td>
          <td style={S.td}>{money(u.balance)}</td>
          <td style={S.td}><div style={{ display: "flex", gap: 5, flexWrap: "wrap" }}>
            {[10, 25, 50].map((a) => <button key={a} style={S.bgh} onClick={() => top(u, a)}>+${a}</button>)}
            <input style={{ ...S.sinp, width: 70 }} type="number" min="0" step="0.01" placeholder="$" value={amt[u.id] || ""} onChange={(e) => setAmt({ ...amt, [u.id]: e.target.value })} />
            <button style={S.bsm} onClick={() => top(u, amt[u.id])}>Add</button>
          </div></td>
        </tr>))}</tbody>
    </table>
  </div>;
}

function AdminPackages({ packages, reload, toast }) {
  const [info, setInfo] = useState({});
  const [edit, setEdit] = useState({});
  const [pick, setPick] = useState(null);
  const [q, setQ] = useState("");
  const [res, setRes] = useState(null);
  const [busy, setBusy] = useState(false);

  const loadInfo = useCallback(async () => {
    const ids = packages.map((p) => p.smm_service_id).filter(Boolean);
    if (!ids.length) return;
    try { const r = await admin("service_info", { ids }); const m = {}; r.results.forEach((s) => (m[s.service] = s)); setInfo(m); } catch (e) { toast(e.message, "error"); }
  }, [packages]);
  useEffect(() => { loadInfo(); }, [loadInfo]);

  const save = async (p, id) => {
    try { await admin("set_service", { package_id: p.id, smm_service_id: id === "" ? null : id }); toast(`Saved service for ${p.name}`); setPick(null); setRes(null); }
    catch (e) { toast(e.message, "error"); }
    reload();
  };
  const savePrice = async (p) => {
    const v = Number(edit[p.id]);
    if (!(v >= 0)) return;
    try { await admin("update_package", { package_id: p.id, price: v }); toast("Price saved"); setEdit({ ...edit, [p.id]: undefined }); } catch (e) { toast(e.message, "error"); }
    reload();
  };
  const toggle = async (p) => { try { await admin("update_package", { package_id: p.id, active: !p.active }); } catch (e) { toast(e.message, "error"); } reload(); };
  const search = async () => {
    setBusy(true);
    try { setRes(await admin("search_services", { q })); } catch (e) { toast(e.message, "error"); }
    setBusy(false);
  };
  const openPick = (p) => { setPick(p); setQ(`${p.platform} ${p.type === "followers" && p.platform === "youtube" ? "subscribers" : p.type}`); setRes(null); };
  const cost = (p, s) => (s ? (Number(s.rate) * p.qty) / 1000 : null);

  return <>
    <div style={S.card}>
      <p style={{ ...S.muted, marginBottom: 12 }}>Each package needs an SMMFollows service ID before its orders can be sent. Cost = what SMMFollows charges you; Profit = price − cost.</p>
      <table style={S.tbl}>
        <thead><tr>{["Package", "Qty", "Price", "SMM service", "Cost", "Profit", "On"].map((h) => <th key={h} style={S.th}>{h}</th>)}</tr></thead>
        <tbody>{packages.map((p) => {
          const s = info[p.smm_service_id]; const c = cost(p, s);
          const qtyBad = s && (p.qty < Number(s.min) || p.qty > Number(s.max));
          return <tr key={p.id} style={{ opacity: p.active ? 1 : 0.5 }}>
            <td style={S.td}>{PI[p.platform]} {p.name}<div style={S.muted}>{p.type}</div></td>
            <td style={S.td}>{p.qty.toLocaleString()}</td>
            <td style={S.td}><div style={{ display: "flex", gap: 4 }}>
              <input style={{ ...S.sinp, width: 70 }} type="number" step="0.01" value={edit[p.id] ?? p.price} onChange={(e) => setEdit({ ...edit, [p.id]: e.target.value })} />
              {edit[p.id] !== undefined && <button style={S.bsm} onClick={() => savePrice(p)}>Save</button>}</div></td>
            <td style={{ ...S.td, maxWidth: 260 }}>
              {p.smm_service_id ? <><b>#{p.smm_service_id}</b> <span style={S.muted}>{s ? s.name.slice(0, 80) : "(not found)"}</span></> : <span style={{ color: "#f59e0b" }}>Not set</span>}
              {qtyBad && <div style={{ color: "#fca5a5", fontSize: 11 }}>Qty outside service min {s.min} / max {s.max}</div>}
              <div><button style={{ ...S.bgh, marginTop: 6 }} onClick={() => openPick(p)}>{p.smm_service_id ? "Change" : "Choose"}</button></div>
            </td>
            <td style={S.td}>{c != null ? money(c) : "—"}</td>
            <td style={{ ...S.td, color: c != null && p.price - c < 0 ? "#ef4444" : "#10b981" }}>{c != null ? money(p.price - c) : "—"}</td>
            <td style={S.td}><input type="checkbox" checked={p.active} onChange={() => toggle(p)} /></td>
          </tr>;
        })}</tbody>
      </table>
    </div>

    {pick && <div style={S.ov} onClick={(e) => e.target === e.currentTarget && setPick(null)}>
      <div style={{ ...S.modal, maxWidth: 820, maxHeight: "88vh", overflowY: "auto" }}>
        <h2 style={{ fontSize: 17, fontWeight: 700, marginBottom: 4 }}>Choose service for {pick.name}</h2>
        <div style={{ ...S.muted, marginBottom: 12 }}>{pick.qty.toLocaleString()} units · you charge {money(pick.price)}. Results are cheapest first — check the name for quality, refill and speed.</div>
        <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
          <input style={S.inp} value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => e.key === "Enter" && search()} placeholder="e.g. instagram followers refill" />
          <button style={{ ...S.bsm, padding: "0 16px" }} onClick={search} disabled={busy}>{busy ? "…" : "Search"}</button>
        </div>
        <div style={{ display: "flex", gap: 8, marginBottom: 12, alignItems: "center" }}>
          <span style={S.muted}>Or enter an ID:</span>
          <input style={{ ...S.sinp, width: 100 }} id="manualId" type="number" />
          <button style={S.bgh} onClick={() => save(pick, document.getElementById("manualId").value)}>Use ID</button>
          {pick.smm_service_id && <button style={S.bred} onClick={() => save(pick, "")}>Clear</button>}
        </div>
        {res && <div style={S.muted}>{res.total} match(es){res.total > 60 ? " — showing cheapest 60; add words to narrow" : ""}</div>}
        {res && res.results.map((s) => {
          const c = cost(pick, s); const ok = pick.qty >= Number(s.min) && pick.qty <= Number(s.max);
          return <div key={s.service} style={{ borderBottom: "1px solid #2a2a4a", padding: "10px 0", display: "flex", gap: 10, alignItems: "center" }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13 }}><b>#{s.service}</b> {s.name}</div>
              <div style={S.muted}>{s.category} · ${s.rate}/1000 · min {s.min} · max {s.max}{s.refill ? " · refill ✓" : ""}{s.cancel ? " · cancel ✓" : ""}</div>
              <div style={{ fontSize: 12, color: ok ? (pick.price - c >= 0 ? "#10b981" : "#ef4444") : "#fca5a5" }}>
                {ok ? `Your cost ${money(c)} · profit ${money(pick.price - c)}` : "Package quantity is outside this service's min/max"}</div>
            </div>
            <button style={S.bsm} disabled={!ok} onClick={() => save(pick, s.service)}>Use</button>
          </div>;
        })}
        <button style={{ ...S.bgh, marginTop: 14 }} onClick={() => setPick(null)}>Close</button>
      </div>
    </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"]].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" && <AdminPackages {...props} />}
  </>;
}

/* ---------------- App ---------------- */
function App() {
  const [session, setSession] = useState(undefined);
  const [profile, setProfile] = useState(null);
  const [packages, setPackages] = useState([]);
  const [orders, setOrders] = useState([]);
  const [users, setUsers] = useState([]);
  const [page, setPage] = useState("store");
  const [toastMsg, setToastMsg] = useState(null);
  const [recovery, setRecovery] = useState(false);

  const toast = (msg, type = "success") => { setToastMsg({ msg, type }); setTimeout(() => setToastMsg(null), 4500); };

  useEffect(() => {
    sb.auth.getSession().then(({ data }) => setSession(data.session));
    const { data: sub } = sb.auth.onAuthStateChange((ev, s) => { setSession(s); if (ev === "PASSWORD_RECOVERY") setRecovery(true); });
    return () => sub.subscription.unsubscribe();
  }, []);

  const load = useCallback(async () => {
    if (!session) return;
    const { data: p, error } = await sb.rpc("myboost_ensure_profile", { p_name: session.user.user_metadata?.name || "" });
    if (error) return toast(error.message, "error");
    setProfile(p);
    const [pk, od] = await Promise.all([
      sb.from("myboost_packages").select("*").order("id"),
      sb.from("myboost_orders").select("*, myboost_packages(name, platform, type), myboost_profiles(name, email)").order("id", { ascending: false }).limit(500),
    ]);
    setPackages(pk.data || []); setOrders(od.data || []);
    if (p.role === "admin") {
      const { data: us } = await sb.from("myboost_profiles").select("*").order("created_at");
      setUsers(us || []);
    }
  }, [session]);
  useEffect(() => { load(); }, [load]);

  if (session === undefined) return <div style={{ ...S.app, display: "flex", alignItems: "center", justifyContent: "center" }}>Loading…</div>;
  if (!session) return <>
    <AuthScreen toast={toast} />
    {toastMsg && <div style={{ ...S.toast, color: toastMsg.type === "error" ? "#ef4444" : "#10b981" }}>{toastMsg.msg}</div>}
  </>;
  if (!profile) return <div style={{ ...S.app, display: "flex", alignItems: "center", justifyContent: "center" }}>Loading your account…</div>;

  const isAdmin = profile.role === "admin";
  return (
    <div style={S.app}>
      <nav style={S.nav}>
        <div style={S.logo}>⚡ MyBoost</div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
          {["store", "orders", "guide", ...(isAdmin ? ["admin"] : [])].map((p) => (
            <button key={p} style={{ ...S.nb, ...(page === p ? S.nba : {}) }} onClick={() => { setPage(p); load(); }}>
              {p === "store" ? "🛍 Store" : p === "orders" ? "📦 Orders" : p === "guide" ? "📖 How-To" : "⚙️ Admin"}
            </button>))}
          <div style={S.badge}>💰 {money(profile.balance)}</div>
          <button style={{ ...S.nb, fontSize: 12 }} onClick={() => sb.auth.signOut()}>👋 Sign out</button>
        </div>
      </nav>
      <div style={S.main}>
        {page === "store" && <Store packages={packages} profile={profile} onOrdered={load} toast={toast} />}
        {page === "orders" && <MyOrders orders={orders} profile={profile} />}
        {page === "guide" && <Guide />}
        {page === "admin" && isAdmin && <Admin orders={orders} users={users} packages={packages} me={profile} reload={load} toast={toast} />}
      </div>
      <footer style={{ textAlign: "center", color: "#44446a", fontSize: 11, padding: "20px 0 30px" }}>MyBoost · built by SoHo Media House · private members platform</footer>
      {recovery && <SetPassword done={() => setRecovery(false)} toast={toast} />}
      {toastMsg && <div style={{ ...S.toast, borderColor: toastMsg.type === "error" ? "#ef4444" : "#10b981", color: toastMsg.type === "error" ? "#ef4444" : "#10b981" }}>
        {toastMsg.type === "error" ? "❌" : "✅"} {toastMsg.msg}</div>}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
