/* ============================================================
 * CRM Personalization Moment, v2
 * No lifestyle photo. Pure editorial: an AI-composed WhatsApp
 * message on the left, the CRM record that produced it on the
 * right, with tokens lighting up as the message types out.
 * Proves that the CRM is the runtime source of every word.
 * ============================================================ */

const { useState: useStateP2, useEffect: useEffectP2 } = React;

function CrmPersonalizationMomentV2() {
  const tokens = [
    { k: "first_name", v: "Aoife",            from: "Profile",                tag: "core" },
    { k: "language",   v: "EN",               from: "Profile",                tag: "core" },
    { k: "property",   v: "Reverence Mare",   from: "Reservation #247887",    tag: "reservation" },
    { k: "checkin",    v: "Thursday",         from: "Reservation #247887",    tag: "reservation" },
    { k: "diet",       v: "vegetarian",       from: "Memory · stay 2024",     tag: "memory" },
    { k: "pet",        v: "Frankie",          from: "Memory · this stay",     tag: "memory" },
    { k: "tier",       v: "Gold",             from: "Loyalty",                tag: "loyalty" },
  ];

  const script = [
    { type: "text", v: "Hi " },
    { type: "tok",  k: "first_name" },
    { type: "text", v: ", we're getting your stay at " },
    { type: "tok",  k: "property" },
    { type: "text", v: " ready for " },
    { type: "tok",  k: "checkin" },
    { type: "text", v: ". I've noted you're " },
    { type: "tok",  k: "diet" },
    { type: "text", v: ", so the kitchen will adjust the welcome plate. And " },
    { type: "tok",  k: "pet" },
    { type: "text", v: " will have a water bowl and a small bed in the room. Your " },
    { type: "tok",  k: "tier" },
    { type: "text", v: " tier upgrade is also confirmed." },
  ];

  const fullLen = script.reduce((acc, s) => acc + (s.type === "text" ? s.v.length : 8), 0);

  const [progress, setProgress] = useStateP2(0);
  const [activeToken, setActiveToken] = useStateP2(null);
  const [usedTokens, setUsedTokens] = useStateP2(new Set());

  useEffectP2(() => {
    let raf;
    let start = null;
    const duration = 10000;
    const tick = (t) => {
      if (start === null) start = t;
      const elapsed = (t - start) % (duration + 1800);
      const p = Math.min(elapsed / duration, 1);
      setProgress(p);

      let acc = 0;
      let curTok = null;
      const consumed = new Set();
      const charProgress = p * fullLen;
      for (const seg of script) {
        const segLen = seg.type === "text" ? seg.v.length : 8;
        if (acc + segLen > charProgress && seg.type === "tok" && acc <= charProgress) {
          curTok = seg.k;
          break;
        }
        if (seg.type === "tok" && acc + segLen <= charProgress) {
          consumed.add(seg.k);
        }
        acc += segLen;
      }
      setActiveToken(curTok);
      setUsedTokens(consumed);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const renderTyped = () => {
    const charProgress = progress * fullLen;
    let acc = 0;
    const out = [];
    for (let i = 0; i < script.length; i++) {
      const seg = script[i];
      const segLen = seg.type === "text" ? seg.v.length : 8;
      if (acc >= charProgress) break;
      const segProgress = Math.max(0, Math.min(1, (charProgress - acc) / segLen));
      if (seg.type === "text") {
        const visible = seg.v.slice(0, Math.ceil(seg.v.length * segProgress));
        out.push(<span key={i}>{visible}</span>);
      } else {
        const t = tokens.find(t => t.k === seg.k);
        if (segProgress >= 1) {
          out.push(<span key={i} className="cpm2-tok cpm2-tok-done">{t.v}</span>);
        } else {
          out.push(
            <span key={i} className="cpm2-tok cpm2-tok-fill">
              <span className="cpm2-tok-l">{t.v}</span>
              <span className="cpm2-tok-bar" style={{ width: `${segProgress * 100}%` }} />
            </span>
          );
        }
      }
      acc += segLen;
    }
    out.push(<span key="cur" className="cpm2-cursor" />);
    return out;
  };

  return (
    <div className="cpm2">
      {/* === LEFT: composed message, life-size === */}
      <div className="cpm2-msg">
        <div className="cpm2-msg-head">
          <div className="cpm2-msg-channel">
            <span className="cpm2-msg-channel-dot" />
            WhatsApp · outbound
          </div>
          <div className="cpm2-msg-meta">
            composed at runtime · 42ms
          </div>
        </div>

        <div className="cpm2-msg-thread">
          <div className="cpm2-msg-stamp">today, 14:02</div>
          <div className="cpm2-msg-bubble">
            <div className="cpm2-msg-from">
              <span className="cpm2-msg-avatar">RM</span>
              <span>
                <div className="cpm2-msg-from-name">Reverence Mare · AI Concierge</div>
                <div className="cpm2-msg-from-sub">to Aoife Daly · +353 87 ••• ••</div>
              </span>
            </div>
            <div className="cpm2-msg-text">
              {renderTyped()}
            </div>
            <div className="cpm2-msg-foot">
              <span className="cpm2-msg-foot-l">delivered · 14:02</span>
              <span className="cpm2-msg-foot-r">read 14:03</span>
            </div>
          </div>
        </div>

        <div className="cpm2-msg-explain">
          Every variable in this message was resolved against Aoife's CRM record at the moment of send.
          Profile, reservation, memory, loyalty, all in one query.
        </div>
      </div>

      {/* === RIGHT: CRM record === */}
      <div className="cpm2-rec">
        <div className="cpm2-rec-head">
          <div className="cpm2-rec-head-l">CRM record · runtime read</div>
          <div className="cpm2-rec-head-r">Aoife Daly · ID 1024</div>
        </div>
        <div className="cpm2-rec-rows">
          {tokens.map((t, i) => {
            const used = usedTokens.has(t.k);
            const active = activeToken === t.k;
            return (
              <div
                key={i}
                className={`cpm2-rec-row ${active ? "active" : ""} ${used ? "used" : ""}`}
              >
                <div className="cpm2-rec-k">{`{{${t.k}}}`}</div>
                <div className="cpm2-rec-v">{t.v}</div>
                <div className="cpm2-rec-from">{t.from}</div>
                <div className="cpm2-rec-pulse" />
              </div>
            );
          })}
        </div>
        <div className="cpm2-rec-foot">
          <span>Resolved in a single CRM read</span>
          <span className="cpm2-rec-foot-r">0 PII leaked · audit logged</span>
        </div>
      </div>

      <style>{`
        .cpm2 {
          display: grid;
          grid-template-columns: 1.15fr 1fr;
          gap: 0;
          background: #0E0D0C;
          border: 1px solid var(--hairline);
          border-radius: 18px;
          overflow: hidden;
          color: #F5F1EA;
          --cpm2-ink: #F5F1EA;
          --cpm2-ink-2: #C9C2B6;
          --cpm2-ink-3: #8B857C;
          --cpm2-line: rgba(245, 241, 234, 0.10);
          --cpm2-accent: #FF3D88;
        }
        @media (max-width: 980px) { .cpm2 { grid-template-columns: 1fr; } }

        /* ===== LEFT: message ===== */
        .cpm2-msg {
          padding: 36px 38px 30px;
          border-right: 1px solid var(--cpm2-line);
          background:
            radial-gradient(ellipse 600px 300px at 30% 10%, rgba(255, 61, 136, 0.08), transparent 60%),
            #0E0D0C;
          display: flex; flex-direction: column;
        }
        @media (max-width: 980px) {
          .cpm2-msg { border-right: 0; border-bottom: 1px solid var(--cpm2-line); padding: 28px 24px; }
        }
        .cpm2-msg-head {
          display: flex; justify-content: space-between; align-items: center;
          margin-bottom: 26px;
        }
        .cpm2-msg-channel {
          display: inline-flex; align-items: center; gap: 8px;
          font-family: var(--f-mono); font-size: 11px;
          color: var(--cpm2-ink-2);
          letter-spacing: 0.06em; text-transform: uppercase;
        }
        .cpm2-msg-channel-dot {
          width: 6px; height: 6px; border-radius: 50%;
          background: var(--c-whatsapp);
          box-shadow: 0 0 8px #25D366;
        }
        .cpm2-msg-meta {
          font-family: var(--f-mono); font-size: 10.5px;
          color: var(--cpm2-ink-3);
          letter-spacing: 0.04em;
        }

        .cpm2-msg-thread {
          flex: 1;
          display: flex; flex-direction: column; align-items: flex-start;
          gap: 10px;
        }
        .cpm2-msg-stamp {
          align-self: center;
          font-family: var(--f-mono); font-size: 10.5px;
          color: var(--cpm2-ink-3);
          letter-spacing: 0.06em;
        }
        .cpm2-msg-bubble {
          background: #1B1A18;
          border: 1px solid var(--cpm2-line);
          border-radius: 16px 16px 16px 4px;
          padding: 18px 20px 14px;
          width: 100%;
          max-width: 540px;
          box-shadow: 0 18px 40px -20px rgba(0,0,0,0.6);
        }
        .cpm2-msg-from {
          display: flex; align-items: center; gap: 12px;
          padding-bottom: 12px; margin-bottom: 12px;
          border-bottom: 1px solid var(--cpm2-line);
        }
        .cpm2-msg-avatar {
          width: 32px; height: 32px; border-radius: 50%;
          background: linear-gradient(135deg, var(--cpm2-accent), #C9255E);
          color: #fff;
          display: grid; place-items: center;
          font-family: var(--f-display); font-size: 12px; font-weight: 400;
          letter-spacing: 0.02em;
          flex-shrink: 0;
        }
        .cpm2-msg-from-name {
          font-size: 13px; color: var(--cpm2-ink); font-weight: 500;
        }
        .cpm2-msg-from-sub {
          font-family: var(--f-mono); font-size: 10.5px;
          color: var(--cpm2-ink-3);
          letter-spacing: 0.02em;
          margin-top: 2px;
        }
        .cpm2-msg-text {
          font-size: 16.5px;
          line-height: 1.6;
          color: var(--cpm2-ink);
          letter-spacing: 0.005em;
          min-height: 130px;
          word-spacing: 0.02em;
        }
        .cpm2-msg-foot {
          display: flex; justify-content: space-between;
          margin-top: 14px;
          font-family: var(--f-mono); font-size: 10.5px;
          color: var(--cpm2-ink-3);
          letter-spacing: 0.04em;
        }

        /* tokens */
        .cpm2-tok {
          display: inline-block;
          padding: 1px 6px;
          margin: 0 1px;
          border-radius: 4px;
          position: relative;
          font-weight: 500;
        }
        .cpm2-tok-done {
          background: color-mix(in srgb, var(--cpm2-accent) 15%, transparent);
          color: #FF93B5;
        }
        .cpm2-tok-fill {
          background: color-mix(in srgb, var(--cpm2-accent) 10%, transparent);
          color: var(--cpm2-ink);
          overflow: hidden;
        }
        .cpm2-tok-l {
          position: relative; z-index: 1;
        }
        .cpm2-tok-bar {
          position: absolute; left: 0; top: 0; bottom: 0;
          background: color-mix(in srgb, var(--cpm2-accent) 30%, transparent);
          z-index: 0;
        }
        .cpm2-cursor {
          display: inline-block;
          width: 2px; height: 1.05em;
          margin-left: 1px;
          background: var(--cpm2-accent);
          vertical-align: text-bottom;
          animation: cpm2-blink 0.9s steps(2, jump-none) infinite;
        }
        @keyframes cpm2-blink {
          0%, 50% { opacity: 1; }
          50.01%, 100% { opacity: 0; }
        }

        .cpm2-msg-explain {
          margin-top: 28px;
          padding-top: 20px;
          border-top: 1px solid var(--cpm2-line);
          font-size: 13px; line-height: 1.6;
          color: var(--cpm2-ink-3);
          max-width: 480px;
        }

        /* ===== RIGHT: record ===== */
        .cpm2-rec {
          display: flex; flex-direction: column;
          background: #0E0D0C;
        }
        .cpm2-rec-head {
          display: flex; justify-content: space-between;
          padding: 18px 24px;
          border-bottom: 1px solid var(--cpm2-line);
          font-family: var(--f-mono); font-size: 10.5px;
          letter-spacing: 0.06em; text-transform: uppercase;
        }
        .cpm2-rec-head-l { color: var(--cpm2-accent); }
        .cpm2-rec-head-r { color: var(--cpm2-ink-3); }

        .cpm2-rec-rows { flex: 1; padding: 8px 0; }
        .cpm2-rec-row {
          position: relative;
          display: grid;
          grid-template-columns: 1.1fr 1fr 1.1fr;
          gap: 16px;
          padding: 12px 24px;
          border-bottom: 1px solid var(--cpm2-line);
          transition: background .25s ease;
        }
        .cpm2-rec-row:last-child { border-bottom: 0; }
        .cpm2-rec-row.used { opacity: 0.55; }
        .cpm2-rec-row.active {
          background: color-mix(in srgb, var(--cpm2-accent) 8%, transparent);
          opacity: 1;
        }
        .cpm2-rec-row.active .cpm2-rec-pulse {
          opacity: 1;
        }
        .cpm2-rec-pulse {
          position: absolute; left: 0; top: 0; bottom: 0;
          width: 3px;
          background: var(--cpm2-accent);
          opacity: 0;
          transition: opacity .2s ease;
        }
        .cpm2-rec-k {
          font-family: var(--f-mono); font-size: 12px;
          color: var(--cpm2-ink-3);
          letter-spacing: 0.02em;
        }
        .cpm2-rec-row.active .cpm2-rec-k,
        .cpm2-rec-row.used .cpm2-rec-k {
          color: var(--cpm2-accent);
        }
        .cpm2-rec-v {
          font-size: 14px; color: var(--cpm2-ink); font-weight: 500;
        }
        .cpm2-rec-from {
          font-family: var(--f-mono); font-size: 10.5px;
          color: var(--cpm2-ink-3);
          letter-spacing: 0.02em;
          text-align: right;
        }
        .cpm2-rec-foot {
          display: flex; justify-content: space-between;
          padding: 16px 24px;
          border-top: 1px solid var(--cpm2-line);
          font-family: var(--f-mono); font-size: 10.5px;
          color: var(--cpm2-ink-3);
          letter-spacing: 0.04em;
        }
        .cpm2-rec-foot-r { color: #4ADE80; }

        @media (max-width: 600px) {
          .cpm2-rec-row { grid-template-columns: 1fr 1fr; }
          .cpm2-rec-from { grid-column: 1 / -1; text-align: left; }
        }
      `}</style>
    </div>
  );
}

window.CrmPersonalizationMomentV2 = CrmPersonalizationMomentV2;
