// modal-tier.jsx — teaser modal for a tier. Per spec it's a TEASER + CTA, not
// a content container: tier label, tagline, three stream highlight cards each
// with a one-liner + CTA into that stream's funnel. Agent mode reveals the
// deeper depth layer. Exports window.L180TierModal.

function L180TierModal({ tier, mode, lens, onClose, onPrev, onNext, prevTier, nextTier, onStream, onEdu, onService, onSchedule, onEmbed, paused }) {
  const [closing, setClosing] = React.useState(false);
  // distinct gradient hue per card (cyan → green → amber → orange → red)
  const cardHues = window.L180_BRAND.risk;
  // graceful exit: play the sink/fade, then unmount
  const requestClose = React.useCallback((after) => {
    setClosing(true);
    setTimeout(() => { (after || onClose)(); }, 280);
  }, [onClose]);

  React.useEffect(() => {
    function onKey(e) {
      if (paused) return; // a pop-up is layered on top — let it own the keyboard
      if (e.key === "Escape") requestClose();
      else if (e.key === "ArrowLeft" && onPrev) onPrev();
      else if (e.key === "ArrowRight" && onNext) onNext();
    }
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [tier, requestClose, onPrev, onNext, paused]);

  const hue = window.l180TierHue(tier.n);
  const isAgent = mode === "agent";
  const isServices = lens === "services";
  // In Services lens the tier IS a service band -> its own services (cards).
  // In Process lens -> the services related to that process tier (chip strip).
  const tierServices = isServices
    ? (window.l180BandServices ? window.l180BandServices(tier) : [])
    : (window.l180ServicesForTier ? window.l180ServicesForTier(tier.n) : []);

  // how many cards this modal renders — 5-card tiers (the routing tier) get a
  // compact layout so they fit on screen without a scroll bar
  const visibleCount = isServices
    ? tierServices.length
    : tier.streams.filter((s) => isAgent || !s.agentOnly).length;
  const compact = visibleCount >= 5;

  return (
    <div className={"l180-backdrop" + (closing ? " closing" : "")} onClick={() => requestClose()}>
      <div className={"l180-sheet" + (compact ? " l180-sheet--compact" : "")} onClick={(e) => e.stopPropagation()}
           style={{ borderTop: `2px solid ${hue}`, "--hue": hue }}>

        {/* centered top toolbar: up-tier · close · down-tier */}
        {(() => {
          const label = (t) => isServices
            ? t.name
            : <>Tier 0{t.n}<span className="l180-navbtn-name"> · {t.name}</span></>;
          return (
            <div className="l180-modaltop">
              {onNext && nextTier && (
                <button className="l180-navbtn" onClick={onNext} aria-label={`Up to ${nextTier.name}`}>
                  <span className="arr">↑</span> {label(nextTier)}
                </button>
              )}
              <button className="l180-close" onClick={() => requestClose()} aria-label="Close">✕</button>
              {onPrev && prevTier && (
                <button className="l180-navbtn" onClick={onPrev} aria-label={`Down to ${prevTier.name}`}>
                  <span className="arr">↓</span> {label(prevTier)}
                </button>
              )}
            </div>
          );
        })()}

        <div className="l180-sheet-inner">
          {/* tier image band — doubles as the intro-video slot when a tier opts in
              (set `video:` on the tier). Empty string = reserved placeholder. */}
          <div className="l180-tierimg-band">
            {tier.video !== undefined ? (
              tier.video ? (
                /youtube|vimeo/.test(tier.video)
                  ? <iframe className="l180-videoframe" src={tier.video} title="Intro video" frameBorder="0" allow="autoplay; encrypted-media; fullscreen" allowFullScreen></iframe>
                  : <video className="l180-videoframe" src={tier.video} controls playsInline></video>
              ) : (
                <div className="l180-videoplaceholder">
                  <span className="l180-videoplaceholder-icon">▶</span>
                  <span className="l180-videoplaceholder-lbl">Intro video</span>
                  <span className="l180-videoplaceholder-sub">Placeholder · video will live here</span>
                </div>
              )
            ) : (
              <>
                <image-slot id={`l180tierimg-${tier.n}`} shape="rect" placeholder={`Drop a photo for ${tier.name}`}></image-slot>
                <div className="l180-tierimg-tint" />
                <div className="l180-tierimg-fade" />
              </>
            )}
          </div>

          {/* header */}
          <div style={{ position: "relative", zIndex: 2 }}>
            <div className="l180-eyebrow" style={{ color: hue }}>
              {isServices ? `Services · 0${tier.n}` : `Tier 0${tier.n}${tier.routing ? " · The Routing Tier" : ""}`}
            </div>
            <h2 className="l180-modal-title">{tier.name}</h2>
            <div className="l180-positioning">{tier.positioning}</div>
            <p className="l180-tagline-q">“{tier.tagline}”</p>
            {tier.intro && <p className="l180-intro">{tier.intro}</p>}
          </div>

          {/* SERVICES LENS — the named services that live on this tier, as cards */}
          {isServices && (
            <>
              {tierServices.length > 0 ? (
                <div className={`l180-streams${tierServices.length === 5 ? " l180-streams--5" : tierServices.length === 4 ? " l180-streams--4" : tierServices.length === 2 ? " l180-streams--2" : ""}`}>
                  {tierServices.map((svc, i) => {
                    const ch = cardHues[i % cardHues.length];
                    return (
                      <div key={svc.key} className="l180-streamcard" style={{ "--hue": ch }}>
                        <div className="l180-streamcard-top">
                          <div className="l180-streamnum" style={{ color: "#fff", borderColor: `color-mix(in oklch, ${ch} 60%, transparent)`, background: `color-mix(in oklch, ${ch} 24%, transparent)` }}>
                            {i + 1}
                          </div>
                          <h3 className="l180-streamname">{svc.name}</h3>
                        </div>
                        <p className="l180-streamone">{svc.tagline}</p>
                        <div className="l180-depth">
                          <span className="l180-depthlabel">What it covers</span>
                          <p>{svc.blurb}</p>
                        </div>
                        <button className="l180-streamcta" style={{ "--hue": ch }}
                                onClick={() => onService && onService(svc, ch)}>
                          Learn more <span className="arr">→</span>
                        </button>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <p className="l180-intro">No standalone services map to this tier — switch to Process to see the steps here.</p>
              )}
              <p className="l180-services-note">Delivered through our {tier.name} process — switch to Process to walk the steps.</p>
            </>
          )}

          {/* stream cards — PROCESS lens (agent-only streams hidden in website mode) */}
          {!isServices && (() => {
          const visibleStreams = tier.streams.filter((s) => isAgent || !s.agentOnly);
          const countClass = visibleStreams.length === 5 ? " l180-streams--5" : visibleStreams.length === 4 ? " l180-streams--4" : visibleStreams.length === 2 ? " l180-streams--2" : "";
          return (
          <div className={`l180-streams${countClass}`}>
            {visibleStreams.map((s, i) => {
              const ch = cardHues[i % cardHues.length];
              return (
              <div key={i} className="l180-streamcard" style={{ "--hue": ch }}>
                <div className="l180-streamcard-top">
                  <div className="l180-streamnum" style={{ color: "#fff", borderColor: `color-mix(in oklch, ${ch} 60%, transparent)`, background: `color-mix(in oklch, ${ch} 24%, transparent)` }}>
                    {s.isGateway ? "★" : i + 1}
                  </div>
                  <h3 className="l180-streamname">{s.name}</h3>
                  {s.agentOnly && <span className="l180-agentonly-tag">Agent only</span>}
                </div>
                <p className="l180-streamone">{s.one}</p>

                {s.bullets && (
                  <ul className="l180-streambullets" style={{ "--hue": ch }}>
                    {s.bullets.map((b, j) => <li key={j}>{b}</li>)}
                  </ul>
                )}

                {/* depth surface — a stream can collapse to a single one-sentence
                    Purpose (website mode) instead of the Overview + Going deeper pair */}
                {!isAgent && s.purpose ? (
                  <div className="l180-depth">
                    <span className="l180-depthlabel">Purpose</span>
                    <p>{s.purpose}</p>
                  </div>
                ) : (
                  <>
                    <div className="l180-depth">
                      <span className="l180-depthlabel">{isAgent ? "Agent layer" : "Overview"}</span>
                      <p>{isAgent ? s.agent : s.website}</p>
                    </div>
                    {!isAgent && s.funnel && (
                      <div className="l180-depth">
                        <span className="l180-depthlabel">Going deeper</span>
                        <p>{s.funnel}</p>
                      </div>
                    )}
                  </>
                )}

                <button className="l180-streamcta" style={{ "--hue": ch }}
                        onClick={() => {
                          if (s.embed && onEmbed) requestClose(() => onEmbed(s.embed, s.name));
                          else if (s.funnelType === "edu" && onEdu) onEdu(s, ch);
                          else if (s.funnelType === "schedule" && onSchedule) onSchedule(s);
                          else requestClose(() => onStream(tier, s));
                        }}>
                  {s.cta} <span className="arr">→</span>
                </button>
                {s.secondary && onEdu && (
                  <button className="l180-streamcta l180-streamcta--ghost" style={{ "--hue": ch }}
                          onClick={() => onEdu(s, ch)}>
                    {s.secondary.label} <span className="arr">→</span>
                  </button>
                )}
              </div>
              );
            })}
          </div>
          );
          })()}

          {/* PROCESS lens — related services as a quiet chip strip */}
          {!isServices && tierServices.length > 0 && (
            <div className="l180-servicechips" style={{ "--hue": hue }}>
              <span className="l180-depthlabel" style={{ marginRight: 2 }}>Related services</span>
              {tierServices.map((svc) => (
                <button key={svc.key} className="l180-servicechip" style={{ "--hue": hue }}
                        onClick={() => onService && onService(svc, hue)}>
                  {svc.name}
                </button>
              ))}
            </div>
          )}

          <div className="l180-sheet-foot">
            <span>{isServices
              ? `These are the LIFE180 services delivered in ${tier.name}. Click any card for details, or switch to Process to see the steps.`
              : isAgent
              ? "Agent view — deeper talking points shown. Each button opens the guided walkthrough you do together."
              : "Each option opens a short guided walkthrough. Switch to Agent view for the deeper talking points."}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

window.L180TierModal = L180TierModal;
