/* KitRate — brand-facing public kit page (what the share link serves) */

function BrandShareView({ profile, rates, config, brand, onExit, publicMode = false, publicSlug = null, publicBrandSlug = null }) {
  const url = publicMode ? location.href : KitRateProduct.buildPublicKitUrl({
      origin: location.origin || "file://",
      pathname: location.pathname,
      profileName: profile.name,
      brandName: brand ? brand.brand : null
    });
  const [tracked, setTracked] = useState(false);

  /* live tracking — log an open for this brand link, then measure dwell
     on the rate-card section while it's actually in view */
  useEffect(() => {
    if (!publicMode && (!brand || !brand.id)) return;
    let eventId = null;
    const start = async () => {
      if (publicMode && publicSlug) {
        try {
          const result = await KitRateAPI.recordPublicOpen(publicSlug, publicBrandSlug);
          eventId = result.eventId;
          setTracked(true);
        } catch (e) {}
      } else {
        eventId = recordBrandOpen(brand.id);
        if (eventId) setTracked(true);
      }
    };
    start();

    let dwell = 0;            // accumulated seconds
    let visibleSince = null;  // performance.now() when rates entered view
    const persist = () => {
      if (!eventId) return;
      const total = dwell + (visibleSince != null ? (performance.now() - visibleSince) / 1000 : 0);
      if (publicMode) KitRateAPI.updatePublicDwell(eventId, total).catch(() => {});
      else updateBrandDwell(brand.id, eventId, total);
    };

    let io = null;
    const el = document.querySelector('[data-kit-section="rates"]');
    if (el) {
      io = new IntersectionObserver((entries) => {
        const en = entries[0];
        if (en.isIntersecting) {
          if (visibleSince == null) visibleSince = performance.now();
        } else if (visibleSince != null) {
          dwell += (performance.now() - visibleSince) / 1000;
          visibleSince = null;
          persist();
        }
      }, { threshold: 0.3 });
      io.observe(el);
    }
    const tick = setInterval(persist, 3000);
    return () => { clearInterval(tick); if (io) io.disconnect(); persist(); };
  }, [publicMode, publicSlug, publicBrandSlug, brand && brand.id]);

  return (
    <div className="kr-share-page" data-screen-label="Public kit — brand view" style={{ minHeight: "100vh" }}>
      {!publicMode && <div className="kr-no-print" style={{ display: "flex", alignItems: "center", gap: 12, padding: "9px 20px", background: "var(--warn-soft)", borderBottom: "1px solid #DECCA0", fontSize: 12.5, color: "var(--warn)" }}>
        <KrIcon d={ICONS.eye} size={14} style={{ flexShrink: 0 }} />
        <span style={{ flex: 1 }}>
          Preview — this is exactly what {brand ? brand.brand : "a brand"} sees at <strong style={{ fontFamily: "var(--mono)", fontWeight: 500 }}>{url}</strong>. Hidden sections and rate-visibility settings are applied.
        </span>
        {tracked && (
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", whiteSpace: "nowrap" }}>
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--good)", animation: "krPulse 1.6s ease-in-out infinite" }}></span>
            Open logged · tracking dwell
          </span>
        )}
        <button className="kr-btn kr-btn-secondary kr-btn-sm" onClick={onExit}><KrIcon d={ICONS.arrowLeft} size={12} /> Back to editor</button>
      </div>}

      {/* minimal public header — no app chrome */}
      <header className="kr-no-print" style={{ position: "sticky", top: 0, zIndex: 40, display: "flex", alignItems: "center", gap: 14, padding: "0 24px", height: 56, background: "color-mix(in oklab, var(--surface-2) 82%, white)", backdropFilter: "blur(8px)", borderBottom: "1px solid var(--line)" }}>
        <span className="kr-avatar" style={{ width: 28, height: 28, fontSize: 13 }}>{(profile.name || "K").charAt(0)}</span>
        <div style={{ flex: 1, fontSize: 14, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {profile.name} <span style={{ color: "var(--muted)", fontWeight: 400 }}>· Media kit</span>
        </div>
        <a className="kr-btn kr-btn-primary kr-btn-sm" href={"mailto:" + (profile.email || "")} style={{ textDecoration: "none" }}>
          Start a partnership <KrIcon d={ICONS.arrowRight} size={12} />
        </a>
      </header>

      <main className="kr-share-main" style={{ padding: "36px 24px 32px" }}>
        {brand && brand.note && (
          <div style={{ maxWidth: 760, margin: "0 auto 22px", textAlign: "center" }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--accent)", marginBottom: 8 }}>A note for {brand.brand}</div>
            <p className="kr-serif" style={{ fontSize: 19, lineHeight: 1.5, color: "var(--ink)", margin: "0 auto", maxWidth: 560, fontStyle: "italic" }}>“{brand.note}”</p>
          </div>
        )}
        <KitDocument profile={profile} rates={rates} config={config} shared={true} preparedFor={brand ? brand.brand : null} />
      </main>

      <footer className="kr-no-print" style={{ textAlign: "center", padding: "0 24px 48px", fontSize: 12.5, color: "var(--muted)" }}>
        Made with <span className="kr-serif" style={{ fontWeight: 600, color: "var(--ink)" }}>Kit<em style={{ fontWeight: 400, color: "var(--accent)" }}>Rate</em></span> — rate-benchmarked media kits for creators.
      </footer>
    </div>
  );
}

window.BrandShareView = BrandShareView;
