/* KitRate — the media kit document + template themes */

/* ---------- template themes (1 flagship + 4 variants) ---------- */
const KIT_THEMES = [
  {
    id: "editorial", label: "Minimal editorial",
    bg: "#FBFAF6", ink: "#1D1A15", muted: "#7C7466", line: "#E2DCCF",
    accent: "#1F3A8F", accentInk: "#FFFFFF",
    serif: "'Newsreader', Georgia, serif", sans: "'Schibsted Grotesk', sans-serif",
    coverMode: "light", desc: "Quiet confidence — hairlines, serif headlines, lots of air."
  },
  {
    id: "bold", label: "Bold creator portfolio",
    bg: "#16140F", ink: "#F4F1EA", muted: "#9B948A", line: "#33302A",
    accent: "#E0742C", accentInk: "#16140F",
    serif: "'Archivo', sans-serif", sans: "'Schibsted Grotesk', sans-serif",
    coverMode: "dark", desc: "Dark ground, oversized type, athletic energy."
  },
  {
    id: "luxe", label: "Luxury beauty / fashion",
    bg: "#F5EFE6", ink: "#2E2418", muted: "#8A7B66", line: "#E0D5C2",
    accent: "#8E6F3E", accentInk: "#FFFFFF",
    serif: "'Libre Caslon Text', Georgia, serif", sans: "'Archivo', sans-serif",
    coverMode: "light", desc: "Champagne neutrals, Caslon serifs, gallery spacing."
  },
  {
    id: "vital", label: "Fitness / wellness",
    bg: "#F4F4EF", ink: "#1B2620", muted: "#6E7A70", line: "#DCDED2",
    accent: "#1F5C40", accentInk: "#FFFFFF",
    serif: "'Schibsted Grotesk', sans-serif", sans: "'Schibsted Grotesk', sans-serif",
    coverMode: "light", desc: "Clean grotesque, deep green, performance-data forward."
  },
  {
    id: "ugc", label: "UGC performance marketer",
    bg: "#FFFFFF", ink: "#171717", muted: "#737373", line: "#E8E5DE",
    accent: "#1F3A8F", accentInk: "#FFFFFF",
    serif: "'Spline Sans Mono', monospace", sans: "'Schibsted Grotesk', sans-serif",
    coverMode: "stat", desc: "Stat-led, mono accents — built to read like a results sheet."
  }
];

const KIT_SECTIONS = [
  { id: "cover", label: "Cover" },
  { id: "bio", label: "About" },
  { id: "audience", label: "Audience snapshot" },
  { id: "metrics", label: "Platform metrics" },
  { id: "showcase", label: "Video showcase" },
  { id: "pillars", label: "Content pillars" },
  { id: "partners", label: "Brand collaborations" },
  { id: "testimonials", label: "Testimonials" },
  { id: "packages", label: "Packages & deliverables" },
  { id: "rates", label: "Rate card" },
  { id: "addons", label: "Usage rights & add-ons" },
  { id: "casestudy", label: "Case study" },
  { id: "contact", label: "Contact / CTA" }
];

const DEFAULT_KIT_CONFIG = {
  templateId: "editorial",
  hidden: [],
  order: KIT_SECTIONS.map(s => s.id),
  showRates: true,
  showRateRanges: true,   // false = midpoint "from $X"
  packageNames: ["Testing the Waters", "The Single Round", "Fight Camp Series", "Main Event Retainer"],
  showcaseKpi: "smart",     /* smart | views | engagement | recent */
  density: "comfortable"  // comfortable | compact
};

/* ---------- helpers ---------- */
function kitPackages(rates, names) {
  const E = KitRateEngine;
  const organic = rates.items.filter(i => i.platform !== "UGC").sort((a, b) => b.mid - a.mid);
  if (!organic.length) return [];
  const top = organic[0], second = organic[1] || organic[0];
  const pk = [];
  const entryFloor = E.roundRate(Math.max(top.floor || top.low, (top.target || top.mid) * 0.72));
  const entryAnchor = E.roundRate(Math.max(entryFloor, (top.target || top.mid) * 0.9));
  pk.push({
    name: names[0] || "Testing the Waters",
    contents: ["1× " + top.label, "One revision", "30-day organic usage"],
    blurb: "A simple first collab to see the fit — one post, no commitment.",
    low: entryFloor, high: entryAnchor, flat: entryFloor === entryAnchor, tag: "Start here"
  });
  pk.push({
    name: names[1] || "Single",
    contents: ["1× " + top.label, "1× Story set (3 frames)"],
    blurb: "A single, well-made placement with full production attention.",
    low: E.roundRate(top.low * 1.18), high: E.roundRate(top.high * 1.18)
  });
  /* best-value bundle — priced between the single placement and the retainer */
  pk.push({
    name: names[2] || "Series",
    contents: ["2× " + top.label, "1× " + second.label, "30-day organic usage"],
    blurb: "A multi-week narrative arc — the format that performs best.",
    low: E.roundRate((top.low * 2 + second.low) * 0.95), high: E.roundRate((top.high * 2 + second.high) * 0.95),
    featured: true, tag: "Best value"
  });
  if (rates.retainer) {
    pk.push({
      name: names[3] || "Retainer",
      contents: [...rates.retainer.items, "Monthly performance recap", "Priority scheduling"],
      blurb: "Always-on partnership, priced under à-la-carte.",
      low: rates.retainer.low, high: rates.retainer.high, perMonth: true
    });
  }
  return pk;
}

/* ---------- the document ---------- */
function KitDocument({ profile, rates, config, scale = 1, shared = false, preparedFor = null }) {
  const t = KIT_THEMES.find(x => x.id === config.templateId) || KIT_THEMES[0];
  const E = KitRateEngine;
  const compact = config.density === "compact";
  /* motion gating — "countup" tweak widens count-up beyond the share page;
     "reveal" slides sections in on scroll (share page only, transform-only so
     print and DOM captures never hide content) */
  const krTweaks = window.KR_TWEAKS || {};
  const countMode = krTweaks.countup || "share";
  const motion = !KR_REDUCED_MOTION && countMode !== "off" && (shared || countMode === "everywhere");
  const reveal = shared && !KR_REDUCED_MOTION && krTweaks.reveal !== false;
  const pad = compact ? "40px 52px" : "56px 64px";
  const visible = config.order.filter(id => !config.hidden.includes(id));
  const packages = kitPackages(rates, config.packageNames);
  const plats = Object.entries(profile.platforms || {}).filter(([, v]) => v && v.followers);
  const a = profile.audience || {};
  /* section numbers follow the visible order, so drag-reorder renumbers cleanly */
  const num = (id) => String(visible.filter(x => x !== "cover" && x !== "contact").indexOf(id) + 1).padStart(2, "0");
  const topReels = rankReels(profile.reels, config.showcaseKpi || "smart");

  const eyebrowStyle = { fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: t.muted };
  const h2Style = { fontFamily: t.serif, fontSize: compact ? 26 : 30, fontWeight: 500, letterSpacing: "-0.01em", color: t.ink, margin: "8px 0 0" };

  const Section = ({ id, eyebrow, title, children, style }) => {
    const [revealRef, revealSeen] = useRevealOnce(!reveal);
    return (
      <section ref={revealRef} data-kit-section={id} data-screen-label={"Kit — " + (title || id)} style={{
        padding: pad, borderTop: "1px solid " + t.line,
        transform: revealSeen ? "none" : "translateY(22px)",
        transition: reveal ? "transform 0.7s cubic-bezier(0.22, 0.61, 0.21, 1)" : "none",
        ...style
      }}>
        {eyebrow && <div style={eyebrowStyle}>{eyebrow}</div>}
        {title && <h2 style={h2Style}>{title}</h2>}
        <div style={{ marginTop: title ? (compact ? 18 : 26) : 0 }}>{children}</div>
      </section>
    );
  };

  const renderers = {
    cover: () => (
      <section className="kr-kit-cover" data-screen-label="Kit — Cover" style={{
        padding: compact ? "56px 52px" : "76px 64px",
        background: t.coverMode === "dark" ? t.ink : "transparent",
        color: t.coverMode === "dark" ? t.bg : t.ink
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 24 }}>
          <div style={{ ...eyebrowStyle, color: t.coverMode === "dark" ? "rgba(244,241,234,0.55)" : t.muted }}>
            Media kit · {new Date().getFullYear()}{preparedFor ? <span style={{ color: t.accent }}> — prepared for {preparedFor}</span> : null}
          </div>
          <div style={{ ...eyebrowStyle, color: t.accent }}>{profile.platforms.instagram?.handle || profile.website}</div>
        </div>
        <div className="kr-kit-cover-main" style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) auto", gap: 40, alignItems: "end", marginTop: compact ? 48 : 80 }}>
          <div>
            <h1 style={{ fontFamily: t.serif, fontSize: config.templateId === "bold" ? 64 : 54, fontWeight: config.templateId === "bold" ? 800 : 500, lineHeight: 1.02, letterSpacing: "-0.02em", margin: 0, textTransform: config.templateId === "bold" ? "uppercase" : "none" }}>
              {profile.name || "Your Name"}
            </h1>
            <p style={{ fontSize: 16, marginTop: 16, opacity: 0.8, maxWidth: 420 }}>{profile.tagline}</p>
            <div style={{ display: "flex", gap: 10, marginTop: 22, flexWrap: "wrap" }}>
              {[profile.nicheLabel, profile.location].filter(Boolean).map(x => (
                <span key={x} style={{ ...eyebrowStyle, whiteSpace: "nowrap", border: "1px solid " + (t.coverMode === "dark" ? "rgba(244,241,234,0.3)" : t.line), borderRadius: 99, padding: "5px 12px", color: "inherit", opacity: 0.85 }}>{x}</span>
              ))}
            </div>
          </div>
          <image-slot id={"kit-hero-" + config.templateId} shape="rounded" radius="6" placeholder="Creator photo"
            style={{ width: 200, height: 250, flexShrink: 0, border: "1px solid " + t.line }}></image-slot>
        </div>
        {t.coverMode === "stat" && plats.length > 0 && (
          <div className="kr-kit-cover-stats" style={{ display: "flex", gap: 40, marginTop: 48, paddingTop: 24, borderTop: "1px solid " + t.line }}>
            {plats.map(([k, v]) => (
              <div key={k}>
                <div style={{ fontFamily: t.serif, fontSize: 26 }}>{E.fmtCompact(v.followers)}</div>
                <div style={{ ...eyebrowStyle, marginTop: 4 }}>{k} followers</div>
              </div>
            ))}
          </div>
        )}
      </section>
    ),

    bio: () => (
      <Section id="bio" eyebrow={num("bio") + " — About"} title={"Meet " + (profile.name ? profile.name.split(" ")[0] : "the creator")}>
        <p style={{ fontFamily: t.serif, fontSize: compact ? 17 : 19, lineHeight: 1.6, color: t.ink, maxWidth: 580 }}>{profile.bio || "Add a short bio in the editor."}</p>
      </Section>
    ),

    audience: () => (
      <Section id="audience" eyebrow={num("audience") + " — Audience"} title="Who's watching">
        <AudienceLedger profile={profile} t={t} compact={compact} motion={motion} />
      </Section>
    ),

    metrics: () => (
      <Section id="metrics" eyebrow={num("metrics") + " — Performance"} title="Platform metrics">
        <MetricsLedger profile={profile} plats={plats} rates={rates} t={t} compact={compact} motion={motion} />
      </Section>
    ),

    showcase: () => topReels.length === 0 ? null : (
      <Section id="showcase" eyebrow={num("showcase") + " — Proof in motion"} title="Top-performing content">
        <ReelSlider reels={topReels} t={t} compact={compact} eyebrowStyle={eyebrowStyle} />
        <p style={{ fontSize: 11.5, color: t.muted, marginTop: compact ? 14 : 18, textAlign: "center" }}>
          Auto-selected from connected accounts — ranked by {{ smart: "views × engagement", views: "views", engagement: "engagement rate", recent: "most recent" }[config.showcaseKpi || "smart"]}, trailing 120 days.
        </p>
      </Section>
    ),

    pillars: () => (
      <Section id="pillars" eyebrow={num("pillars") + " — Content"} title="Content pillars">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(190px, 1fr))", gap: compact ? 16 : 24 }}>
          {(profile.pillars || []).map((pl, i) => (
            <div key={i}>
              <div style={{ fontFamily: t.serif, fontStyle: t.serif.includes("Newsreader") || t.serif.includes("Caslon") ? "italic" : "normal", fontSize: 15, color: t.accent, marginBottom: 8 }}>{String(i + 1).padStart(2, "0")}</div>
              <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 6 }}>{pl.title}</div>
              <p style={{ fontSize: 13, color: t.muted, lineHeight: 1.55 }}>{pl.desc}</p>
            </div>
          ))}
          {(profile.contentFormats || []).length > 0 && (
            <div style={{ gridColumn: "1 / -1", display: "flex", gap: 8, flexWrap: "wrap", marginTop: 4 }}>
              {profile.contentFormats.map(f => (
                <span key={f} style={{ ...eyebrowStyle, whiteSpace: "nowrap", border: "1px solid " + t.line, borderRadius: 99, padding: "5px 12px" }}>{f}</span>
              ))}
            </div>
          )}
        </div>
      </Section>
    ),

    partners: () => (
      <Section id="partners" eyebrow={num("partners") + " — Track record"} title="Brand collaborations">
        <div style={{ display: "grid", gap: 0 }}>
          {(profile.pastBrands || []).map((b, i) => (
            <div key={i} className="kr-kit-row" style={{ display: "grid", gridTemplateColumns: "minmax(130px,1fr) minmax(110px,0.8fr) minmax(0,1.6fr)", gap: 18, padding: "14px 0", borderBottom: "1px solid " + t.line, alignItems: "baseline" }}>
              <div style={{ fontFamily: t.serif, fontSize: 16.5 }}>{b.name}</div>
              <div style={{ ...eyebrowStyle }}>{b.category}</div>
              <div style={{ fontSize: 13, color: t.muted }}>{b.result}</div>
            </div>
          ))}
        </div>
        {(profile.pastBrands || []).length === 0 && <p style={{ color: t.muted, fontSize: 13.5 }}>Open to first partnerships — UGC samples available on request.</p>}
      </Section>
    ),

    testimonials: () => (profile.testimonials || []).length === 0 ? null : (
      <Section id="testimonials" eyebrow={num("testimonials") + " — In their words"} title={null}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: compact ? 18 : 28 }}>
          {(profile.testimonials || []).map((tm, i) => (
            <figure key={i} style={{ margin: 0 }}>
              <blockquote style={{ margin: 0, fontFamily: t.serif, fontSize: compact ? 16 : 18, lineHeight: 1.55, color: t.ink }}>
                <span style={{ color: t.accent }}>“</span>{tm.quote}<span style={{ color: t.accent }}>”</span>
              </blockquote>
              <figcaption style={{ ...eyebrowStyle, marginTop: 12 }}>— {tm.author}</figcaption>
            </figure>
          ))}
        </div>
      </Section>
    ),

    packages: () => (
      <Section id="packages" eyebrow={num("packages") + " — Working together"} title="Packages">
        <div className="kr-kit-packages" style={{ display: "grid", gridTemplateColumns: "repeat(" + packages.length + ", minmax(0, 1fr))", gap: 12, alignItems: "stretch" }}>
          {packages.map((pk, i) => (
            <div key={i} className="kr-kit-pkg" style={{
              display: "flex", flexDirection: "column",
              border: pk.featured ? "1.5px solid " + t.accent : "1px solid " + t.line, borderRadius: 12,
              padding: compact ? "16px 13px" : "20px 14px", position: "relative",
              background: pk.featured ? (t.coverMode === "dark" ? "rgba(224,116,44,0.08)" : t.accent + "0D") : "transparent"
            }}>
              {pk.tag && (
                <div style={{ ...eyebrowStyle, color: pk.featured ? t.accent : t.muted, position: "absolute", top: -9, left: "50%", transform: "translateX(-50%)", background: t.bg, padding: "0 8px", whiteSpace: "nowrap" }}>{pk.tag}</div>
              )}
              <div style={{ fontFamily: t.serif, fontSize: 17.5, lineHeight: 1.2, marginBottom: 6 }}>{pk.name}</div>
              <p style={{ fontSize: 12, color: t.muted, marginBottom: 12, lineHeight: 1.45 }}>{pk.blurb}</p>
              <ul style={{ margin: "0 0 16px", padding: 0, listStyle: "none", fontSize: 12.5, flex: 1 }}>
                {pk.contents.map(c => <li key={c} style={{ padding: "4px 0", borderBottom: "1px solid " + t.line }}>{c}</li>)}
              </ul>
              {config.showRates && (
                <div>
                  <div style={{ fontFamily: t.serif, fontSize: pk.featured ? 18 : 15.5, color: t.accent, letterSpacing: "-0.01em" }}>
                    {pk.flat ? E.fmtMoney(pk.low) : config.showRateRanges ? E.fmtRange(pk.low, pk.high) : "from " + E.fmtMoney(pk.low)}
                    {pk.perMonth && <span style={{ fontSize: 12, color: t.muted }}> /mo</span>}
                  </div>
                  {pk.flat && <div style={{ ...eyebrowStyle, fontSize: 9.5, marginTop: 3 }}>Flat rate</div>}
                  {pk.featured && <div style={{ ...eyebrowStyle, fontSize: 9.5, marginTop: 3, color: t.accent }}>Bundle — under à-la-carte</div>}
                </div>
              )}
            </div>
          ))}
        </div>
        <p style={{ fontSize: 11.5, color: t.muted, marginTop: 16 }}>All sponsored content includes platform-appropriate paid-partnership disclosure.</p>
      </Section>
    ),

    rates: () => config.showRates ? (
      <Section id="rates" eyebrow={num("rates") + " — Rate card"} title="À-la-carte rates">
        <RateLedger rates={rates} profile={profile} config={config} t={t} compact={compact} motion={motion} />
      </Section>
    ) : null,

    addons: () => config.showRates ? (
      <Section id="addons" eyebrow={num("addons") + " — Licensing"} title="Usage rights & add-ons">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: "10px 28px" }}>
          {rates.addons.map(ad => (
            <div key={ad.id} style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "9px 0", borderBottom: "1px solid " + t.line, fontSize: 13 }}>
              <span>{ad.label}</span>
              <span style={{ fontFamily: "var(--mono)", fontSize: 12.5, color: t.accent, whiteSpace: "nowrap" }}>+{ad.pct}%</span>
            </div>
          ))}
        </div>
        <p style={{ fontSize: 11.5, color: t.muted, marginTop: 14 }}>Organic posting rights for 30 days are included with every deliverable. Anything beyond — paid amplification, whitelisting, exclusivity, perpetual use — is licensed separately so both sides know exactly what's covered.</p>
      </Section>
    ) : null,

    casestudy: () => profile.caseStudy ? (
      <Section id="casestudy" eyebrow={num("casestudy") + " — Case study"} title={profile.caseStudy.title}>
        <p style={{ fontSize: 14, color: t.muted, maxWidth: 540, lineHeight: 1.6 }}>{profile.caseStudy.context}</p>
        <div style={{ ...eyebrowStyle, margin: "16px 0 22px" }}>{profile.caseStudy.deliverables}</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 24 }}>
          {profile.caseStudy.results.map((r, i) => (
            <div key={i} style={{ borderTop: "2px solid " + t.accent, paddingTop: 12 }}>
              <div style={{ fontFamily: t.serif, fontSize: 30 }}>{r.metric}</div>
              <div style={{ fontSize: 12, color: t.muted, marginTop: 4 }}>{r.label}</div>
            </div>
          ))}
        </div>
      </Section>
    ) : null,

    contact: () => (
      <section data-screen-label="Kit — Contact" style={{ padding: compact ? "48px 52px" : "72px 64px", background: t.coverMode === "dark" ? t.accent : t.ink, color: t.coverMode === "dark" ? t.accentInk : t.bg, textAlign: "center" }}>
        <div style={{ ...eyebrowStyle, color: "inherit", opacity: 0.6, marginBottom: 14 }}>Next step</div>
        <h2 style={{ fontFamily: t.serif, fontSize: compact ? 30 : 38, fontWeight: 500, letterSpacing: "-0.015em", margin: 0 }}>Let's build a campaign.</h2>
        <p style={{ marginTop: 14, fontSize: 14.5, opacity: 0.8 }}>{profile.email}{profile.website ? " · " + profile.website : ""}</p>
        <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 24, flexWrap: "wrap" }}>
          {plats.map(([k, v]) => (
            <span key={k} style={{ ...eyebrowStyle, whiteSpace: "nowrap", color: "inherit", border: "1px solid currentColor", opacity: 0.7, borderRadius: 99, padding: "5px 14px" }}>{k}: {v.handle}</span>
          ))}
        </div>
      </section>
    )
  };

  return (
    <div className="kr-kitdoc" style={{
      background: t.bg, color: t.ink, fontFamily: t.sans, width: 760,
      transform: scale !== 1 ? "scale(" + scale + ")" : "none", transformOrigin: "top center",
      boxShadow: shared ? "var(--shadow-2)" : "var(--shadow-1)",
      borderRadius: 4, overflow: "hidden", margin: "0 auto",
      border: "1px solid var(--line)"
    }}>
      {visible.map(id => {
        const r = renderers[id];
        return r ? <React.Fragment key={id}>{r()}</React.Fragment> : null;
      })}
      <div className="kr-kit-footer" style={{ padding: "16px 64px", fontSize: 10, fontFamily: "var(--mono)", letterSpacing: "0.12em", textTransform: "uppercase", color: t.muted, display: "flex", justifyContent: "space-between", borderTop: "1px solid " + t.line }}>
        <span>Made with KitRate</span>
        <span>Rates benchmarked {rates.benchmarkDate}</span>
      </div>
    </div>
  );
}

Object.assign(window, { KIT_THEMES, KIT_SECTIONS, DEFAULT_KIT_CONFIG, KitDocument, kitPackages });
