// Cards.jsx — UseCaseCard, AudienceCard, StarterPackCard

const HeartIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
  </svg>
);

const ArrowRightIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <line x1="5" y1="12" x2="19" y2="12" />
    <polyline points="12 5 19 12 12 19" />
  </svg>
);


function PhaseVisual({ phaseId }) {
  if (phaseId === "launch") return (
    <svg className="tb-breaker-card__svg" width="260" height="120" viewBox="0 0 260 120" fill="none" xmlns="http://www.w3.org/2000/svg">
  <line x1="28" y1="84" x2="232" y2="84" stroke="rgba(31,10,56,0.14)" strokeWidth="3" strokeLinecap="round"></line>
  <circle cx="79" cy="84" r="4.5" fill="#ffffff" stroke="rgba(31,10,56,0.18)" strokeWidth="2"></circle>
  <circle cx="130" cy="84" r="4.5" fill="#ffffff" stroke="rgba(31,10,56,0.18)" strokeWidth="2"></circle>
  <circle cx="181" cy="84" r="4.5" fill="#ffffff" stroke="rgba(31,10,56,0.18)" strokeWidth="2"></circle>
  <circle cx="232" cy="84" r="4.5" fill="#ffffff" stroke="rgba(31,10,56,0.18)" strokeWidth="2"></circle>
  <circle cx="28" cy="84" r="13" fill="rgba(31,10,56,0.05)"></circle>
  <circle cx="28" cy="84" r="9" fill="none" stroke="rgba(31,10,56,0.22)" strokeWidth="2"></circle>
  <circle cx="28" cy="84" r="4.5" fill="rgba(31,10,56,0.42)"></circle>
</svg>
  );
  if (phaseId === "vis-promo") return (
    <svg className="tb-breaker-card__svg" width="260" height="120" viewBox="0 0 260 120" fill="none" xmlns="http://www.w3.org/2000/svg">
  <line x1="28" y1="84" x2="232" y2="84" stroke="rgba(31,10,56,0.14)" strokeWidth="3" strokeLinecap="round"></line>
  <line x1="28" y1="84" x2="79" y2="84" stroke="rgba(31,10,56,0.30)" strokeWidth="3" strokeLinecap="round"></line>
  <circle cx="28" cy="84" r="4.5" fill="rgba(31,10,56,0.28)"></circle>
  <circle cx="130" cy="84" r="4.5" fill="#ffffff" stroke="rgba(31,10,56,0.18)" strokeWidth="2"></circle>
  <circle cx="181" cy="84" r="4.5" fill="#ffffff" stroke="rgba(31,10,56,0.18)" strokeWidth="2"></circle>
  <circle cx="232" cy="84" r="4.5" fill="#ffffff" stroke="rgba(31,10,56,0.18)" strokeWidth="2"></circle>
  <circle cx="79" cy="84" r="13" fill="rgba(31,10,56,0.05)"></circle>
  <circle cx="79" cy="84" r="9" fill="none" stroke="rgba(31,10,56,0.22)" strokeWidth="2"></circle>
  <circle cx="79" cy="84" r="4.5" fill="rgba(31,10,56,0.42)"></circle>
</svg>
  );
  if (phaseId === "reg-drive") return (
    <svg className="tb-breaker-card__svg" width="260" height="120" viewBox="0 0 260 120" fill="none" xmlns="http://www.w3.org/2000/svg">
  <line x1="28" y1="84" x2="232" y2="84" stroke="rgba(31,10,56,0.14)" strokeWidth="3" strokeLinecap="round"></line>
  <line x1="28" y1="84" x2="130" y2="84" stroke="rgba(31,10,56,0.30)" strokeWidth="3" strokeLinecap="round"></line>
  <circle cx="28" cy="84" r="4.5" fill="rgba(31,10,56,0.28)"></circle>
  <circle cx="79" cy="84" r="4.5" fill="rgba(31,10,56,0.28)"></circle>
  <circle cx="181" cy="84" r="4.5" fill="#ffffff" stroke="rgba(31,10,56,0.18)" strokeWidth="2"></circle>
  <circle cx="232" cy="84" r="4.5" fill="#ffffff" stroke="rgba(31,10,56,0.18)" strokeWidth="2"></circle>
  <circle cx="130" cy="84" r="13" fill="rgba(31,10,56,0.05)"></circle>
  <circle cx="130" cy="84" r="9" fill="none" stroke="rgba(31,10,56,0.22)" strokeWidth="2"></circle>
  <circle cx="130" cy="84" r="4.5" fill="rgba(31,10,56,0.42)"></circle>
</svg>
  );
  if (phaseId === "showtime") return (
    <svg className="tb-breaker-card__svg" width="260" height="120" viewBox="0 0 260 120" fill="none" xmlns="http://www.w3.org/2000/svg">
  <line x1="28" y1="84" x2="232" y2="84" stroke="rgba(31,10,56,0.14)" strokeWidth="3" strokeLinecap="round"></line>
  <line x1="28" y1="84" x2="181" y2="84" stroke="rgba(31,10,56,0.30)" strokeWidth="3" strokeLinecap="round"></line>
  <circle cx="28" cy="84" r="4.5" fill="rgba(31,10,56,0.28)"></circle>
  <circle cx="79" cy="84" r="4.5" fill="rgba(31,10,56,0.28)"></circle>
  <circle cx="130" cy="84" r="4.5" fill="rgba(31,10,56,0.28)"></circle>
  <circle cx="232" cy="84" r="4.5" fill="#ffffff" stroke="rgba(31,10,56,0.18)" strokeWidth="2"></circle>
  <circle cx="181" cy="84" r="13" fill="rgba(31,10,56,0.05)"></circle>
  <circle cx="181" cy="84" r="9" fill="none" stroke="rgba(31,10,56,0.22)" strokeWidth="2"></circle>
  <circle cx="181" cy="84" r="4.5" fill="rgba(31,10,56,0.42)"></circle>
</svg>
  );
  if (phaseId === "post-event") return (
    <svg className="tb-breaker-card__svg" width="260" height="120" viewBox="0 0 260 120" fill="none" xmlns="http://www.w3.org/2000/svg">
  <line x1="28" y1="84" x2="232" y2="84" stroke="rgba(31,10,56,0.14)" strokeWidth="3" strokeLinecap="round"></line>
  <line x1="28" y1="84" x2="232" y2="84" stroke="rgba(31,10,56,0.30)" strokeWidth="3" strokeLinecap="round"></line>
  <circle cx="28" cy="84" r="4.5" fill="rgba(31,10,56,0.28)"></circle>
  <circle cx="79" cy="84" r="4.5" fill="rgba(31,10,56,0.28)"></circle>
  <circle cx="130" cy="84" r="4.5" fill="rgba(31,10,56,0.28)"></circle>
  <circle cx="181" cy="84" r="4.5" fill="rgba(31,10,56,0.28)"></circle>
  <circle cx="232" cy="84" r="13" fill="rgba(31,10,56,0.05)"></circle>
  <circle cx="232" cy="84" r="9" fill="none" stroke="rgba(31,10,56,0.22)" strokeWidth="2"></circle>
  <circle cx="232" cy="84" r="4.5" fill="rgba(31,10,56,0.42)"></circle>
</svg>
  );
  return null;
}

function AudienceVisual({ audienceId }) {
  if (audienceId === "attendees") return (
    <svg className="tb-breaker-card__svg" width="160" height="96" viewBox="0 0 160 96" fill="none" xmlns="http://www.w3.org/2000/svg">
  <circle cx="24" cy="20" r="7" fill="#9ff7e4"></circle>
  <circle cx="61" cy="20" r="7" fill="#fdcfb1"></circle>
  <circle cx="98" cy="20" r="7" fill="#aef1fa"></circle>
  <circle cx="135" cy="20" r="7" fill="#fff5cb"></circle>
  <circle cx="24" cy="48" r="7" fill="#fdcfb1"></circle>
  <circle cx="61" cy="48" r="7" fill="#fcd456"></circle>
  <circle cx="98" cy="48" r="7" fill="#9ff7e4"></circle>
  <circle cx="135" cy="48" r="7" fill="#aef1fa"></circle>
  <circle cx="24" cy="76" r="7" fill="#aef1fa"></circle>
  <circle cx="61" cy="76" r="7" fill="#9ff7e4"></circle>
  <circle cx="98" cy="76" r="7" fill="#fdcfb1"></circle>
  <circle cx="135" cy="76" r="7" fill="#fcd456"></circle>
</svg>
  );
  if (audienceId === "exhibitors") return (
    <svg className="tb-breaker-card__svg" width="160" height="96" viewBox="0 0 160 96" fill="none" xmlns="http://www.w3.org/2000/svg">
  <rect x="20" y="14" width="28" height="28" rx="7" fill="#9ff7e4"></rect>
  <rect x="66" y="14" width="28" height="28" rx="7" fill="#fcd456"></rect>
  <rect x="112" y="14" width="28" height="28" rx="7" fill="#aef1fa"></rect>
  <rect x="43" y="54" width="28" height="28" rx="7" fill="#fdcfb1"></rect>
  <rect x="89" y="54" width="28" height="28" rx="7" fill="#fff5cb"></rect>
</svg>
  );
  if (audienceId === "sponsors") return (
    <svg className="tb-breaker-card__svg" width="120" height="100" viewBox="0 0 120 100" fill="none" xmlns="http://www.w3.org/2000/svg">
  <circle cx="60" cy="50" r="42" stroke="#1f0a38" stroke-opacity="0.18" strokeWidth="1.5"></circle>
  <circle cx="60" cy="50" r="28" stroke="#1f0a38" stroke-opacity="0.18" strokeWidth="1.5"></circle>
  <circle cx="60" cy="22" r="6" fill="#9ff7e4"></circle>
  <circle cx="36" cy="64" r="6" fill="#fdcfb1"></circle>
  <circle cx="84" cy="64" r="6" fill="#aef1fa"></circle>
  <circle cx="60" cy="50" r="11" fill="#fcd456"></circle>
</svg>
  );
  if (audienceId === "speakers") return (
    <svg className="tb-breaker-card__svg" width="170" height="96" viewBox="0 0 170 96" fill="none" xmlns="http://www.w3.org/2000/svg">
  <line x1="52" y1="48" x2="128" y2="24" stroke="#1f0a38" stroke-opacity="0.18" strokeWidth="1.5"></line>
  <line x1="52" y1="48" x2="128" y2="48" stroke="#1f0a38" stroke-opacity="0.18" strokeWidth="1.5"></line>
  <line x1="52" y1="48" x2="128" y2="72" stroke="#1f0a38" stroke-opacity="0.18" strokeWidth="1.5"></line>
  <rect x="16" y="34" width="36" height="28" rx="8" fill="#fcd456"></rect>
  <rect x="128" y="16" width="34" height="16" rx="5" fill="#9ff7e4"></rect>
  <rect x="128" y="40" width="34" height="16" rx="5" fill="#fdcfb1"></rect>
  <rect x="128" y="64" width="34" height="16" rx="5" fill="#aef1fa"></rect>
</svg>
  );
  return null;
}

function BreakerCardVisual({ kind, id }) {
  if (kind === "phase") return <PhaseVisual phaseId={id} />;
  if (kind === "audience") return <AudienceVisual audienceId={id} />;
  return (
    <div className="tb-aud-card__avatars">
      <div className="tb-aud-card__avatar"></div>
      <div className="tb-aud-card__avatar"></div>
      <div className="tb-aud-card__avatar"></div>
    </div>
  );
}

function UseCaseCard({ id, title, phase, page, audience, videos, variant = 0, onClick, onUseTemplate }) {
  // Phase + page chip lookups (data lives on window from templates-data.js).
  const phaseDef = (window.PHASES || []).find((p) => p.id === phase);
  // Thumbnail variant is derived from video count (1..6 → variant 0..5),
  // so the diagram matches the real flow shape.
  const flowVariant = Math.max(0, Math.min(5, ((videos || []).length || 1) - 1));
  const phaseLabel = phaseDef ? phaseDef.label : null;
  const pageLabel = (window.PAGES || {})[page] || null;
  const audienceLabel = (window.AUDIENCES || {})[audience] || null;
  const videoCount = Array.isArray(videos) ? videos.length : 0;

  return (
    <div className="tb-card" onClick={onClick}>
      <div className="tb-card__media">
        {phaseLabel && (
          <span className={"tb-card__corner-badge is-phase is-phase-" + phase}>
            <span>{phaseLabel}</span>
          </span>
        )}
        <div className="tb-card__thumb">
          <FlowThumbnail variant={flowVariant} />
        </div>
        <div className="tb-card__hover">
          <button
            className="tb-card__hover-cta"
            onClick={(e) => { e.stopPropagation(); onUseTemplate && onUseTemplate(); }}
          >
            Use This Template
          </button>
          <button className="tb-card__hover-link" onClick={(e) => { e.stopPropagation(); onClick && onClick(); }}>
            See details →
          </button>
        </div>
      </div>
      <div>
        <p className="tb-card__title">{title}</p>
        <div className="tb-card__meta">
          <span>{videoCount} {videoCount === 1 ? "video" : "videos"}</span>
        </div>
      </div>
    </div>
  );
}

function AudienceCard({ label, count, tone = "yellow", onClick }) {
  return (
    <button className="tb-aud-card" onClick={onClick}>
      <div className={"tb-aud-card__visual is-" + tone}>
        <div className="tb-aud-card__avatars">
          <div className="tb-aud-card__avatar"></div>
          <div className="tb-aud-card__avatar"></div>
          <div className="tb-aud-card__avatar"></div>
        </div>
      </div>
      <div className="tb-aud-card__body">
        <div>
          <p className="tb-aud-card__name">{label}</p>
          <p className="tb-aud-card__count">{count} Templates</p>
        </div>
        <div className="tb-aud-card__arrow">
          <ArrowRightIcon />
        </div>
      </div>
    </button>
  );
}

function StarterPackCard({ name, description, templateCount, variants, onClick }) {
  return (
    <div className="tb-pack" onClick={onClick}>
      <div className="tb-pack__stack">
        <span className="tb-pack__count">{templateCount} Templates</span>
        <div className="tb-pack__layer is-back">
          <div className="tb-pack__thumb-wrap" style={{ opacity: 0.5 }}>
            <FlowThumbnail variant={variants[2] ?? 2} />
          </div>
        </div>
        <div className="tb-pack__layer is-mid">
          <div className="tb-pack__thumb-wrap" style={{ opacity: 0.7 }}>
            <FlowThumbnail variant={variants[1] ?? 1} />
          </div>
        </div>
        <div className="tb-pack__layer is-front">
          <div className="tb-pack__thumb-wrap">
            <FlowThumbnail variant={variants[0] ?? 0} />
          </div>
        </div>
      </div>
      <p className="tb-pack__title">{name}</p>
      <p className="tb-pack__desc">{description}</p>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// BrowseByCarousel — generic horizontal-scroll row used by both
// "Browse by campaign phase" and "Browse by audience" sections.
// Each item renders as the same audience-card visual treatment so the two
// breakers feel like one family. Right-arrow control nudges the row.
// ─────────────────────────────────────────────────────────────────────────────
function BrowseByCarousel({ title, subtitle, items }) {
  const trackRef = React.useRef(null);
  const [canScrollRight, setCanScrollRight] = React.useState(false);
  const [canScrollLeft, setCanScrollLeft] = React.useState(false);

  const updateScrollState = React.useCallback(() => {
    const el = trackRef.current;
    if (!el) return;
    setCanScrollLeft(el.scrollLeft > 4);
    setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 4);
  }, []);

  React.useEffect(() => {
    updateScrollState();
    const el = trackRef.current;
    if (!el) return;
    el.addEventListener("scroll", updateScrollState, { passive: true });
    window.addEventListener("resize", updateScrollState);
    return () => {
      el.removeEventListener("scroll", updateScrollState);
      window.removeEventListener("resize", updateScrollState);
    };
  }, [updateScrollState, items]);

  const scrollBy = (dir) => {
    const el = trackRef.current;
    if (!el) return;
    // Step ≈ one card width plus gap.
    const step = Math.max(280, el.clientWidth * 0.6);
    el.scrollBy({ left: dir * step, behavior: "smooth" });
  };

  return (
    <section className="tb-breaker">
      <div className="tb-breaker__head">
        <div>
          <h3 className="tb-breaker__title">{title}</h3>
          {subtitle && <p className="tb-breaker__subtitle">{subtitle}</p>}
        </div>
        <div className="tb-breaker__nav">
          <button
            className="tb-breaker__nav-btn"
            onClick={() => scrollBy(-1)}
            disabled={!canScrollLeft}
            aria-label="Scroll left"
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <line x1="19" y1="12" x2="5" y2="12" />
              <polyline points="12 19 5 12 12 5" />
            </svg>
          </button>
          <button
            className="tb-breaker__nav-btn"
            onClick={() => scrollBy(1)}
            disabled={!canScrollRight}
            aria-label="Scroll right"
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <line x1="5" y1="12" x2="19" y2="12" />
              <polyline points="12 5 19 12 12 19" />
            </svg>
          </button>
        </div>
      </div>
      <div className="tb-breaker__track-wrap">
        <div className="tb-breaker__track" ref={trackRef}>
          {items.map((it) => (
            <button key={it.key} className="tb-aud-card tb-breaker__card" onClick={it.onClick}>
              <div className={"tb-aud-card__visual is-" + it.tone}>
                <BreakerCardVisual kind={it.kind} id={it.key} />
                {it.badge && <span className="tb-breaker__badge">{it.badge}</span>}
              </div>
              <div className="tb-aud-card__body">
                <div>
                  <p className="tb-aud-card__name">{it.label}</p>
                  <p className="tb-aud-card__count">{it.count} {it.count === 1 ? "Template" : "Templates"}</p>
                </div>
                <div className="tb-aud-card__arrow">
                  <ArrowRightIcon />
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// StarterPacksCarousel — same horizontal-scroll chrome as BrowseByCarousel
// but renders the chunky stacked-card "pack" visual. One pack per phase,
// in manifest order. Click → opens StarterPackModal with that pack's templates.
// ─────────────────────────────────────────────────────────────────────────────
function StarterPacksCarousel({ phases, templates, onOpenPack }) {
  const trackRef = React.useRef(null);
  const [canScrollRight, setCanScrollRight] = React.useState(false);
  const [canScrollLeft, setCanScrollLeft] = React.useState(false);

  const updateScrollState = React.useCallback(() => {
    const el = trackRef.current;
    if (!el) return;
    setCanScrollLeft(el.scrollLeft > 4);
    setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 4);
  }, []);

  React.useEffect(() => {
    updateScrollState();
    const el = trackRef.current;
    if (!el) return;
    el.addEventListener("scroll", updateScrollState, { passive: true });
    window.addEventListener("resize", updateScrollState);
    return () => {
      el.removeEventListener("scroll", updateScrollState);
      window.removeEventListener("resize", updateScrollState);
    };
  }, [updateScrollState]);

  const scrollBy = (dir) => {
    const el = trackRef.current;
    if (!el) return;
    const step = Math.max(300, el.clientWidth * 0.6);
    el.scrollBy({ left: dir * step, behavior: "smooth" });
  };

  // Build pack data: one pack per phase, with that phase's templates inside.
  const packs = phases.map((p) => {
    const items = templates.filter((t) => t.phase === p.id);
    return {
      name: p.label + " Pack",
      phaseId: p.id,
      description: p.packDescription || p.job,
      window: p.window,
      templates: items,
      variants: items.slice(0, 3).map((t) => Math.max(0, Math.min(5, ((t.videos || []).length || 1) - 1)))
    };
  }).filter((pk) => pk.templates.length > 0);

  return (
    <section className="tb-breaker tb-breaker--packs">
      <div className="tb-breaker__head">
        <div>
          <h3 className="tb-breaker__title">Starter packs</h3>
          <p className="tb-breaker__subtitle">Load every template for a phase in one go — your homepage, why-attend, sponsor, and more, all wired up.</p>
        </div>
        <div className="tb-breaker__nav">
          <button className="tb-breaker__nav-btn" onClick={() => scrollBy(-1)} disabled={!canScrollLeft} aria-label="Scroll left">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <line x1="19" y1="12" x2="5" y2="12" />
              <polyline points="12 19 5 12 12 5" />
            </svg>
          </button>
          <button className="tb-breaker__nav-btn" onClick={() => scrollBy(1)} disabled={!canScrollRight} aria-label="Scroll right">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <line x1="5" y1="12" x2="19" y2="12" />
              <polyline points="12 5 19 12 12 19" />
            </svg>
          </button>
        </div>
      </div>
      <div className="tb-breaker__track-wrap">
        <div className="tb-breaker__track" ref={trackRef}>
          {packs.map((pk) => (
            <div key={pk.phaseId} className="tb-pack tb-breaker__pack" onClick={() => onOpenPack(pk)}>
              <div className="tb-pack__stack">
                <span className="tb-pack__count">{pk.templates.length} Templates</span>
                <div className="tb-pack__layer is-back">
                  <div className="tb-pack__thumb-wrap" style={{ opacity: 0.5 }}>
                    <FlowThumbnail variant={pk.variants[2] ?? 2} />
                  </div>
                </div>
                <div className="tb-pack__layer is-mid">
                  <div className="tb-pack__thumb-wrap" style={{ opacity: 0.7 }}>
                    <FlowThumbnail variant={pk.variants[1] ?? 1} />
                  </div>
                </div>
                <div className="tb-pack__layer is-front">
                  <div className="tb-pack__thumb-wrap">
                    <FlowThumbnail variant={pk.variants[0] ?? 0} />
                  </div>
                </div>
              </div>
              <p className="tb-pack__title">{pk.name}</p>
              <p className="tb-pack__desc">{pk.window}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { UseCaseCard, AudienceCard, StarterPackCard, BrowseByCarousel, StarterPacksCarousel, HeartIcon, ArrowRightIcon, PhaseVisual, AudienceVisual, BreakerCardVisual });
