// MyBoost: Engagement Circle — real members engage with each other's new posts (loaded after welcome.jsx)
const CIRCLE_FN = SB_URL + "/functions/v1/myboost-circle-hook";
const CIRCLE_HOST = {
  instagram: /^https:\/\/([a-z0-9-]+\.)*(instagram\.com|instagr\.am)\//i,
  facebook: /^https:\/\/([a-z0-9-]+\.)*(facebook\.com|fb\.com|fb\.me|fb\.watch)\//i,
  youtube: /^https:\/\/([a-z0-9-]+\.)*(youtube\.com|youtu\.be)\//i,
  tiktok: /^https:\/\/([a-z0-9-]+\.)*tiktok\.com\//i,
};
const CIRCLE_DEFAULT_IDEAS = [
  "Love this! 🔥", "This is so helpful, thank you for sharing", "Great tip 👏", "Saving this for later!",
  "So true 💯", "Beautiful work ✨", "Needed this today 🙌", "Congrats, well deserved!",
];
const ago = (t) => { const m = Math.round((Date.now() - new Date(t)) / 60000); return m < 60 ? `${m}m ago` : m < 1440 ? `${Math.round(m / 60)}h ago` : `${Math.round(m / 1440)}d ago`; };
const guessPlatform = (u) => Object.keys(CIRCLE_HOST).find((k) => CIRCLE_HOST[k].test(u)) || "";

async function circleFeed() {
  const { data, error } = await sb.rpc("myboost_circle_feed");
  if (error) throw error;
  return data || [];
}
const circleTodo = (feed) => feed.filter((p) => !p.is_mine && !p.my_skipped && !(p.my_liked || p.my_commented));
window.circleTodoCount = 0;

/* Badge + phone notification while the app is open */
function useCircleBadge(profile) {
  const [n, setN] = useState(0);
  useEffect(() => {
    if (!profile || !profile.circle_joined) { setN(0); return; }
    let seen = null, alive = true;
    const tick = async () => {
      try {
        const todo = circleTodo(await circleFeed());
        if (!alive) return;
        setN(todo.length);
        try { navigator.setAppBadge && (todo.length ? navigator.setAppBadge(todo.length) : navigator.clearAppBadge()); } catch (e) {}
        const ids = new Set(todo.map((p) => p.id));
        if (seen) {
          const fresh = todo.filter((p) => !seen.has(p.id));
          if (fresh.length && window.Notification && Notification.permission === "granted" && document.visibilityState !== "visible") {
            try { new Notification("MyBoost Circle", { body: `${fresh[0].owner_name} just posted. Show some love! 🤝`, icon: "/icon-192.png" }); } catch (e) {}
          }
        }
        seen = ids;
      } catch (e) {}
    };
    tick();
    const t = setInterval(tick, 120000);
    return () => { alive = false; clearInterval(t); };
  }, [profile && profile.id, profile && profile.circle_joined]);
  return n;
}

function CircleJoin({ profile, reload, toast }) {
  const [busy, setBusy] = useState(false);
  const join = async () => {
    setBusy(true);
    const { error } = await sb.rpc("myboost_circle_join", { p_join: true });
    setBusy(false);
    if (error) return toast(error.message, "error");
    try { window.Notification && Notification.permission === "default" && Notification.requestPermission(); } catch (e) {}
    toast("Welcome to the Circle 🤝"); reload();
  };
  return <div style={S.card}>
    <h1 style={S.h1}>🤝 Engagement Circle</h1>
    <div style={{ color: "#a0a0c0", fontSize: 14, lineHeight: 1.7, marginBottom: 14 }}>
      Real people supporting real people. When a member posts, everyone in the Circle gets it on their list.
      You open it, like it, and leave a genuine comment. When you post, they do the same for you.
      <br /><br />
      <b style={{ color: "#f0f0f0" }}>The deal:</b> give before you get. Engage with others' posts, and share up to 3 of your own a day.
      Only real members, no bots, so the likes and comments you get are from real people.
    </div>
    <button style={S.btn} disabled={busy} onClick={join}>🤝 Join the Circle</button>
  </div>;
}

function CircleShare({ accounts, onShared, toast }) {
  const [url, setUrl] = useState("");
  const [note, setNote] = useState("");
  const [busy, setBusy] = useState(false);
  const share = async () => {
    let u = url.trim();
    if (u && !/^https?:\/\//i.test(u)) u = "https://" + u;
    u = u.replace(/^http:\/\//i, "https://");
    const pf = guessPlatform(u);
    if (!pf) return toast("Paste a link to an Instagram, Facebook, YouTube or TikTok post", "error");
    setBusy(true);
    const { error } = await sb.rpc("myboost_circle_share", { p_url: u, p_platform: pf, p_note: note });
    setBusy(false);
    if (error) return toast(error.message, "error");
    setUrl(""); setNote(""); toast("Shared with the Circle"); onShared();
  };
  return <div style={S.card}>
    <div style={{ fontWeight: 700, marginBottom: 10 }}>📣 Share a new post</div>
    <input style={{ ...S.inp, marginBottom: 8 }} placeholder="paste the link to your new post or video" value={url} onChange={(e) => setUrl(e.target.value)} />
    <input style={{ ...S.inp, marginBottom: 10 }} maxLength={280} placeholder="optional: what should people comment on? (e.g. 'tell me your favorite tip')" value={note} onChange={(e) => setNote(e.target.value)} />
    <button style={S.bsm} disabled={busy || !url.trim()} onClick={share}>Share with the Circle</button>
    <div style={{ ...S.muted, marginTop: 8 }}>Post through Buffer or Zapier? Set up ⚙️ Auto-share below once, and new posts land here on their own.</div>
  </div>;
}

function CirclePostCard({ p, ideas, onMark }) {
  const [idea, setIdea] = useState(() => ideas[Math.floor(Math.random() * ideas.length)] || "");
  const [opened, setOpened] = useState(false);
  const another = () => setIdea(ideas[Math.floor(Math.random() * ideas.length)] || "");
  const copy = async () => { try { await navigator.clipboard.writeText(idea); } catch (e) {} };
  const done = p.my_liked || p.my_commented;
  return <div style={{ ...S.pc, borderColor: done ? "#10b98155" : "#2a2a4a" }}>
    <div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center" }}>
      <div style={{ fontWeight: 700 }}>{PI[p.platform] || "🔗"} {p.is_mine ? "Your post" : p.owner_name}</div>
      <span style={S.muted}>{ago(p.created_at)}</span>
    </div>
    {p.note && <div style={{ fontSize: 13, color: "#c0c0e0" }}>💡 {p.note}</div>}
    <a href={p.post_url} target="_blank" rel="noopener noreferrer" onClick={() => setOpened(true)}
      style={{ ...S.bsm, textAlign: "center", textDecoration: "none", padding: "9px 12px", fontSize: 13 }}>Open post ↗</a>
    {p.is_mine ? <div style={S.muted}>❤️ {p.likes} liked · 💬 {p.comments} commented · stays on the list for 3 days</div> : <>
      {ideas.length > 0 && <div style={{ background: "#0d0d1f", border: "1px solid #2a2a4a", borderRadius: 10, padding: 10, fontSize: 13 }}>
        <div style={{ ...S.muted, marginBottom: 4 }}>Comment idea (make it your own):</div>
        <div style={{ marginBottom: 8 }}>{idea}</div>
        <div style={{ display: "flex", gap: 6 }}>
          <button style={S.bgh} onClick={copy}>Copy</button>
          <button style={S.bgh} onClick={another}>Another idea</button>
        </div>
      </div>}
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
        <button style={{ ...S.bgh, ...(p.my_liked ? { borderColor: "#10b981", color: "#10b981" } : {}) }} onClick={() => onMark(p, "liked", !p.my_liked)}>{p.my_liked ? "✅" : "❤️"} I liked it</button>
        <button style={{ ...S.bgh, ...(p.my_commented ? { borderColor: "#10b981", color: "#10b981" } : {}) }} onClick={() => onMark(p, "commented", !p.my_commented)}>{p.my_commented ? "✅" : "💬"} I commented</button>
        {!done && <button style={{ ...S.bgh, color: "#8888aa" }} onClick={() => onMark(p, "skipped", true)}>Skip</button>}
      </div>
      {!opened && !done && <div style={S.muted}>Open the post first, then tap what you did.</div>}
    </>}
  </div>;
}

function CircleAutoShare({ accounts, reload, toast }) {
  const [open, setOpen] = useState(false);
  const toggle = async (a) => {
    const { error } = await sb.from("myboost_accounts").update({ circle_on: !a.circle_on }).eq("id", a.id);
    if (error) return toast(error.message, "error");
    reload();
  };
  const copy = async (t) => { try { await navigator.clipboard.writeText(t); toast("Copied"); } catch (e) { toast("Copy failed, press and hold to copy", "error"); } };
  return <div style={S.card}>
    <div style={{ display: "flex", justifyContent: "space-between", cursor: "pointer" }} onClick={() => setOpen(!open)}>
      <div style={{ fontWeight: 700 }}>⚙️ Auto-share my new posts <span style={S.muted}>· for Buffer / Zapier users</span></div>
      <span style={S.muted}>{open ? "Hide" : "Show"}</span>
    </div>
    {open && <div style={{ marginTop: 12 }}>
      {!accounts.length && <div style={S.muted}>Save your profile links first under 🛍 Store → 🔗 My accounts.</div>}
      {accounts.map((a) => {
        const hook = `${CIRCLE_FN}?t=${a.hook_token}`;
        return <div key={a.id} style={{ borderTop: "1px solid #2a2a4a", padding: "10px 0" }}>
          <div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center", marginBottom: 6 }}>
            <div style={{ fontSize: 13, wordBreak: "break-all" }}>{PI[a.platform]} {a.url}</div>
            <button style={a.circle_on ? S.bsm : S.bgh} onClick={() => toggle(a)}>{a.circle_on ? "Auto-share ON" : "Auto-share OFF"}</button>
          </div>
          <div style={{ display: "flex", gap: 6 }}>
            <input readOnly style={{ ...S.sinp, flex: 1 }} value={hook} onFocus={(e) => e.target.select()} />
            <button style={S.bgh} onClick={() => copy(hook)}>Copy</button>
          </div>
        </div>;
      })}
      {accounts.length > 0 && <div style={{ color: "#a0a0c0", fontSize: 13, lineHeight: 1.7, marginTop: 8 }}>
        <b>Zapier setup (one time per account):</b><br />
        1. New Zap. Trigger: your posting app (Buffer → "New Sent Update", or Instagram/Facebook Pages → "New Post").<br />
        2. Action: <b>Webhooks by Zapier → POST</b>.<br />
        3. URL: paste the link above for that account. Payload type: JSON.<br />
        4. Data: key <b>url</b>, value = the post link field from step 1.<br />
        5. Test, then turn the Zap on. New posts now show up in the Circle automatically.<br />
        <span style={S.muted}>Keep this link private. It only adds posts for this one account.</span>
      </div>}
    </div>}
  </div>;
}

function Circle({ profile, reload, toast }) {
  const [feed, setFeed] = useState(null);
  const [ideas, setIdeas] = useState(CIRCLE_DEFAULT_IDEAS);
  const [accounts, setAccounts] = useState([]);
  const [view, setView] = useState("todo");
  const load = useCallback(async () => {
    try { setFeed(await circleFeed()); } catch (e) { toast(e.message, "error"); setFeed([]); }
    const { data: ac } = await sb.from("myboost_accounts").select("*").eq("user_id", profile.id).order("id");
    setAccounts(ac || []);
  }, [profile.id]);
  useEffect(() => {
    if (!profile.circle_joined) return;
    load();
    sb.rpc("myboost_circle_comment_ideas").then(({ data }) => { if (data && data.length) setIdeas(data.map((r) => (typeof r === "string" ? r : r.myboost_circle_comment_ideas)).filter(Boolean)); });
  }, [profile.circle_joined, load]);

  if (!profile.circle_joined) return <CircleJoin profile={profile} reload={reload} toast={toast} />;

  const mark = async (p, kind, val) => {
    const { error } = await sb.rpc("myboost_circle_mark", { p_post: p.id, p_kind: kind, p_value: val });
    if (error) return toast(error.message, "error");
    load();
  };
  const leave = async () => {
    if (!window.confirm("Leave the Circle? Your posts will stop going out to members.")) return;
    const { error } = await sb.rpc("myboost_circle_join", { p_join: false });
    if (error) return toast(error.message, "error");
    reload();
  };
  const all = feed || [];
  const todo = circleTodo(all);
  const done = all.filter((p) => !p.is_mine && (p.my_liked || p.my_commented));
  const mine = all.filter((p) => p.is_mine);
  const list = view === "todo" ? todo : view === "done" ? done : mine;

  return <>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
      <h1 style={S.h1}>🤝 Engagement Circle</h1>
      <button style={{ ...S.nb, fontSize: 12 }} onClick={leave}>Leave Circle</button>
    </div>
    <div style={{ ...S.muted, marginBottom: 14 }}>Real members, real likes, real comments. Give before you get.</div>
    <CircleShare accounts={accounts} onShared={load} toast={toast} />
    <div style={{ ...S.fr, margin: "6px 0 0" }}>
      {[["todo", `📝 To do (${todo.length})`], ["done", `✅ Done (${done.length})`], ["mine", `📣 My posts (${mine.length})`]].map(([v, l]) =>
        <button key={v} style={{ ...S.fb, ...(view === v ? S.fba : {}) }} onClick={() => setView(v)}>{l}</button>)}
      <button style={S.fb} onClick={load}>🔄</button>
    </div>
    {feed === null ? <div style={{ ...S.muted, marginTop: 16 }}>Loading…</div> :
      !list.length ? <div style={{ ...S.card, marginTop: 14, color: "#a0a0c0" }}>
        {view === "todo" ? "All caught up 🎉 New posts from members will show up here." : view === "done" ? "Nothing yet. Posts you like or comment on show up here." : "You have no posts in the Circle right now. Share one above."}
      </div> :
      <div style={S.grid}>{list.map((p) => <CirclePostCard key={p.id} p={p} ideas={ideas} onMark={mark} />)}</div>}
    <div style={{ height: 16 }} />
    <CircleAutoShare accounts={accounts} reload={load} toast={toast} />
  </>;
}

function AdminCircle({ toast }) {
  const [rows, setRows] = useState(null);
  useEffect(() => { sb.rpc("myboost_circle_stats").then(({ data, error }) => { if (error) toast(error.message, "error"); setRows(data || []); }); }, []);
  if (!rows) return <div style={S.muted}>Loading…</div>;
  return <div style={S.card}>
    <div style={{ fontWeight: 700, marginBottom: 4 }}>🤝 Circle activity (last 30 days)</div>
    <div style={{ ...S.muted, marginBottom: 10 }}>Members who share a lot but rarely engage are taking more than they give.</div>
    <table style={S.tbl}><thead><tr>{["Member", "In Circle", "Posts shared", "Likes/comments given"].map((h) => <th key={h} style={S.th}>{h}</th>)}</tr></thead>
      <tbody>{rows.map((r) => <tr key={r.user_id}>
        <td style={S.td}>{r.name || r.email}<div style={S.muted}>{r.email}</div></td>
        <td style={S.td}>{r.joined ? "✅" : "—"}</td>
        <td style={S.td}>{r.shared_30d}</td>
        <td style={{ ...S.td, color: r.shared_30d > 0 && r.given_30d < r.shared_30d ? "#f59e0b" : "#f0f0f0" }}>{r.given_30d}</td>
      </tr>)}</tbody></table>
  </div>;
}

/* ---------------- Wiring: Circle tab inside the Store page, admin activity card ---------------- */
const __BaseStoreForCircle = window.Store;
window.Store = function StoreWithCircle(props) {
  const [mode, setMode] = useState(() => { try { return sessionStorage.getItem("myboost_mode") || "store"; } catch (e) { return "store"; } });
  const n = useCircleBadge(props.profile);
  const pick = (m) => { setMode(m); try { sessionStorage.setItem("myboost_mode", m); } catch (e) {} };
  return <>
    <div style={{ ...S.fr, marginBottom: 14 }}>
      <button style={{ ...S.fb, fontSize: 14, padding: "8px 18px", ...(mode === "store" ? S.fba : {}) }} onClick={() => pick("store")}>🛍 Store</button>
      <button style={{ ...S.fb, fontSize: 14, padding: "8px 18px", ...(mode === "circle" ? S.fba : {}) }} onClick={() => pick("circle")}>
        🤝 Engagement Circle{n > 0 && <span style={{ ...S.chip, background: "#ef4444", color: "#fff", padding: "0 7px", marginLeft: 6 }}>{n}</span>}
      </button>
    </div>
    {mode === "circle" ? <Circle profile={props.profile} reload={props.onOrdered} toast={props.toast} /> : <__BaseStoreForCircle {...props} />}
  </>;
};

const __BaseAdminForCircle = window.Admin;
window.Admin = function AdminWithCircle(props) {
  const [show, setShow] = useState(false);
  return <>
    <__BaseAdminForCircle {...props} />
    <div style={{ marginTop: 10 }}>
      <button style={S.fb} onClick={() => setShow(!show)}>🤝 {show ? "Hide" : "Show"} Circle activity</button>
      {show && <div style={{ marginTop: 10 }}><AdminCircle {...props} /></div>}
    </div>
  </>;
};
