/* Slow Weekend — Insights.
   The founder-facing read-back of the instrumentation: discovery, consumption,
   return behavior, intent. Reads SWA.aggregate() (local event log). On-brand,
   deliberately calm. No public link; reach it directly via ?insights=1. */

const SWI_INK = "#2F2F2F";
const SWI_SAGE = "#7E9078";
const SWI_DEEP = "#5d6b58";
const SWI_CAT = { Recharge: "#7E9078", Explore: "#A6884F", Connect: "#8576A0" };

function swiPct(n, d) { return d ? Math.round((n / d) * 100) : 0; }

function SWStatTile({ label, value, sub, accent }) {
  return (
    <div style={{ background: "#FFFFFF", borderRadius: 16, padding: "20px 22px", border: "1px solid rgba(47,47,47,0.06)", boxShadow: "0 14px 36px -30px rgba(47,47,47,0.5)" }}>
      <div style={{ fontSize: 12, letterSpacing: "0.1em", textTransform: "uppercase", color: "rgba(47,47,47,0.45)", fontWeight: 600 }}>{label}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 7, marginTop: 10 }}>
        <span style={{ font: "600 32px 'Source Serif 4', serif", color: accent || SWI_INK, letterSpacing: "-0.01em" }}>{value}</span>
        {sub && <span style={{ fontSize: 13, color: "rgba(47,47,47,0.5)" }}>{sub}</span>}
      </div>
    </div>
  );
}

function SWBarList({ rows, total, accentFor, empty }) {
  const max = rows.reduce((m, r) => Math.max(m, r.n), 0) || 1;
  if (!rows.length) return <p style={{ fontSize: 14, color: "rgba(47,47,47,0.45)", margin: "6px 2px" }}>{empty || "No data yet."}</p>;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
      {rows.map((r) => {
        const accent = accentFor ? accentFor(r.key) : SWI_SAGE;
        return (
          <div key={r.key}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 5 }}>
              <span style={{ fontSize: 14.5, color: SWI_INK }}>{r.key}</span>
              <span style={{ fontSize: 13, color: "rgba(47,47,47,0.5)" }}>
                {r.n}{total ? <span style={{ color: "rgba(47,47,47,0.35)" }}> · {swiPct(r.n, total)}%</span> : null}
              </span>
            </div>
            <div style={{ height: 8, borderRadius: 999, background: "rgba(47,47,47,0.06)", overflow: "hidden" }}>
              <div style={{ width: `${Math.max(4, (r.n / max) * 100)}%`, height: "100%", borderRadius: 999, background: accent, transition: "width .6s cubic-bezier(.3,.7,.3,1)" }} />
            </div>
          </div>
        );
      })}
    </div>
  );
}

function SWPanel({ title, note, children, span }) {
  return (
    <section style={{ background: "rgba(255,255,255,0.55)", borderRadius: 20, padding: "26px 28px", border: "1px solid rgba(47,47,47,0.06)", gridColumn: span ? "1 / -1" : "auto" }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 12, marginBottom: 18, flexWrap: "wrap" }}>
        <h3 style={{ font: "500 19px 'Source Serif 4', serif", color: SWI_INK, margin: 0 }}>{title}</h3>
        {note && <span style={{ fontSize: 12.5, color: "rgba(47,47,47,0.45)" }}>{note}</span>}
      </div>
      {children}
    </section>
  );
}

function InsightsView({ onBack }) {
  const [, force] = React.useState(0);
  const localAgg = React.useMemo(() => SWA.aggregate(), []);
  // Pooled read-back: fetch the cross-user event stream from PostHog (via the
  // /api/insights serverless function) and run the SAME reducer over it. Falls
  // back silently to the local view when the read-back isn't configured.
  const [pooled, setPooled] = React.useState(null); // { agg, count } | null
  const [source, setSource] = React.useState("local");
  React.useEffect(() => {
    let alive = true;
    fetch("/api/insights").then((r) => (r.ok ? r.json() : null)).then((j) => {
      if (!alive || !j || !j.configured || !Array.isArray(j.events) || !j.events.length) return;
      setPooled({ agg: SWA.aggregateEvents(j.events, { firstSeen: j.firstSeen }), count: j.events.length });
      setSource("pooled");
    }).catch(() => {});
    return () => { alive = false; };
  }, []);

  const usingPooled = source === "pooled" && !!pooled;
  const agg = usingPooled ? pooled.agg : localAgg;
  const t = agg.totals;
  const seeded = !usingPooled && SWA.isSeeded();
  const partnerName = (k) => { const r = (window.SLOW_WEEKEND_DATA.partners || {})[k]; return r ? r.name : k; };
  // Real-data state: a fresh beta has only this browser's own session events.
  const isThin = !usingPooled && !seeded && t.opens === 0 && t.saves === 0 && t.sessions <= 1;

  return (
    <div className="sw-fade" style={{ maxWidth: 1080, margin: "0 auto", padding: "26px clamp(20px,5vw,52px) 110px" }}>
      <button onClick={onBack} style={{ border: "none", background: "none", cursor: "pointer", font: "inherit", fontSize: 14.5, color: "rgba(47,47,47,0.6)", display: "inline-flex", alignItems: "center", gap: 8, padding: "6px 0", marginBottom: 18 }}>
        ← Back to this week
      </button>

      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 18, flexWrap: "wrap", marginBottom: 10 }}>
        <div>
          <div style={{ fontSize: 12.5, letterSpacing: "0.16em", textTransform: "uppercase", color: SWI_DEEP, fontWeight: 600, marginBottom: 10 }}>Beta instrumentation</div>
          <h1 style={{ font: "500 clamp(30px,4.4vw,40px)/1.1 'Source Serif 4', serif", letterSpacing: "-0.02em", color: SWI_INK, margin: 0 }}>What the market is voting</h1>
          <p style={{ margin: "12px 0 0", fontSize: 16, lineHeight: 1.55, color: "rgba(47,47,47,0.6)", maxWidth: 620 }}>
            Behavioral signal, not opinions. Discovery, consumption, return, and intent, the four things worth obsessing over while the beta is live.
          </p>
        </div>
        {pooled && (
          <div style={{ display: "inline-flex", alignItems: "center", gap: 0, background: "rgba(47,47,47,0.05)", borderRadius: 999, padding: 3 }}>
            {[["pooled", "All beta users", pooled.count + " events"], ["local", "This browser", null]].map(([key, label, sub]) => {
              const on = source === key;
              return (
                <button key={key} onClick={() => setSource(key)} title={sub || ""} style={{
                  border: "none", cursor: "pointer", font: "inherit", borderRadius: 999, padding: "7px 15px",
                  background: on ? "#FFFFFF" : "transparent", color: on ? SWI_INK : "rgba(47,47,47,0.5)",
                  fontWeight: on ? 600 : 400, fontSize: 13, boxShadow: on ? "0 6px 16px -12px rgba(47,47,47,0.5)" : "none", transition: "all .25s ease",
                }}>{label}</button>
              );
            })}
          </div>
        )}
      </div>

      {seeded && (
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14, flexWrap: "wrap", background: "rgba(166,136,79,0.1)", border: "1px solid rgba(166,136,79,0.28)", borderRadius: 14, padding: "13px 18px", margin: "22px 0 26px" }}>
          <span style={{ fontSize: 13.5, color: "#7a6230", lineHeight: 1.5 }}>
            <strong>Showing sample data</strong> (loaded via <code style={{ background: "rgba(122,98,48,0.12)", padding: "1px 6px", borderRadius: 5, fontSize: 12.5 }}>?demo</code>). Clear it to read only real visits.
          </span>
          <button onClick={() => { SWA.reset(); force((n) => n + 1); }} style={{ border: "1px solid rgba(122,98,48,0.4)", background: "transparent", cursor: "pointer", font: "inherit", fontSize: 13, fontWeight: 600, color: "#7a6230", borderRadius: 999, padding: "7px 16px", whiteSpace: "nowrap" }}>
            Clear sample data
          </button>
        </div>
      )}

      {isThin && (
        <div style={{ background: "rgba(126,144,120,0.09)", border: "1px solid rgba(126,144,120,0.22)", borderRadius: 14, padding: "15px 20px", margin: "22px 0 26px" }}>
          <span style={{ fontSize: 13.5, color: "#4f5c4a", lineHeight: 1.55 }}>
            <strong>Live and collecting.</strong> This is real behavioral data from actual visits, it’s quiet because the beta is young. Open a few picks to see the funnel fill in, or load <code style={{ background: "rgba(126,144,120,0.16)", padding: "1px 6px", borderRadius: 5, fontSize: 12.5 }}>?demo</code> to preview a populated dashboard.
          </span>
        </div>
      )}

      {/* top stats */}
      <div style={{ display: "grid", gap: 14, gridTemplateColumns: "repeat(auto-fit, minmax(155px, 1fr))", margin: seeded ? "0 0 16px" : "26px 0 16px" }}>
        <SWStatTile label="Save rate" value={`${t.saveRatePct}%`} sub="of opens" accent={SWI_SAGE} />
        <SWStatTile label="Actually went" value={t.visited} sub={`"we went"`} accent="#C2A878" />
        <SWStatTile label="Returning" value={`${swiPct(t.returningSessions, t.sessions)}%`} sub="of sessions" accent={SWI_DEEP} />
        <SWStatTile label="Avg gap" value={t.avgDaysBetween == null ? "—" : t.avgDaysBetween} sub="days back" />
      </div>

      <div style={{ display: "grid", gap: 16, gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))" }}>
        <SWPanel title="Direct feedback" note="what they told us, the kill/keep signal" span>
          <div style={{ display: "grid", gap: 18, gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))" }}>
            <div>
              <div style={{ display: "flex", gap: 18, marginBottom: 14 }}>
                <span style={{ fontSize: 14.5, color: SWI_INK }}>👍 <strong style={{ font: "600 18px 'Source Serif 4', serif" }}>{t.likes}</strong></span>
                <span style={{ fontSize: 14.5, color: SWI_INK }}>👎 <strong style={{ font: "600 18px 'Source Serif 4', serif" }}>{t.flags}</strong></span>
              </div>
              <div style={{ fontSize: 12.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "rgba(47,47,47,0.45)", fontWeight: 600, margin: "0 0 8px" }}>Most flagged (cut candidates)</div>
              <SWBarList rows={agg.flagged.slice(0, 5)} accentFor={() => "#9A6238"} empty="No flags yet." />
            </div>
            <div>
              <div style={{ fontSize: 12.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "rgba(47,47,47,0.45)", fontWeight: 600, margin: "0 0 8px" }}>Most liked (feature candidates)</div>
              <SWBarList rows={agg.liked.slice(0, 5)} accentFor={() => SWI_SAGE} empty="No likes yet." />
              {agg.reasons.length > 0 && (
                <div style={{ marginTop: 16 }}>
                  <div style={{ fontSize: 12.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "rgba(47,47,47,0.45)", fontWeight: 600, margin: "0 0 8px" }}>Why-not notes</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                    {agg.reasons.slice(-4).reverse().map((r, i) => (
                      <div key={i} style={{ fontSize: 13, color: "rgba(47,47,47,0.7)", lineHeight: 1.45 }}>“{r.reason}” <span style={{ color: "rgba(47,47,47,0.4)" }}>· {r.title}</span></div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
          <p style={{ fontSize: 12.5, color: "rgba(47,47,47,0.5)", lineHeight: 1.55, margin: "16px 2px 0" }}>
            Votes inform our editorial calls, they never auto-rank the list.
          </p>
        </SWPanel>

        {agg.partners.length > 0 && (
          <SWPanel title="Partner referrals" note="the value you send partners" span>
            <p style={{ fontSize: 13.5, lineHeight: 1.55, color: "rgba(47,47,47,0.55)", margin: "0 0 16px", maxWidth: 640 }}>
              The shareable loop: how partner inventory performs, and the numbers you hand back to each operator. Site-wide save rate is <strong style={{ color: SWI_INK }}>{t.saveRatePct}%</strong>.
            </p>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {agg.partners.map((p) => (
                <div key={p.key} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap", padding: "14px 18px", background: "rgba(176,118,79,0.06)", border: "1px solid rgba(176,118,79,0.2)", borderRadius: 14 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
                    <span style={{ flexShrink: 0, width: 26, height: 26, borderRadius: "50%", background: "radial-gradient(circle at 35% 30%, #C58FA0, #B0764F)", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "#fff", fontSize: 12 }}>✦</span>
                    <span style={{ font: "500 16px 'Source Serif 4', serif", color: SWI_INK }}>{partnerName(p.key)}</span>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 22, flexWrap: "wrap" }}>
                    {[["Opens", p.opens], ["Saves", p.saves], ["Click-throughs", p.outbound], ["Save rate", p.saveRate + "%"]].map(([l, v]) => (
                      <div key={l} style={{ textAlign: "center" }}>
                        <div style={{ font: "600 18px 'Source Serif 4', serif", color: SWI_INK }}>{v}</div>
                        <div style={{ fontSize: 10.5, letterSpacing: "0.06em", textTransform: "uppercase", color: "rgba(47,47,47,0.45)" }}>{l}</div>
                      </div>
                    ))}
                    {p.vsAvg != null && (
                      <span style={{ fontSize: 12.5, fontWeight: 600, color: p.vsAvg >= 1 ? "#5d6b58" : "#9A6238", background: p.vsAvg >= 1 ? "rgba(126,144,120,0.16)" : "rgba(166,136,79,0.16)", borderRadius: 999, padding: "5px 12px", whiteSpace: "nowrap" }}>
                        {p.vsAvg}× site save rate
                      </span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </SWPanel>
        )}

        <SWPanel title="Explore the rest in PostHog" note="this page stays curated on purpose" span>
          <p style={{ fontSize: 13.5, lineHeight: 1.6, color: "rgba(47,47,47,0.6)", margin: 0, maxWidth: 680 }}>
            This page is deliberately just the product-defining numbers: the taste-trust proxy (save rate), the kill/keep feedback, and what partners earn. For funnels (visit → open → intent), retention, acquisition sources, paths, and any breakdown by category, child age, window, or energy, use PostHog directly. It does those better than anything we would hand-roll, and keeping them there is what lets this page stay calm.
          </p>
        </SWPanel>
      </div>

      <div style={{ marginTop: 22, padding: "18px 22px", background: "rgba(47,47,47,0.03)", borderRadius: 16, border: "1px solid rgba(47,47,47,0.06)" }}>
        <h4 style={{ font: "600 13px system-ui", letterSpacing: "0.08em", textTransform: "uppercase", color: "rgba(47,47,47,0.5)", margin: "0 0 8px" }}>Where this data comes from</h4>
        <p style={{ fontSize: 13.5, lineHeight: 1.6, color: "rgba(47,47,47,0.6)", margin: 0 }}>
          Events stream to PostHog through <code style={{ background: "rgba(47,47,47,0.06)", padding: "1px 6px", borderRadius: 5, fontSize: 12.5 }}>/api/events</code> (wired via the <code style={{ background: "rgba(47,47,47,0.06)", padding: "1px 6px", borderRadius: 5, fontSize: 12.5 }}>swa-endpoint</code> meta tag) once <code style={{ background: "rgba(47,47,47,0.06)", padding: "1px 6px", borderRadius: 5, fontSize: 12.5 }}>POSTHOG_KEY</code> is set. To read them back here, pooled across every beta user, set <code style={{ background: "rgba(47,47,47,0.06)", padding: "1px 6px", borderRadius: 5, fontSize: 12.5 }}>POSTHOG_PROJECT_ID</code> + <code style={{ background: "rgba(47,47,47,0.06)", padding: "1px 6px", borderRadius: 5, fontSize: 12.5 }}>POSTHOG_QUERY_KEY</code> (a read-scoped personal key) in the frontend Vercel project. The <strong>All beta users / This browser</strong> toggle above appears once pooled data loads; until then this page reads only <em>this</em> browser's events.
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { InsightsView });
