// Primate App Kit — Billing page (brand decoration panel + billing content)
const { useState: useStateBL } = React;

// orbiting bananas — each parameterized by ring radius r + base angle a0 (deg) so it
// stays ON its ring while subtly sliding toward the cursor. Central = bright hub.
const BL_BANANAS = [
  { central: true, size: 116 },
  { r: 260, a0: -142, size: 58, ang: 35 },
  { r: 180, a0: -45, size: 54, ang: 160 },
  { r: 260, a0: 125, size: 64, ang: 250 },
  { r: 180, a0: 33, size: 62, ang: 90 },
];

const BL_RINGS = [100, 180, 260, 340];

const BL_STARS = [
  { left: "30%", top: "23%", size: 2, gold: false, dur: 4.4 },
  { left: "58%", top: "18%", size: 2.5, gold: true, dur: 0 },
  { left: "44%", top: "29%", size: 1.5, gold: false, dur: 5.2 },
  { left: "70%", top: "33%", size: 2, gold: false, dur: 0 },
  { left: "20%", top: "52%", size: 2, gold: true, dur: 3.8 },
  { left: "80%", top: "58%", size: 1.5, gold: false, dur: 4.9 },
  { left: "33%", top: "68%", size: 2, gold: false, dur: 0 },
  { left: "62%", top: "73%", size: 2.5, gold: true, dur: 4.1 },
  { left: "47%", top: "84%", size: 1.5, gold: false, dur: 5.5 },
  { left: "16%", top: "63%", size: 2, gold: false, dur: 0 },
];

function BananaOrbit({ size, central, idx, ang = 0, r, a0, pointer }) {
  const glow = central ? 0.32 : 0.22;
  const ringD = Math.round(size * 1.7);
  let left = "50%", top = "54%";
  let baseDx = 0, baseDy = 0, slideX = 0, slideY = 0;
  if (!central) {
    const a0r = (a0 * Math.PI) / 180;
    baseDx = r * Math.cos(a0r);
    baseDy = r * Math.sin(a0r);
    let off = 0;
    if (pointer && pointer.active) {
      let d = pointer.angle - a0r;
      d = Math.atan2(Math.sin(d), Math.cos(d));   // shortest signed angle
      const max = 0.06;                            // ~3.5° of very subtle drift along the ring
      off = Math.max(-max, Math.min(max, d));
    }
    const a = a0r + off;
    slideX = r * Math.cos(a) - baseDx;
    slideY = r * Math.sin(a) - baseDy;
    left = `calc(50% + ${baseDx.toFixed(1)}px)`;
    top = `calc(54% + ${baseDy.toFixed(1)}px)`;
  }
  // magnet: nudge slightly off-axis toward the cursor (capped)
  let magX = 0, magY = 0;
  if (pointer && pointer.active) {
    const toCx = pointer.cx - baseDx, toCy = pointer.cy - baseDy;
    const dist = Math.hypot(toCx, toCy) || 1;
    const mag = Math.min(6, dist * 0.02);
    magX = (toCx / dist) * mag;
    magY = (toCy / dist) * mag;
  }
  const transform = `translate(-50%,-50%) translate(${(slideX + magX).toFixed(1)}px, ${(slideY + magY).toFixed(1)}px)`;
  return (
    <div style={{ position: "absolute", left, top, transform, transition: "transform 2.2s cubic-bezier(.16,.84,.30,1)", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div style={{ position: "absolute", width: size * 2.1, height: size * 2.1, borderRadius: "50%", background: `radial-gradient(circle, rgba(235,187,54,${glow}) 0%, rgba(235,187,54,0.06) 45%, transparent 70%)` }} />
      {!central && (
        <svg width={ringD} height={ringD} viewBox={`0 0 ${ringD} ${ringD}`} style={{ position: "absolute" }}>
          <defs>
            <linearGradient id={`bring-${idx}`} x1="0" y1="0" x2={ringD} y2={ringD} gradientUnits="userSpaceOnUse" gradientTransform={`rotate(${ang} ${ringD / 2} ${ringD / 2})`}>
              <stop offset="0%" stopColor="#FEED45" />
              <stop offset="36%" stopColor="#2A2A2A" />
            </linearGradient>
          </defs>
          <circle cx={ringD / 2} cy={ringD / 2} r={ringD / 2 - 1} fill="none" stroke={`url(#bring-${idx})`} strokeWidth="1" opacity="0.75" />
        </svg>
      )}
      <img src="assets/banana-glow.svg" width={size} alt="" style={{ position: "relative", display: "block", filter: `drop-shadow(0 0 ${central ? 16 : 9}px rgba(235,187,54,0.45))` }} />
    </div>
  );
}

function BillingDecor({ pointer }) {
  return (
    <div style={{ position: "absolute", inset: 0, overflow: "hidden", pointerEvents: "none" }}>
      {/* orbit rings — dotted, each with a gold/dark gradient at a randomized angle */}
      <svg width={844} height={844} viewBox="0 0 844 844" style={{ position: "absolute", left: "50%", top: "54%", transform: "translate(-50%,-50%)", overflow: "visible" }}>
        <defs>
          {[28, 142, 255, 86].map((ang, i) => (
            <linearGradient key={i} id={`ring-grad-${i}`} x1="0" y1="0" x2="844" y2="0" gradientUnits="userSpaceOnUse" gradientTransform={`rotate(${ang} 422 422)`}>
              <stop offset="0%" stopColor="#322F26" />
              <stop offset="25%" stopColor="#AA9C79" />
              <stop offset="58%" stopColor="#202020" />
              <stop offset="100%" stopColor="#4A402B" />
            </linearGradient>
          ))}
        </defs>
        {BL_RINGS.map((r, i) => (
          <circle key={i} cx="422" cy="422" r={r} fill="none" stroke={`url(#ring-grad-${i})`} strokeWidth="1.5" strokeDasharray="1.5 6" opacity={(0.75 - i * 0.07).toFixed(2)} />
        ))}
      </svg>
      {/* stars */}
      {BL_STARS.map((s, i) => (
        <span key={`s${i}`} style={{
          position: "absolute", left: s.left, top: s.top, width: s.size, height: s.size, borderRadius: "50%",
          background: s.gold ? "#EBBB36" : "#FFFFFF", boxShadow: `0 0 ${s.size * 2}px ${s.size * 0.6}px ${s.gold ? "rgba(235,187,54,0.5)" : "rgba(255,255,255,0.45)"}`,
          opacity: s.dur ? undefined : 0.5,
          animation: s.dur ? `starTwinkle ${s.dur}s ease-in-out ${(-i * 0.6).toFixed(1)}s infinite` : undefined,
        }} />
      ))}
      {/* bananas */}
      {BL_BANANAS.map((b, i) => <BananaOrbit key={`b${i}`} idx={i} pointer={pointer} {...b} />)}
    </div>
  );
}

/* ============================ right panel ============================ */
function SectionLabel({ children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      <span style={{ font: "14px/20px var(--font-sans)", letterSpacing: "-0.3px", color: "#D4D4D8" }}>{children}</span>
      <div style={{ height: 1, background: "var(--border)" }} />
    </div>
  );
}

function BillingButton() {
  const [h, setH] = useStateBL(false);
  return (
    <button onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ alignSelf: "flex-start", display: "inline-flex", alignItems: "center", gap: 8, height: 36, padding: "0 16px", borderRadius: 8, border: "none", background: h ? "var(--gold-bright)" : "var(--gold)", color: "var(--on-gold)", font: "400 14px var(--font-mono)", cursor: "pointer", transition: "background .14s ease", whiteSpace: "nowrap" }}>
      Billing Settings <Icon name="external-link" size={16} color="var(--on-gold)" />
    </button>
  );
}

const BL_ROWS = [
  { date: "May 1, 2026", cost: "$20", plan: "Pro" },
  { date: "April 1, 2026", cost: "$20", plan: "Pro" },
  { date: "March 1, 2026", cost: "$20", plan: "Pro" },
];
const BL_COLS = "minmax(150px,1.3fr) 0.85fr 0.95fr";

function BillingRow({ row }) {
  const [h, setH] = useStateBL(false);
  return (
    <div onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)} style={{ display: "grid", gridTemplateColumns: BL_COLS, alignItems: "center", padding: "0 24px", height: 45, borderTop: "1px solid var(--border)", cursor: "pointer", background: h ? "rgba(255,255,255,0.035)" : "transparent", transition: "background .1s ease" }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 6, minWidth: 0 }}>
        <span style={{ font: "var(--t-body-sm)", color: "var(--fg)", whiteSpace: "nowrap", textDecoration: h ? "underline" : "none", textUnderlineOffset: 3 }}>{row.date}</span>
        {h && <Icon name="arrow-up-right" size={13} color="var(--fg-muted)" />}
      </span>
      <span style={{ font: "var(--t-body-sm)", color: "var(--fg-secondary)" }}>{row.cost}</span>
      <span style={{ font: "var(--t-body-sm)", color: "var(--fg-secondary)" }}>{row.plan}</span>
    </div>
  );
}

function PageBtn({ icon, disabled }) {
  const [h, setH] = useStateBL(false);
  return (
    <button disabled={disabled} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ width: 32, height: 32, display: "flex", alignItems: "center", justifyContent: "center", borderRadius: 8, border: "1px solid var(--border-subtle)", background: h && !disabled ? "var(--bg-elevated-2)" : "var(--bg-elevated)", color: disabled ? "var(--fg-faint)" : "var(--fg-secondary)", cursor: disabled ? "default" : "pointer", opacity: disabled ? 0.5 : 1, transition: "background .14s ease" }}>
      <Icon name={icon} size={16} />
    </button>
  );
}

function BillingTable() {
  return (
    <div style={{ borderRadius: 8, border: "1px solid var(--border)", background: "var(--bg-card)", overflow: "hidden" }}>
      {/* header */}
      <div style={{ display: "grid", gridTemplateColumns: BL_COLS, alignItems: "center", padding: "0 24px", height: 48, background: "var(--bg-elevated)", borderBottom: "1px solid var(--border)", font: "var(--t-label)", color: "var(--fg-secondary)" }}>
        <span>Date</span><span>Cost</span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>Plan <Icon name="chevrons-up-down" size={13} color="var(--fg-faint)" /></span>
      </div>
      {BL_ROWS.map((r, i) => <BillingRow key={i} row={r} />)}
      {/* pagination */}
      <PaginationFooter />
    </div>
  );
}

function Billing() {
  const [pointer, setPointer] = useStateBL({ active: false, angle: 0 });
  const panelRef = React.useRef(null);
  const vp = useViewport();
  const compact = vp !== "desktop";
  const mobile = vp === "mobile";
  const tablet = vp === "tablet";
  React.useEffect(() => {
    function onMove(e) {
      const el = panelRef.current;
      if (!el) return;
      const rc = el.getBoundingClientRect();
      const hx = rc.left + rc.width * 0.5;
      const hy = rc.top + rc.height * 0.54;
      setPointer({ active: true, angle: Math.atan2(e.clientY - hy, e.clientX - hx), cx: e.clientX - hx, cy: e.clientY - hy });
    }
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);
  return (
    <div style={{ width: "100%", height: "100%", display: "flex", borderRadius: 8, border: "1px solid var(--border)", overflow: "hidden", background: "var(--bg-card)" }}>
      {/* left — brand / decoration (desktop only) */}
      {!compact && (
        <div ref={panelRef} style={{ position: "relative", flex: "0 1 clamp(220px, 38%, 511px)", minWidth: 0, overflow: "hidden", background: "linear-gradient(180deg, rgba(0,0,0,0.2) 0%, rgba(102,102,102,0.2) 100%), var(--bg-card)" }}>
          <BillingDecor pointer={pointer} />
          <style>{`@keyframes primateBob { 0%,100% { transform: translateX(-50%) translateY(0); } 50% { transform: translateX(-50%) translateY(-7px); } }`}</style>
          <img src="assets/hanging-primate.webp" alt="" style={{ position: "absolute", top: 0, left: "50%", transform: "translateX(-50%)", width: "70%", display: "block", pointerEvents: "none", zIndex: 2, animation: "primateBob 9s ease-in-out infinite", transformOrigin: "top center" }} />
        </div>
      )}

      {/* right — billing content */}
      <div style={{ flex: 1, minWidth: 0, background: "var(--bg)", borderLeft: compact ? "none" : "1px solid var(--border)", padding: mobile ? "20px" : tablet ? "24px 28px" : "56px clamp(32px, 5vw, 64px)", display: "flex", flexDirection: "column", gap: 32, overflowY: "auto" }}>
        <h1 style={{ font: `600 ${mobile ? 24 : 30}px/36px var(--font-sans)`, letterSpacing: "0.4px", color: "var(--fg)", margin: 0 }}>Billing</h1>

        {/* current plan */}
        <div style={{ display: "flex", flexDirection: "column", gap: 18, maxWidth: 785 }}>
          <SectionLabel>CURRENT PLAN</SectionLabel>
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <div style={{ display: "flex", flexDirection: "column" }}>
                <span style={{ font: "700 20px/28px var(--font-sans)", letterSpacing: "-0.45px", color: "var(--fg)" }}>Pro Plan</span>
                <span style={{ font: "18px/28px var(--font-sans)", letterSpacing: "-0.44px", color: "var(--fg)" }}>$20.00 per month</span>
              </div>
              <span style={{ font: "14px/20px var(--font-sans)", letterSpacing: "-0.15px", color: "var(--fg)" }}>Your plan renews on June 1, 2026</span>
            </div>
            <BillingButton />
          </div>
        </div>

        {/* billing history */}
        <div style={{ display: "flex", flexDirection: "column", gap: 18, maxWidth: 785, marginTop: 24 }}>
          <SectionLabel>BILLING HISTORY</SectionLabel>
          <BillingTable />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Billing });
