/* KitRate — signature data aesthetic for the kit document.
   Annual-report craft: hairline ledgers, oversized serif numerals,
   mono footnotes, market-position rails, and pricing receipts that
   show the math behind every rate (visible on the share link too). */

/* ---------- market position descriptors ---------- */
const REACH_DESC = {
  v_low: "bottom quartile", v_base: "mid-pack",
  v_high: "top ~25%", v_break: "top ~5%"
};
const ENG_DESC = {
  e_low: "bottom third", e_avg: "mid-pack",
  e_good: "top ~30%", e_top: "top ~10%"
};

function findTier(tiers, value, key) {
  for (const tr of tiers) { if (tr[key] == null || value < tr[key]) return tr; }
  return tiers[tiers.length - 1];
}

/* ---------- market rail: hairline scale, typical band, creator dot ---------- */
function MarketRail({ value, min, max, bandLo, bandHi, t, caption, sup, motion }) {
  const pct = (v) => Math.min(97, Math.max(2, ((v - min) / (max - min)) * 100));
  const [ref, seen] = useRevealOnce(!motion);
  const ease = "cubic-bezier(0.22, 0.61, 0.21, 1)";
  return (
    <div style={{ marginTop: 9 }} ref={ref}>
      <div style={{ position: "relative", height: 12 }}>
        {/* track */}
        <div style={{ position: "absolute", left: 0, right: 0, top: 5.5, height: 1, background: t.line }}></div>
        {/* typical market band */}
        <div style={{ position: "absolute", left: pct(bandLo) + "%", width: (seen ? pct(bandHi) - pct(bandLo) : 0) + "%", top: 3.5, height: 5, background: t.muted, opacity: 0.28, transition: motion ? "width 0.7s " + ease : "none" }}></div>
        {/* creator dot */}
        <div style={{ position: "absolute", left: (seen ? pct(value) : 2) + "%", top: 2.5, width: 7, height: 7, borderRadius: "50%", background: t.accent, transform: "translateX(-50%)", boxShadow: "0 0 0 2px " + t.bg, transition: motion ? "left 0.9s " + ease + " 0.15s" : "none" }}></div>
      </div>
      <div style={{ fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.08em", textTransform: "uppercase", color: t.muted, marginTop: 4, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
        {caption}{sup && <sup style={{ color: t.accent }}>{"\u00A0"}{sup}</sup>}
      </div>
    </div>
  );
}

/* ---------- big ledger numeral ---------- */
function LedgerStat({ value, label, t, compact, accent, motion }) {
  return (
    <div>
      <div style={{ fontFamily: t.serif, fontSize: compact ? 26 : 32, fontWeight: 500, letterSpacing: "-0.01em", lineHeight: 1, color: accent ? t.accent : t.ink, fontVariantNumeric: "tabular-nums" }}><KrNum motion={motion} value={value} /></div>
      <div style={{ fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.14em", textTransform: "uppercase", color: t.muted, marginTop: 6 }}>{label}</div>
    </div>
  );
}

/* ---------- footnotes block ---------- */
function Footnotes({ notes, t }) {
  return (
    <div style={{ borderTop: "1px solid " + t.line, marginTop: 22, paddingTop: 10 }}>
      {notes.map((n, i) => (
        <p key={i} style={{ fontFamily: "var(--mono)", fontSize: 9.5, lineHeight: 1.7, color: t.muted, margin: "2px 0", letterSpacing: "0.01em" }}>
          <sup style={{ color: t.accent }}>{i + 1}</sup> {n}
        </p>
      ))}
    </div>
  );
}

/* ============================================================
   AUDIENCE LEDGER — who's watching, as an annual-report spread
   ============================================================ */
const TENTH_WORDS = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"];

function AudienceLedger({ profile, t, compact, motion }) {
  const a = profile.audience || {};
  const g = a.genderSplit;
  const ages = a.ageRanges || [];
  const topAge = ages.length ? ages.reduce((b, r) => r.pct > b.pct ? r : b) : null;
  const maxAge = ages.length ? Math.max(...ages.map(r => r.pct)) : 1;
  const geos = a.topGeos || [];
  const cities = a.topCities || [];

  const monoHead = { fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase", color: t.muted };
  const Em = ({ children }) => <span style={{ color: t.accent }}>{children}</span>;
  const [ageRef, ageSeen] = useRevealOnce(!motion);
  const [gRef, gSeen] = useRevealOnce(!motion);
  const revealEase = "cubic-bezier(0.22, 0.61, 0.21, 1)";

  /* editorial lede composed strictly from the data */
  let lede = null;
  if (g) {
    const lead = g.male >= (g.female || 0) ? ["men", g.male] : ["women", g.female];
    const tenths = Math.max(1, Math.min(10, Math.round(lead[1] / 10)));
    lede = (
      <p style={{ fontFamily: t.serif, fontSize: compact ? 19 : 23, lineHeight: 1.45, color: t.ink, margin: 0, maxWidth: 560, letterSpacing: "-0.005em" }}>
        {TENTH_WORDS[tenths]} in ten are <Em>{lead[0]}</Em>{topAge ? <span>, most aged <Em>{topAge.range}</Em></span> : null}{geos.length ? <span> — watching from <Em>{geos[0]}</Em> first.</span> : "."}
      </p>
    );
  }

  return (
    <div>
      {lede}
      <div style={{ display: "grid", gridTemplateColumns: compact ? "1fr" : "1.5fr 1fr", gap: compact ? 26 : 44, marginTop: lede ? (compact ? 24 : 34) : 0 }}>
        <div>
          {ages.length > 0 && (
            <div ref={ageRef}>
              <div style={{ ...monoHead, paddingBottom: 8 }}>Age distribution<sup style={{ color: t.accent }}>{"\u00A0"}1</sup></div>
              {ages.map((r, ri) => {
                const isTop = topAge && r.range === topAge.range;
                return (
                  <div key={r.range} style={{ display: "grid", gridTemplateColumns: "52px 1fr 52px", gap: 14, alignItems: "center", padding: compact ? "7px 0" : "9px 0", borderTop: "1px solid " + t.line }}>
                    <span style={{ fontFamily: "var(--mono)", fontSize: 10.5, color: isTop ? t.ink : t.muted }}>{r.range}</span>
                    <div style={{ position: "relative", height: 12 }} aria-hidden="true">
                      <div style={{ position: "absolute", left: 0, right: 0, top: 5.5, height: 1, background: t.line }}></div>
                      <div style={{ position: "absolute", left: 0, top: 4, width: (ageSeen ? Math.max(2, (r.pct / maxAge) * 100) : 0) + "%", height: 4, background: isTop ? t.accent : t.muted, opacity: isTop ? 1 : 0.4, transition: motion ? "width 0.8s " + revealEase + " " + (ri * 0.08) + "s" : "none" }}></div>
                    </div>
                    <span style={{ fontFamily: t.serif, fontSize: isTop ? 17 : 14, color: isTop ? t.accent : t.ink, textAlign: "right", fontVariantNumeric: "tabular-nums" }}><KrNum motion={motion} value={r.pct + "%"} delay={ri * 80} /></span>
                  </div>
                );
              })}
            </div>
          )}
          {g && (
            <div style={{ marginTop: ages.length ? (compact ? 22 : 30) : 0 }} ref={gRef}>
              <div style={{ ...monoHead, paddingBottom: 8 }}>Gender split<sup style={{ color: t.accent }}>{"\u00A0"}1</sup></div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", borderTop: "1px solid " + t.line, paddingTop: compact ? 10 : 14 }}>
                <div>
                  <span style={{ fontFamily: t.serif, fontSize: compact ? 24 : 30, color: t.accent, fontVariantNumeric: "tabular-nums" }}><KrNum motion={motion} value={g.male + "%"} /></span>
                  <span style={{ ...monoHead, marginLeft: 8 }}>Male</span>
                </div>
                <div>
                  <span style={{ ...monoHead, marginRight: 8 }}>Female</span>
                  <span style={{ fontFamily: t.serif, fontSize: compact ? 24 : 30, color: t.ink, fontVariantNumeric: "tabular-nums" }}><KrNum motion={motion} value={g.female + "%"} /></span>
                </div>
              </div>
              <div style={{ display: "flex", height: 5, marginTop: 10, gap: 2 }} aria-hidden="true">
                <div style={{ width: (gSeen ? g.male : 0) + "%", background: t.accent, transition: motion ? "width 0.8s " + revealEase : "none" }}></div>
                <div style={{ width: (gSeen ? (g.female || 0) : 0) + "%", background: t.muted, opacity: 0.45, transition: motion ? "width 0.8s " + revealEase + " 0.1s" : "none" }}></div>
                {g.other ? <div style={{ width: (gSeen ? g.other : 0) + "%", background: t.line, transition: motion ? "width 0.8s " + revealEase + " 0.2s" : "none" }}></div> : null}
              </div>
            </div>
          )}
        </div>
        <div>
          {geos.length > 0 && (
            <div>
              <div style={{ ...monoHead, paddingBottom: 8 }}>Top countries</div>
              {geos.slice(0, 4).map((geo, i) => (
                <div key={geo} style={{ display: "flex", gap: 12, alignItems: "baseline", padding: compact ? "7px 0" : "9px 0", borderTop: "1px solid " + t.line }}>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: i === 0 ? t.accent : t.muted }}>{String(i + 1).padStart(2, "0")}</span>
                  <span style={{ fontFamily: t.serif, fontSize: i === 0 ? 16.5 : 14, color: t.ink }}>{geo}</span>
                </div>
              ))}
            </div>
          )}
          {cities.length > 0 && (
            <div style={{ marginTop: geos.length ? (compact ? 18 : 26) : 0 }}>
              <div style={{ ...monoHead, paddingBottom: 8 }}>Top cities</div>
              {cities.slice(0, 4).map((c, i) => (
                <div key={c} style={{ display: "flex", gap: 12, alignItems: "baseline", padding: "6px 0", borderTop: "1px solid " + t.line }}>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: t.muted }}>{String(i + 1).padStart(2, "0")}</span>
                  <span style={{ fontSize: 13, color: t.ink }}>{c}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
      <Footnotes t={t} notes={[
        "Audience insights from connected accounts, trailing 90 days. Age fill scaled to the largest segment." + (g && g.other ? " " + g.other + "% other / undisclosed." : "")
      ]} />
    </div>
  );
}

/* ============================================================
   METRICS LEDGER — platform metrics as an annual-report spread
   ============================================================ */
function MetricsLedger({ profile, plats, rates, t, compact, motion }) {
  const E = KitRateEngine;
  const bm = useMemo(() => window.loadBenchmarks(), [rates.benchmarkVersion]);
  const engBand = { lo: bm.engagementTiers[0].maxRate, hi: bm.engagementTiers[1].maxRate };   /* "average" band */
  const reachBand = { lo: bm.viewTiers[0].maxRatio, hi: bm.viewTiers[1].maxRatio };

  return (
    <div>
      {/* column heads */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(120px, 0.9fr) 1fr 1.2fr 1.3fr", gap: compact ? 16 : 24, padding: "0 0 8px", fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase", color: t.muted }}>
        <span>Channel</span><span>Followers</span><span>Avg views · reach</span><span>Engagement · quality</span>
      </div>
      {plats.map(([k, v]) => {
        const ratio = v.avgViews && v.followers ? v.avgViews / v.followers : null;
        const reachTier = ratio != null ? findTier(bm.viewTiers, ratio, "maxRatio") : null;
        const engTier = v.engagement != null ? findTier(bm.engagementTiers, v.engagement, "maxRate") : null;
        const fTier = E.tierFor(v.followers, bm);
        return (
          <div key={k} style={{ display: "grid", gridTemplateColumns: "minmax(120px, 0.9fr) 1fr 1.2fr 1.3fr", gap: compact ? 16 : 24, alignItems: "start", padding: compact ? "14px 0" : "20px 0", borderTop: "1px solid " + t.line }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
              <PlatformMark name={k} size={22} />
              <div>
                <div style={{ fontWeight: 600, fontSize: 13, textTransform: "capitalize" }}>{k}</div>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: t.muted, marginTop: 2 }}>{v.handle}</div>
              </div>
            </div>
            <div>
              <LedgerStat value={E.fmtCompact(v.followers)} label={fTier.label + " tier"} t={t} compact={compact} motion={motion} />
            </div>
            <div>
              <LedgerStat value={v.avgViews ? E.fmtCompact(v.avgViews) : "—"} label={ratio != null ? (ratio >= 1 ? (ratio).toFixed(1) : Math.round(ratio * 100) + "%") + " of following" : "avg views"} t={t} compact={compact} motion={motion} />
              {ratio != null && (
                <MarketRail value={Math.min(ratio, 1.18)} min={0} max={1.2} bandLo={reachBand.lo} bandHi={reachBand.hi} t={t} sup="1" motion={motion}
                  caption={reachTier.label.replace(/-delivering| reach$/gi, "") + " — " + (REACH_DESC[reachTier.id] || "")} />
              )}
            </div>
            <div>
              <LedgerStat value={v.engagement != null ? v.engagement + "%" : "—"} label="Engagement rate" t={t} compact={compact} accent motion={motion} />
              {v.engagement != null && (
                <MarketRail value={Math.min(v.engagement, 7.8)} min={0} max={8} bandLo={engBand.lo} bandHi={engBand.hi} t={t} sup="1" motion={motion}
                  caption={engTier.label + " — " + (ENG_DESC[engTier.id] || "")} />
              )}
            </div>
          </div>
        );
      })}
      <Footnotes t={t} notes={[
        "Shaded band = typical range for creators in this follower tier. Benchmark v" + rates.benchmarkVersion + ", updated " + rates.benchmarkDate + ", " + bm.sources.filter(s => s.status === "active").length + " industry sources.",
        "Engagement = (likes + comments) ÷ followers, trailing 30 days." + (profile.platforms.instagram?.avgStoryViews ? " Story frames average " + KitRateEngine.fmtCompact(profile.platforms.instagram.avgStoryViews) + " views." : "")
      ]} />
    </div>
  );
}

/* ============================================================
   RATE LEDGER — rate card with market-band bars and receipts
   ============================================================ */
function ReceiptLine({ left, right, t, strong, rule }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "4.5px 0", borderTop: rule ? "1px solid " + t.line : "none", fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.02em", color: strong ? t.ink : t.muted, fontWeight: strong ? 600 : 400 }}>
      <span>{left}</span>
      <span style={{ whiteSpace: "nowrap", color: strong ? t.accent : "inherit" }}>{right}</span>
    </div>
  );
}

function RateReceipt({ item, profile, rates, bm, t, open }) {
  const E = KitRateEngine;
  const isUGC = item.platform === "UGC";
  const tierSpan = E.fmtCompact(item.tier.min) + (item.tier.max ? "–" + E.fmtCompact(item.tier.max) : "+") + " followers";
  const niche = bm.nicheMults.find(n => n.id === profile.nicheId);
  const region = bm.regionMults.find(r => r.id === profile.regionId);
  const proof = !isUGC && (profile.pastBrands || []).length >= 2;

  const steps = [];
  steps.push([
    "Market base — " + item.tier.label.toLowerCase() + " tier (" + tierSpan + ")",
    E.fmtRange(item.base[0], item.base[1])
  ]);
  if (item.viewTier && item.viewTier.mult !== 1) steps.push([item.viewTier.label + " (avg views vs following)", "× " + item.viewTier.mult.toFixed(2)]);
  if (item.engTier && item.engTier.mult !== 1) steps.push([item.engTier.label + " engagement", "× " + item.engTier.mult.toFixed(2)]);
  if (niche && niche.mult !== 1) steps.push([niche.label + " — sponsor demand", "× " + niche.mult.toFixed(2)]);
  if (region && region.mult !== 1) steps.push([region.label + " market", "× " + region.mult.toFixed(2)]);
  if (proof) steps.push(["Documented brand work (" + profile.pastBrands.length + " collaborations)", "× 1.05"]);
  if (isUGC) steps.push(["Priced on production value + licensing, not audience", "—"]);

  return (
    <div className={"kr-receipt" + (open ? " open" : "")}>
      <div style={{ margin: "2px 0 14px", padding: "12px 16px 14px", background: t.coverMode === "dark" ? "rgba(244,241,234,0.045)" : "rgba(29,26,21,0.032)", borderTop: "1px solid " + t.line }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12, marginBottom: 8 }}>
          <span style={{ fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase", color: t.accent }}>Pricing receipt</span>
          <span style={{ fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.08em", textTransform: "uppercase", color: t.muted }}>{rates.confidence.label}</span>
        </div>
        {steps.map((s, i) => <ReceiptLine key={i} left={s[0]} right={s[1]} t={t} rule={i > 0} />)}
        <ReceiptLine left={"Offered range — rounded to market increments"} right={E.fmtRange(item.low, item.high)} t={t} strong rule />
        <p style={{ fontFamily: "var(--mono)", fontSize: 9, lineHeight: 1.7, color: t.muted, margin: "10px 0 0", letterSpacing: "0.02em" }}>
          Benchmarked against {item.tier.label.toLowerCase()}-tier creators · v{rates.benchmarkVersion} · updated {rates.benchmarkDate} · {bm.sources.filter(s => s.status === "active").length} industry sources
        </p>
      </div>
    </div>
  );
}
function RateLedgerRow({ item, profile, rates, bm, t, compact, config, scaleMax, motion }) {
  const E = KitRateEngine;
  const [open, setOpen] = useState(false);
  const [rowRef, rowSeen] = useRevealOnce(!motion);
  const pct = (v) => Math.min(100, (v / scaleMax) * 100);
  return (
    <div>
      <div ref={rowRef} className="kr-kit-row" style={{ display: "grid", gridTemplateColumns: compact ? "minmax(0,1.5fr) minmax(110px,auto) 30px" : "minmax(0,1.4fr) 1fr minmax(120px,auto) 30px", gap: compact ? 14 : 22, alignItems: "center", padding: compact ? "10px 0" : "13px 0", borderTop: "1px solid " + t.line }}>
        <div>
          <span style={{ fontWeight: 600, fontSize: 13.5 }}>{item.label}</span>
          <span style={{ fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.12em", textTransform: "uppercase", color: t.muted, marginLeft: 10 }}>{item.platform}</span>
        </div>
        {!compact && (
          <div style={{ position: "relative", height: 12 }} aria-hidden="true">
            <div style={{ position: "absolute", left: 0, right: 0, top: 5.5, height: 1, background: t.line }}></div>
            {/* market base band */}
            <div style={{ position: "absolute", left: pct(item.base[0]) + "%", width: (rowSeen ? Math.max(1.5, pct(item.base[1]) - pct(item.base[0])) : 0) + "%", top: 3.5, height: 5, background: t.muted, opacity: 0.25, transition: motion ? "width 0.7s cubic-bezier(0.22, 0.61, 0.21, 1)" : "none" }}></div>
            {/* creator range */}
            <div style={{ position: "absolute", left: pct(item.low) + "%", width: (rowSeen ? Math.max(2, pct(item.high) - pct(item.low)) : 0) + "%", top: 4.5, height: 3, background: t.accent, borderRadius: 99, transition: motion ? "width 0.8s cubic-bezier(0.22, 0.61, 0.21, 1) 0.2s" : "none" }}></div>
          </div>
        )}
        <div style={{ textAlign: "right", fontFamily: t.serif, fontSize: compact ? 15 : 17, fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>
          <KrNum motion={motion} value={config.showRateRanges ? E.fmtRange(item.low, item.high) : "from " + E.fmtMoney(item.low)} />
        </div>
        <button className="kr-receipt-toggle" onClick={() => setOpen(!open)} aria-label={(open ? "Hide" : "Show") + " pricing receipt for " + item.label} aria-expanded={open} style={{
          width: 22, height: 22, borderRadius: "50%", border: "1px solid " + (open ? t.accent : t.line), justifySelf: "end",
          background: open ? t.accent : "transparent", color: open ? t.accentInk : t.muted, cursor: "pointer",
          display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--mono)", fontSize: 11, lineHeight: 1, padding: 0,
          transition: "background 0.2s, color 0.2s, border-color 0.2s"
        }}>{open ? "×" : "+"}</button>
      </div>
      <RateReceipt item={item} profile={profile} rates={rates} bm={bm} t={t} open={open} />
    </div>
  );
}

function RateLedger({ rates, profile, config, t, compact, motion }) {
  const bm = useMemo(() => window.loadBenchmarks(), [rates.benchmarkVersion]);
  const scaleMax = Math.max(...rates.items.map(i => Math.max(i.high, i.base[1]))) * 1.04;
  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: compact ? "minmax(0,1.5fr) minmax(110px,auto) 30px" : "minmax(0,1.4fr) 1fr minmax(120px,auto) 30px", gap: compact ? 14 : 22, padding: "0 0 8px", fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase", color: t.muted }}>
        <span>Deliverable</span>{!compact && <span>vs market base<sup style={{ color: t.accent }}> 1</sup></span>}<span style={{ textAlign: "right" }}>Rate<sup style={{ color: t.accent }}> 2</sup></span><span></span>
      </div>
      {rates.items.map(i => (
        <RateLedgerRow key={i.id} item={i} profile={profile} rates={rates} bm={bm} t={t} compact={compact} config={config} scaleMax={scaleMax} motion={motion} />
      ))}
      <Footnotes t={t} notes={[
        "Shaded band = unadjusted market base for this follower tier; the accent mark is this creator's adjusted range. Tap + on any line for the full pricing receipt.",
        rates.confidence.label + " — " + rates.confidence.detail + " Final pricing depends on scope, licensing and exclusivity."
      ]} />
    </div>
  );
}

Object.assign(window, { MarketRail, LedgerStat, Footnotes, MetricsLedger, RateLedger, RateReceipt, AudienceLedger });
