// Competitor benchmarking — compare your reach/engagement/cadence vs tracked competitors.

function fmtNum(n) {
  if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
  if (n >= 1000) return `${(n / 1000).toFixed(1)}K`;
  return String(Math.round(n));
}

function BenchmarkingPage() {
  const hub = window.useClearCast();
  const data = hub.data || {};
  const competitors = data.competitors || [];
  const integrations = (data.integrations || []).filter((i) => i.connected);
  const [name, setName] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const yourFollowers = integrations.reduce((s, i) => s + (i.followers || 0), 0);
  const m = data.metrics || {};
  const yourEngagement = m.reach ? Math.round((m.engagement / m.reach) * 1000) / 10 : 4.5;
  const yourPostsPerWeek = (data.posts || []).length;

  const you = { id: "you", name: data.workspace?.name || "Your business", followers: yourFollowers, engagementRate: yourEngagement, postsPerWeek: yourPostsPerWeek, you: true };
  const rows = [you, ...competitors];
  const all = [you, ...competitors];
  const industry = competitors.length
    ? { followers: Math.round(all.reduce((s, r) => s + r.followers, 0) / all.length), engagementRate: Math.round((all.reduce((s, r) => s + r.engagementRate, 0) / all.length) * 10) / 10 }
    : null;

  const add = async () => {
    if (!name.trim()) { hub.toast("Enter a competitor name"); return; }
    setBusy(true);
    try { await hub.actions.addCompetitor({ name: name.trim() }); setName(""); }
    finally { setBusy(false); }
  };

  return (
    <div className="page benchmarking-page">
      <div className="card" style={{ padding: 20, marginBottom: 16 }}>
        <h3 style={{ margin: "0 0 4px", fontSize: 15 }}>Track a competitor</h3>
        <div className="muted" style={{ fontSize: 12.5, marginBottom: 14 }}>See how you stack up on followers, engagement, and posting cadence — plus an industry average.</div>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <input className="input" placeholder="Competitor name or @handle" value={name} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") add(); }} style={{ flex: 1, minWidth: 220 }} />
          <button className="btn btn-primary" disabled={busy} onClick={add}><Icon.Plus width="14" height="14" /> Track</button>
        </div>
      </div>

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div className="bench-row bench-head">
          <div>Account</div><div>Followers</div><div>Engagement</div><div>Posts / wk</div><div></div>
        </div>
        {rows.map((r) => (
          <div key={r.id} className={`bench-row ${r.you ? "you" : ""}`}>
            <div style={{ fontWeight: r.you ? 700 : 500 }}>{r.name}{r.you && <span className="pill ok" style={{ padding: "1px 6px", fontSize: 9.5, marginLeft: 6 }}>You</span>}</div>
            <div>{fmtNum(r.followers)}</div>
            <div>{r.engagementRate}%</div>
            <div>{r.postsPerWeek}</div>
            <div style={{ textAlign: "right" }}>{!r.you && <button className="btn btn-sm" onClick={() => hub.actions.deleteCompetitor(r.id)} style={{ color: "var(--danger)", padding: "2px 8px" }}>Remove</button>}</div>
          </div>
        ))}
        {industry && (
          <div className="bench-row" style={{ background: "var(--bg-2)", fontStyle: "italic", color: "var(--text-2)" }}>
            <div>Industry average</div><div>{fmtNum(industry.followers)}</div><div>{industry.engagementRate}%</div><div>—</div><div></div>
          </div>
        )}
      </div>
      {!competitors.length && <div className="muted" style={{ fontSize: 12.5, marginTop: 12, textAlign: "center" }}>Add a competitor above to see the comparison and industry average.</div>}
      <div className="muted" style={{ fontSize: 11.5, marginTop: 14, textAlign: "center" }}>Competitor metrics are sample estimates until platform benchmarking APIs are connected.</div>
    </div>
  );
}

window.BenchmarkingPage = BenchmarkingPage;
