/* ============================================================
   BrotherVader — UI enhancements (10 new responsive elements):
   1) StatStrip      — animated headline-number ticker band
   2) TotalMeter     — estimated powerlifting total + bar to 1000 lb
   3) ProgressRing   — circular goal completion ring
   4) Badges         — achievement chips earned from the data
   5) KpiCards       — key metric cards (bodyweight, change, sessions…)
   6) WeeklyVolume   — mini weekly-volume bar chart from the log
   7) NextMilestone  — next deadlift milestone progress
   8) CreedMarquee   — scrolling creed band
   9) BackToTop      — floating scroll-to-top button
   10) PlateDivider  — decorative barbell-plate section divider
   All read live data and are fully responsive.
   ============================================================ */

function prBy(list, key) {
  if (!list) return null;
  return list.find((p) => p.id === key) ||
    list.find((p) => (p.lift || "").toLowerCase().includes(key));
}
function estTotal(prsMain) {
  const sq = prBy(prsMain, "squat"); const bn = prBy(prsMain, "bench"); const dl = prBy(prsMain, "dl-conv") || prBy(prsMain, "deadlift");
  return (sq?.value || 0) + (bn?.value || 0) + (dl?.value || 0);
}

/* ---------- 1) StatStrip ---------- */
function StatStrip({ prsMain, log, transformation }) {
  const total = estTotal(prsMain);
  const before = transformation?.before, after = transformation?.after;
  const lost = before && after ? Math.abs((before.bodyweightKg || 0) - (after.bodyweightKg || 0)) : 0;
  const unit = after?.bwUnit || "lbs";
  const gym = Object.values(log || {}).filter((e) => e.status === "gym").length;
  const vol = Object.values(log || {}).reduce((a, e) => a + (e.totalVolume || 0), 0);
  const items = [
    { n: total, s: " lb", l: "Est. total" },
    { n: lost, s: " " + unit, l: "Weight lost" },
    { n: gym, s: "", l: "Gym days" },
    { n: Math.round(vol / 1000), s: "k kg", l: "Volume moved" },
    { n: prBy(prsMain, "dl-conv")?.value || 0, s: " lb", l: "Deadlift PR" },
  ];
  return (
    <Reveal className="statstrip">
      <div className="container statstrip-inner">
        {items.map((it, i) => (
          <div className="statstrip-cell" key={i}>
            <div className="statstrip-num display tnum"><CountUp value={it.n} />{it.s}</div>
            <div className="statstrip-lbl eyebrow">{it.l}</div>
          </div>
        ))}
      </div>
    </Reveal>
  );
}

/* ---------- 3) ProgressRing ---------- */
function ProgressRing({ pct, size = 132, stroke = 10, children }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const p = Math.max(0, Math.min(1, pct));
  return (
    <div className="ring" style={{ width: size, height: size }}>
      <svg width={size} height={size}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--line-strong)" strokeWidth={stroke} />
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--ox-bright)" strokeWidth={stroke}
          strokeDasharray={c} strokeDashoffset={c * (1 - p)} strokeLinecap="round"
          transform={`rotate(-90 ${size / 2} ${size / 2})`} style={{ transition: "stroke-dashoffset 1.1s cubic-bezier(.16,1,.3,1)" }} />
      </svg>
      <div className="ring-center">{children}</div>
    </div>
  );
}

/* ---------- 2,4,5,6,7,8) Insights section ---------- */
function Insights({ prsMain, log, transformation }) {
  const [seen, setSeen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((es) => es.forEach((e) => e.isIntersecting && setSeen(true)), { threshold: 0.2 });
    io.observe(el); return () => io.disconnect();
  }, []);

  const total = estTotal(prsMain);
  const goal = 1000;
  const pct = total / goal;
  const dl = prBy(prsMain, "dl-conv") || prBy(prsMain, "deadlift");
  const after = transformation?.after, before = transformation?.before;
  const unit = after?.bwUnit || "lbs";
  const lost = before && after ? Math.abs((before.bodyweightKg || 0) - (after.bodyweightKg || 0)) : 0;
  const gym = Object.values(log || {}).filter((e) => e.status === "gym").length;
  const vol = Object.values(log || {}).reduce((a, e) => a + (e.totalVolume || 0), 0);

  // Badges earned from real data
  const badges = [];
  if (total >= 1000) badges.push(["1000 lb Club", "Four-figure total"]);
  if ((dl?.value || 0) >= 405) badges.push([`${dl.value} lb Pull`, "Four-plate deadlift"]);
  if (lost >= 25) badges.push([`−${lost} ${unit}`, "Body recomposed"]);
  if (gym >= 50) badges.push([`${gym} Sessions`, "Consistency"]);
  if ((prBy(prsMain, "bench")?.value || 0) >= 225) badges.push(["2-Plate Bench", "225 lb+"]);

  // Next deadlift milestone (next multiple of 45 above current)
  const cur = dl?.value || 0;
  const next = Math.ceil((cur + 1) / 45) * 45;
  const prevMile = next - 45;
  const milePct = (cur - prevMile) / (next - prevMile);

  // Weekly volume (last 8 weeks)
  const weeks = {};
  Object.entries(log || {}).forEach(([k, e]) => {
    if (e.status !== "gym") return;
    const [y, m, d] = k.split("-").map(Number);
    const dt = new Date(y, m - 1, d);
    const off = (dt.getDay() + 6) % 7; dt.setDate(dt.getDate() - off); // Monday
    const wk = `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, "0")}-${String(dt.getDate()).padStart(2, "0")}`;
    weeks[wk] = (weeks[wk] || 0) + (e.totalVolume || 0);
  });
  const weekArr = Object.entries(weeks).sort((a, b) => a[0].localeCompare(b[0])).slice(-8);
  const maxW = Math.max(1, ...weekArr.map((w) => w[1]));

  const kpis = [
    { n: after?.bodyweightKg || 0, s: " " + unit, l: "Bodyweight now" },
    { n: lost, s: " " + unit, l: "Total lost", neg: true },
    { n: gym, s: "", l: "Gym sessions" },
    { n: Math.round(vol / 1000), s: "k kg", l: "Lifetime volume" },
  ];

  return (
    <section id="insights" className="section" ref={ref}>
      <div className="container">
        <Reveal className="section-head">
          <div>
            <div className="section-index">03B — THE TALLY</div>
            <h2 className="section-title">Strength<br/>Dashboard</h2>
          </div>
          <p className="muted" style={{ maxWidth: 320, margin: 0 }}>The numbers behind the numbers — your total, your milestones, your weekly grind, all computed live.</p>
        </Reveal>

        <div className="insights-grid">
          {/* Total meter + ring */}
          <Reveal className="card ins-total">
            <div className="ins-total-head">
              <span className="eyebrow">Estimated total · S/B/D</span>
              <span className="ins-total-num display tnum"><CountUp value={total} /> <span className="ins-unit">lb</span></span>
            </div>
            <div className="ins-meter"><span className="ins-meter-fill" style={{ width: (seen ? Math.min(100, pct * 100) : 0) + "%" }} /></div>
            <div className="ins-meter-scale tnum"><span>0</span><span>500</span><span className="ins-goal">1000 lb goal</span></div>
            <div className="ins-ring-wrap">
              <ProgressRing pct={seen ? pct : 0}>
                <div className="ring-pct display tnum">{Math.round(pct * 100)}%</div>
                <div className="ring-sub eyebrow">to 1000</div>
              </ProgressRing>
              <p className="muted ins-ring-note">{total >= goal ? "Milestone cleared — now chase the next plate." : `${goal - total} lb to the four-figure club.`}</p>
            </div>
          </Reveal>

          {/* KPI cards */}
          <div className="ins-kpis">
            {kpis.map((k, i) => (
              <Reveal key={i} className="card ins-kpi" delay={i * 60}>
                <div className="ins-kpi-num display tnum">{k.neg && k.n ? "−" : ""}<CountUp value={k.n} />{k.s}</div>
                <div className="ins-kpi-lbl eyebrow">{k.l}</div>
              </Reveal>
            ))}
          </div>

          {/* Next milestone */}
          <Reveal className="card ins-mile">
            <div className="eyebrow">Next deadlift milestone</div>
            <div className="ins-mile-row">
              <span className="ins-mile-cur display tnum">{cur}</span>
              <span className="ins-mile-arrow"><Icons.Arrow size={18} /></span>
              <span className="ins-mile-next display tnum">{next}<span className="ins-unit"> lb</span></span>
            </div>
            <div className="ins-meter sm"><span className="ins-meter-fill" style={{ width: (seen ? Math.min(100, milePct * 100) : 0) + "%" }} /></div>
            <p className="muted" style={{ margin: "8px 0 0", fontSize: 13 }}>{next - cur} lb to go — that's {(((next - cur) / 2.205) || 0).toFixed(1)} kg on the bar.</p>
          </Reveal>

          {/* Weekly volume bars */}
          <Reveal className="card ins-weekly">
            <div className="eyebrow" style={{ marginBottom: 14 }}>Weekly volume · last {weekArr.length} weeks</div>
            <div className="ins-bars">
              {weekArr.map(([wk, v], i) => (
                <div className="ins-bar-col" key={wk} title={`${v.toLocaleString()} kg`}>
                  <div className="ins-bar" style={{ height: (seen ? Math.max(4, (v / maxW) * 100) : 0) + "%" }} />
                  <span className="ins-bar-lbl tnum">{wk.slice(5).replace("-", "/")}</span>
                </div>
              ))}
              {weekArr.length === 0 && <p className="muted">No volume logged yet.</p>}
            </div>
          </Reveal>
        </div>

        {/* Badges */}
        {badges.length > 0 && (
          <Reveal className="ins-badges">
            {badges.map((b, i) => (
              <div className="ins-badge" key={i}>
                <span className="ins-badge-ico"><Icons.Flame size={16} /></span>
                <span className="ins-badge-main head">{b[0]}</span>
                <span className="ins-badge-sub dim">{b[1]}</span>
              </div>
            ))}
          </Reveal>
        )}
      </div>
    </section>
  );
}

/* ---------- 8) CreedMarquee ---------- */
function CreedMarquee() {
  const words = ["BUILT NOT BORN", "NO OFF-SEASON", "THE BAR DOESN'T NEGOTIATE", "EAT · LIFT · REPEAT", "STRENGTH IS HONEST", "CHASE THE PLATE"];
  const row = [...words, ...words];
  return (
    <div className="creed-marquee" aria-hidden="true">
      <div className="creed-track">
        {row.map((w, i) => <span key={i} className="creed-word display">{w}<span className="creed-dot">●</span></span>)}
      </div>
    </div>
  );
}

/* ---------- 9) BackToTop ---------- */
function BackToTop() {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const f = () => setShow(window.scrollY > 700);
    window.addEventListener("scroll", f, { passive: true }); f();
    return () => window.removeEventListener("scroll", f);
  }, []);
  return (
    <button className={"backtotop" + (show ? " on" : "")} onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })} aria-label="Back to top">
      <Icons.Download size={18} style={{ transform: "rotate(180deg)" }} />
    </button>
  );
}

/* ---------- 10) PlateDivider ---------- */
function PlateDivider() {
  return (
    <div className="plate-divider" aria-hidden="true">
      <span className="plate-line" />
      <span className="plate-ico"><i /><i /><i /></span>
      <span className="plate-line" />
    </div>
  );
}

Object.assign(window, { StatStrip, Insights, CreedMarquee, BackToTop, PlateDivider, ProgressRing });
