/* The Pulse — newsletter preview (this renders the exported email). */
(function () {
  const I = window.PulseIcons;
  const PulseLine = window.PulseLine;
  const FauxQR = window.FauxQR;

  function Kicker({ num, ico, title }) {
    const Ico = ico;
    return (
      <div className="pm-kicker">
        {num && <span className="num">{num}</span>}
        {Ico && <span className="ico"><Ico size={15} /></span>}
        <span className="ttl">{title}</span>
        <span className="rule" />
      </div>
    );
  }

  /* ---------------- MASTHEADS ---------------- */
  function Masthead({ meta }) {
    const issue = `Issue ${meta.issueNo} · ${meta.month} ${meta.year}`;
    const word = (
      <React.Fragment>The <em>Pulse</em></React.Fragment>
    );
    if (meta.masthead === "banner") {
      return (
        <div className="mh-bn">
          <div className="mh-bn-top">
            <span className="mh-bn-brand">{meta.brand}</span>
            <span className="mh-bn-issue">{issue}</span>
          </div>
          <div className="mh-bn-body">
            <div>
              <div className="mh-bn-word">{word}</div>
              <div className="mh-bn-tag">{meta.tagline}</div>
            </div>
            <div className="mh-bn-badge">
              <span className="m">{meta.month}</span>
              <span className="y">{meta.year}</span>
            </div>
          </div>
          <PulseLine color="#00B7BD" height={22} stroke={2.4} />
        </div>
      );
    }
    if (meta.masthead === "gradient") {
      return (
        <div className="mh-gr">
          <div className="mh-gr-top">
            <span className="mh-gr-brand">{meta.brand}</span>
            <span className="mh-gr-issue">{issue}</span>
          </div>
          <div className="mh-gr-body">
            <span className="mh-gr-chip">{meta.month} {meta.year}</span>
            <div className="mh-gr-word">{word}</div>
            <div className="mh-gr-tag">{meta.tagline}</div>
          </div>
          <PulseLine color="rgba(255,255,255,.6)" height={26} stroke={2.6} />
        </div>
      );
    }
    // editorial (default)
    return (
      <div className="mh-ed">
        <div className="mh-ed-top">
          <span className="mh-ed-brand">{meta.brand}</span>
          <span className="mh-ed-issue">{issue}</span>
        </div>
        <div className="mh-ed-rule" />
        <div className="mh-ed-word">{word}</div>
        <div className="mh-ed-tag">{meta.tagline}</div>
        <PulseLine color="#00B7BD" height={22} stroke={2.4} />
      </div>
    );
  }

  /* ---------------- SECTIONS ---------------- */
  function Welcome({ d, num }) {
    return (
      <div className="pm-sec">
        <Kicker num={num} ico={I.Heart} title="A Note to Start" />
        <div className="pm-welcome">
          {d.photo
            ? <img className="pm-avatar-img av-ring-teal" src={d.photo} alt="" />
            : <div className="pm-avatar av-teal">{d.initials}</div>}
          <div style={{ flex: 1, minWidth: 0 }}>
            <p className="w-body">{d.body}</p>
            <div className="w-sign">
              <b>{d.name}</b>
              <span>{d.role}</span>
            </div>
          </div>
        </div>
      </div>
    );
  }

  function Featured({ d, num }) {
    const meta = [
      { ic: I.Calendar, t: d.date },
      { ic: I.Pin, t: d.location },
      { ic: I.Run, t: d.paces }
    ].filter((r) => r.t);
    const showQr = d.showQr !== false;
    const qrSrc = (window.pulseQR && d.qrUrl) ? window.pulseQR(d.qrUrl, 6) : null;
    return (
      <div className="pm-feat">
        <Kicker num={num} title="Featured Event" />
        {d.image && <img className="feat-hero" src={d.image} alt="" />}
        <div className={"feat-grid" + (showQr ? "" : " no-qr")}>
          <div className="feat-main">
            {d.kicker && <span className="feat-chip"><I.Sparkle size={12} />{d.kicker}</span>}
            <h2 className="feat-title">{d.title}</h2>
            <div className="feat-meta">
              {meta.map((r, i) => {
                const Ic = r.ic;
                return (
                  <div className="row" key={i}>
                    <span className="ic"><Ic size={16} /></span>{r.t}
                  </div>
                );
              })}
            </div>
            <p className="feat-desc">{d.description}</p>
            {d.friend && (
              <div className="feat-friend">
                <span className="ic"><I.People size={16} /></span>{d.friend}
              </div>
            )}
          </div>
          {showQr && (
            <div className="feat-qr">
              <div className="feat-qr-frame">
                {qrSrc
                  ? <img src={qrSrc} alt="QR code" width="116" height="116" style={{ display: "block", borderRadius: 4, imageRendering: "pixelated" }} />
                  : <FauxQR fg="#004860" size={116} />}
                <div className="feat-qr-cap">{d.qrCaption}</div>
              </div>
              {d.qrUrl && <div className="feat-qr-url">{d.qrUrl}</div>}
            </div>
          )}
        </div>
      </div>
    );
  }

  function Recap({ d, num }) {
    return (
      <div className="pm-sec">
        <Kicker num={num} ico={I.Mic} title="Event Recap" />
        {d.eventTag && <span className="rc-tag">{d.eventTag}</span>}
        <div className="rc-person">
          {d.speakerPhoto
            ? <img className="pm-avatar-img av-ring-teal" src={d.speakerPhoto} alt="" />
            : <div className="pm-avatar av-teal">{d.initials}</div>}
          <div>
            <h4>{d.name}</h4>
            <p>{d.role}</p>
          </div>
        </div>
        {d.photo && <img className={"pm-photo size-" + (d.photoSize || "full")} src={d.photo} alt="" />}
        {(d.paras || []).map((p, i) => <p className="pm-para" key={i}>{p}</p>)}
        {d.quote && (
          <blockquote className="pm-quote">
            <p>“{d.quote}”</p>
            {d.quoteBy && <cite>— {d.quoteBy}</cite>}
          </blockquote>
        )}
        {(d.takeaways || []).length > 0 && (
          <div className="rc-takeaways">
            {d.takeaways.map((t, i) => <span className="rc-pill" key={i}>{t}</span>)}
          </div>
        )}
      </div>
    );
  }

  function Spotlight({ d, num }) {
    const layout = d.photo ? (d.photoLayout || "inline") : "inline";
    const side = layout === "left" || layout === "right";
    const valueChip = d.value && <span className="sp-value"><I.Sparkle size={12} />KH Value · {d.value}</span>;
    const quote = d.quote && (
      <blockquote className="pm-quote">
        <p>“{d.quote}”</p>
        {d.quoteBy && <cite>— {d.quoteBy}</cite>}
      </blockquote>
    );
    const paras = (d.paras || []).map((p, i) => <p className="pm-para" key={i}>{p}</p>);
    return (
      <div className="pm-sec pm-spot">
        <Kicker num={num} ico={I.Star} title="YP Spotlight" />
        {side ? (
          <div className={"sp-split sp-" + layout}>
            <img className="sp-photo" src={d.photo} alt="" />
            <div className="sp-split-body">
              <div className="sp-id">
                <h4>{d.name}</h4>
                <p>{d.role}</p>
              </div>
              {valueChip}
              {paras}
              {quote}
            </div>
          </div>
        ) : (
          <React.Fragment>
            <div className="sp-top">
              {d.photo
                ? <img className="pm-avatar-img av-ring-purple" src={d.photo} alt="" />
                : <div className="pm-avatar av-purple">{d.initials}</div>}
              <div>
                <h4>{d.name}</h4>
                <p>{d.role}</p>
              </div>
            </div>
            {valueChip}
            {paras}
            {quote}
          </React.Fragment>
        )}
        {d.nominate && (
          <div className="sp-nominate">
            <span className="ic"><I.Star size={20} /></span>
            <p>{d.nominate}</p>
          </div>
        )}
      </div>
    );
  }

  const TAGCLASS = { Wellness: "tg-wellness", Social: "tg-social", Develop: "tg-develop", Serve: "tg-serve" };

  function Upcoming({ d, num }) {
    return (
      <div className="pm-sec">
        <Kicker num={num} ico={I.List} title="Upcoming Events" />
        {d.intro && <p className="up-intro">{d.intro}</p>}
        <div className="up-list">
          {(d.items || []).map((it, i) => (
            <div className="up-item" key={i}>
              <div className="up-date">
                <div className="d">{it.day}</div>
                <div className="m">{it.mon}</div>
              </div>
              <div className="up-info">
                <h4>{it.title}</h4>
                <p><span className="ic"><I.Clock size={13} /></span>{it.meta}</p>
              </div>
              {it.tag && <span className={"up-tag " + (TAGCLASS[it.tag] || "tg-default")}>{it.tag}</span>}
            </div>
          ))}
        </div>
      </div>
    );
  }

  const CMICON = { run: I.Run, book: I.Book, hands: I.Hands, tree: I.Tree, people: I.People, heart: I.Heart };
  const CMCOLOR = { run: "#FF6A14", book: "#8C30F5", hands: "#1f8a5b", tree: "#00778B", people: "#00B7BD", heart: "#CB2C30" };

  function Community({ d, num }) {
    return (
      <div className="pm-sec">
        <Kicker num={num} ico={I.People} title="Community Corner" />
        {d.intro && <p className="cm-intro">{d.intro}</p>}
        <div className="cm-list">
          {(d.items || []).map((it, i) => {
            const Ic = CMICON[it.icon] || I.Heart;
            const col = CMCOLOR[it.icon] || "#00778B";
            return (
              <div className="cm-item" key={i}>
                <div className="cm-ico" style={{ background: col }}><Ic size={20} /></div>
                <div className="cm-body">
                  {it.category && <div className="cm-cat" style={{ color: col }}>{it.category}</div>}
                  <h4>{it.title}</h4>
                  <p className="desc">{it.desc}</p>
                  {it.where && <div className="cm-where"><span className="ic"><I.Pin size={13} /></span>{it.where}</div>}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  function Footer({ d }) {
    return (
      <div className="pm-foot">
        <div className="pm-foot-line">
          <div>
            <div className="pm-foot-brand">Kettering Health <em>Young Professionals</em></div>
            <div className="pm-foot-sub">The Pulse · Monthly Newsletter<br />{d.audience}</div>
          </div>
          <div className="pm-foot-contact">
            <a href={"mailto:" + d.contactEmail}>{d.contactEmail}</a>
            <p>{d.involve}</p>
          </div>
        </div>
        <hr className="pm-foot-div" />
        <div className="pm-foot-fine">
          You're receiving this as part of the Kettering Health Young Professionals community.
        </div>
      </div>
    );
  }

  /* ---------------- ROOT ---------------- */
  const SECTIONS = {
    welcome: Welcome,
    featured: Featured,
    recap: Recap,
    spotlight: Spotlight,
    upcoming: Upcoming,
    community: Community
  };
  const DEFAULT_ORDER = ["welcome", "featured", "recap", "spotlight", "upcoming", "community"];

  function Newsletter({ content }) {
    const c = content;
    const CustomSection = window.PulseCustomSection;
    const isCustom = (k) => c[k] && c[k].type === "custom";
    const customKeys = Object.keys(c).filter(isCustom);
    const order = (c.sectionOrder || DEFAULT_ORDER).filter((k) => SECTIONS[k] || isCustom(k));
    DEFAULT_ORDER.forEach((k) => { if (order.indexOf(k) === -1) order.push(k); });
    customKeys.forEach((k) => { if (order.indexOf(k) === -1) order.push(k); });
    // running number for enabled body sections, in display order
    let n = 0;
    const num = () => String(++n).padStart(2, "0");
    return (
      <div className="pmail-wrap">
        <div className="pmail" id="pulse-email">
          <Masthead meta={c.meta} />
          {order.map((key) => {
            const d = c[key];
            if (!d || !d.enabled) return null;
            if (isCustom(key)) return <CustomSection key={key} d={d} num={num()} />;
            const Sec = SECTIONS[key];
            if (!Sec) return null;
            return <Sec key={key} d={d} num={num()} />;
          })}
          <Footer d={c.footer} />
        </div>
      </div>
    );
  }

  window.PulseNewsletter = Newsletter;
})();
