// ──────────────────────────────────────────────────────────────
// ContextualPhone — phone illustration for the homepage
// "The Right Experience" section. The phone displays a generic
// piece of content; three attribute chips overlap its edges
// (language, location, date) to convey that the content adapts to
// those signals — they are representations, not tappable UI.
// At rest it sits settled; on hover the phone lifts, the chips
// pop back in (staggered), and a light sweeps across the screen —
// mirroring the 2nd section's dashboard visual.
// ──────────────────────────────────────────────────────────────
const { useEffect: useCPEffect, useState: useCPState, useRef: useCPRef } = React;

const CP_BLUE = "#2F3886";
const CP_BLUE2 = "#6976E7";
const CP_AMBER = "#FFB855";
const CP_AMBER2 = "#F2A030";
const CP_INK = "#1C2250";
const CP_PANEL = "#F6F7FE";
const CP_LINE = "#E6E8F7";

/* A floating attribute chip with its own soft shadow + a hover tooltip.
   `icon` is drawn in an 84×84 box; `label` is an array of tooltip lines. */
function CPChip({ cx, cy, color, icon, idx, label }) {
  cx = +cx; cy = +cy;
  const s = 84, r = s / 2;
  const k = 0.94; // overall chip scale (square + icon shrink together)
  // Line 0 is always the small "Adapt Content by" eyebrow; line 1 is the
  // larger, bolder descriptor that follows.
  const lines = label || [];
  const eyebrow = lines[0] || "";
  const descriptor = lines[1] || "";
  const w0 = eyebrow.length * 5.9;
  const w1 = descriptor.length * 7.6;
  const tw = Math.max(108, Math.max(w0, w1) + 28);
  const th = lines.length > 0 ? 48 : 0;
  const chipHalf = r * k;
  const ty = cy - chipHalf - 12 - th; // tooltip sits above the chip
  const tx = cx - tw / 2;
  return (
    <g className="ts-cp-chipwrap"
       onClick={(e) => {
         e.stopPropagation();
         const el = e.currentTarget;
         el.classList.toggle("is-tapped");
         setTimeout(() => el.classList.remove("is-tapped"), 3000);
       }}>
      <g className="ts-cp-chip" style={{ animationDelay: (idx * 110) + "ms" }}>
        <g transform={`translate(${cx} ${cy}) scale(${k}) translate(${-cx} ${-cy})`}>
          <g filter="url(#cpChipShadow)">
            <rect x={cx - r} y={cy - r} width={s} height={s} rx="23" fill={color} />
          </g>
          {/* icons authored full-size in an 84×84 box; scaled within the square */}
          <g transform={`translate(${cx} ${cy}) scale(0.88) translate(${-r} ${-r})`}>
            <g className="ts-cp-iconwiggle">{icon}</g>
          </g>
        </g>
      </g>
      {lines.length > 0 &&
        <g className="ts-cp-tip">
          <rect x={tx} y={ty} width={tw} height={th} rx="9" fill={CP_INK} />
          <path d={`M${cx - 7} ${ty + th} H${cx + 7} L${cx} ${ty + th + 8} Z`} fill={CP_INK} />
          <text x={cx} y={ty + 17} textAnchor="middle"
                fontSize="10" fontWeight="500" fill="rgba(255,255,255,0.78)"
                letterSpacing="0.02em" fontFamily="Montserrat">{eyebrow}</text>
          <text x={cx} y={ty + 36} textAnchor="middle"
                fontSize="13.5" fontWeight="800" fill="#fff"
                fontFamily="Montserrat">{descriptor}</text>
        </g>}
    </g>
  );
}

function ContextualPhone() {
  // A counter bumped on every hover. Used as a React key on the animated
  // groups so they remount and the CSS build restarts reliably each time.
  const [runId, setRunId] = useCPState(0);
  const wrapRef = useCPRef(null);

  // Sequential icon wiggle: fire one icon at a time (1.5s apart, looping),
  // each as a single finite animation that removes itself when done. No
  // animation runs at rest, so the icons stay crisp.
  useCPEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap) return;
    if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    let i = 0;
    const fire = () => {
      const icons = wrap.querySelectorAll(".ts-cp-iconwiggle");
      if (!icons.length) return;
      const el = icons[i % icons.length];
      i += 1;
      if (!el) return;
      el.classList.remove("is-wiggling");
      // reflow so the animation restarts even if re-added quickly
      void el.getBoundingClientRect();
      el.classList.add("is-wiggling");
      const done = () => { el.classList.remove("is-wiggling"); el.removeEventListener("animationend", done); };
      el.addEventListener("animationend", done);
    };
    const id = setInterval(fire, 1500);
    const kick = setTimeout(fire, 400);
    return () => { clearInterval(id); clearTimeout(kick); };
  }, []);

  useCPEffect(() => {
    if (document.getElementById("ts-contextual-phone-css")) return;
    const s = document.createElement("style");
    s.id = "ts-contextual-phone-css";
    s.textContent = `
      .ts-cp {
        position: relative; width: 100%; max-width: 460px; margin: 0 auto;
        display: flex; justify-content: center; cursor: pointer;
      }
      .ts-cp svg { display: block; width: 86%; height: auto; overflow: visible; }

      .ts-cp-device {
        transition: transform 340ms cubic-bezier(0.2,0.8,0.2,1);
        transform-box: fill-box; transform-origin: center;
      }
      .ts-cp:hover .ts-cp-device { transform: translateY(-6px); }

      .ts-cp-chip { transform-box: fill-box; transform-origin: center; }
      .ts-cp.is-live .ts-cp-chip {
        animation: cpPop 0.62s cubic-bezier(0.34,1.56,0.64,1) both;
      }

      .ts-cp-tip { opacity: 0; transition: opacity 160ms ease; pointer-events: none; }
      .ts-cp-chipwrap:hover .ts-cp-tip,
      .ts-cp-chipwrap.is-tapped .ts-cp-tip { opacity: 1; }
      .ts-cp-chipwrap { cursor: pointer; }

      /* Sequential icon wiggle — mirrors the CTA logo badge. Driven by JS
         (one finite run at a time via .is-wiggling) so that AT REST there is
         no running animation and the icon renders as a crisp vector instead
         of a cached, blurry composited bitmap. */
      .ts-cp-iconwiggle {
        transform-box: fill-box; transform-origin: 50% 50%;
      }
      .ts-cp-iconwiggle.is-wiggling {
        animation: cpIconWiggle 0.7s ease-in-out 1 both;
      }
      @keyframes cpIconWiggle {
        0%   { transform: rotate(0deg) scale(1); }
        15%  { transform: rotate(-8deg) scale(1.04); }
        35%  { transform: rotate(7deg)  scale(1.04); }
        55%  { transform: rotate(-5deg) scale(1.03); }
        75%  { transform: rotate(3deg)  scale(1.02); }
        100% { transform: rotate(0deg)  scale(1); }
      }
      @keyframes cpPop {
        0%   { opacity: 0; transform: scale(0.35) rotate(-10deg); }
        60%  { opacity: 1; }
        100% { opacity: 1; transform: scale(1) rotate(0); }
      }

      .ts-cp-sweep { transform-box: fill-box; transform-origin: center; opacity: 0; }
      .ts-cp.is-live .ts-cp-sweep { animation: cpSweep 0.95s ease-in-out both; }
      @keyframes cpSweep {
        0%   { opacity: 0; transform: translateX(-150px) skewX(-12deg); }
        25%  { opacity: 0.75; }
        100% { opacity: 0; transform: translateX(150px) skewX(-12deg); }
      }

      @media (prefers-reduced-motion: reduce) {
        .ts-cp-chip, .ts-cp-sweep, .ts-cp-device, .ts-cp-iconwiggle { animation: none !important; transition: none !important; }
      }
    `;
    document.head.appendChild(s);
  }, []);

  // Re-trigger the build on every hover.
  const replay = () => setRunId((n) => n + 1);
  const live = runId > 0;

  // Also play the build when the card scrolls into view (re-fires each time
  // it re-enters) — mirrors the 2nd section's dashboard visual so the phone
  // fully runs its chip-pop + sweep on page load, not only on hover.
  useCPEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap) return;
    if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) replay(); });
    }, { threshold: 0.4 });
    io.observe(wrap);
    return () => io.disconnect();
  }, []);

  // Language (uploaded) — navy on gold.
  const langIcon = (
    <g transform="translate(42 42) scale(2.3) translate(-12 -12)" fill="#fff">
      <path d="M19.9999 2H9.33325V5.33333H10.6666V3.33333H19.9999C20.3999 3.33333 20.6666 3.6 20.6666 4V11.3333C20.6666 11.7333 20.3999 12 19.9999 12H11.3333V16.6667H7.79992L5.33325 18.6V16.6667H3.33325C2.93325 16.6667 2.66659 16.4 2.66659 16V8.66667C2.66659 8.26667 2.93325 8 3.33325 8H11.9999V6.66667H3.33325C2.19992 6.66667 1.33325 7.53333 1.33325 8.66667V16C1.33325 17.1333 2.19992 18 3.33325 18H3.99992V21.4L8.19992 18H12.6666V13.3333H19.9999C21.1333 13.3333 21.9999 12.4667 21.9999 11.3333V4C21.9999 2.86667 21.1333 2 19.9999 2Z" />
      <path d="M4.13354 15.2666H5.73355L6.13354 14.1999H8.20021L8.60021 15.2666H10.2002L7.93354 9.33325H6.33355L4.13354 15.2666ZM7.13355 10.9999L7.80021 13.0666H6.46688L7.13355 10.9999Z" />
      <path d="M13.3333 11.3333C14.0666 11.3333 15.0666 11.1333 15.9999 10.6667C16.9333 11.1333 17.9999 11.3333 18.6666 11.3333V10C18.6666 10 17.9999 10 17.2666 9.73333C18.0666 8.93333 18.6666 7.73333 18.6666 6V5.33333H16.6666V4H15.3333V5.33333H13.3333V6.66667H17.2666C17.1333 7.86667 16.5999 8.6 15.9999 9.06667C15.5999 8.73333 15.1999 8.26667 14.9333 7.66667H13.5333C13.7999 8.53333 14.1999 9.2 14.7333 9.73333C14.0666 10 13.4666 10 13.3333 10V11.3333Z" />
    </g>
  );

  // Map pin (uploaded) — navy on light blue.
  const pinIcon = (
    <g transform="translate(42 42) scale(2.3) translate(-12 -12)" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12.601 21.799C14.461 20.193 20 14.993 20 10C20 7.87827 19.1571 5.84344 17.6569 4.34315C16.1566 2.84285 14.1217 2 12 2C9.87827 2 7.84344 2.84285 6.34315 4.34315C4.84285 5.84344 4 7.87827 4 10C4 14.993 9.539 20.193 11.399 21.799C11.5723 21.9293 11.7832 21.9998 12 21.9998C12.2168 21.9998 12.4277 21.9293 12.601 21.799Z" />
      <path d="M12 13C13.6569 13 15 11.6569 15 10C15 8.34315 13.6569 7 12 7C10.3431 7 9 8.34315 9 10C9 11.6569 10.3431 13 12 13Z" />
    </g>
  );

  // Calendar (uploaded) — white on dark blue.
  const calIcon = (
    <g transform="translate(42 42) scale(2.3) translate(-12 -12)" fill="#fff">
      <path d="M5.38084 8.21429H18.7142V6.30953H5.38084V8.21429ZM5.38084 21.5476C4.85703 21.5476 4.40877 21.3613 4.03607 20.9886C3.66338 20.6159 3.47671 20.1673 3.47607 19.6429V6.30953C3.47607 5.78572 3.66274 5.33746 4.03607 4.96476C4.40941 4.59207 4.85766 4.4054 5.38084 4.40476H6.33322V3.45238C6.33322 3.18254 6.42464 2.95651 6.6075 2.77429C6.79036 2.59207 7.01639 2.50064 7.2856 2.5C7.5548 2.49937 7.78115 2.5908 7.96464 2.77429C8.14814 2.95778 8.23925 3.18381 8.23798 3.45238V4.40476H15.857V3.45238C15.857 3.18254 15.9484 2.95651 16.1313 2.77429C16.3142 2.59207 16.5402 2.50064 16.8094 2.5C17.0786 2.49937 17.305 2.5908 17.4884 2.77429C17.6719 2.95778 17.7631 3.18381 17.7618 3.45238V4.40476H18.7142C19.238 4.40476 19.6865 4.59143 20.0599 4.96476C20.4332 5.3381 20.6196 5.78635 20.6189 6.30953V10.7619C20.6189 11.0317 20.5275 11.2581 20.3446 11.441C20.1618 11.6238 19.9357 11.7149 19.6665 11.7143C19.3973 11.7137 19.1713 11.6222 18.9884 11.44C18.8056 11.2578 18.7142 11.0317 18.7142 10.7619V10.119H5.38084V19.6429H10.9046C11.1745 19.6429 11.4008 19.7343 11.5837 19.9171C11.7665 20.1 11.8577 20.326 11.857 20.5952C11.8564 20.8644 11.765 21.0908 11.5827 21.2743C11.4005 21.4578 11.1745 21.5489 10.9046 21.5476H5.38084ZM14.3932 21.1076C13.4643 20.1787 12.9999 19.0556 12.9999 17.7381C12.9999 16.4206 13.4643 15.2978 14.3932 14.3695C15.3221 13.4413 16.445 12.9768 17.7618 12.9762C19.0786 12.9756 20.2018 13.44 21.1313 14.3695C22.0608 15.299 22.525 16.4219 22.5237 17.7381C22.5224 19.0543 22.058 20.1775 21.1304 21.1076C20.2027 22.0378 19.0799 22.5019 17.7618 22.5C16.4437 22.4981 15.3208 22.0346 14.3932 21.1076ZM18.238 17.5476V15.3571C18.238 15.2302 18.1904 15.119 18.0951 15.0238C17.9999 14.9286 17.8888 14.881 17.7618 14.881C17.6348 14.881 17.5237 14.9286 17.4284 15.0238C17.3332 15.119 17.2856 15.2302 17.2856 15.3571V17.5238C17.2856 17.6508 17.3094 17.774 17.357 17.8933C17.4046 18.0127 17.4761 18.1197 17.5713 18.2143L19.0237 19.6667C19.1189 19.7619 19.23 19.8095 19.357 19.8095C19.484 19.8095 19.5951 19.7619 19.6904 19.6667C19.7856 19.5714 19.8332 19.4603 19.8332 19.3333C19.8332 19.2063 19.7856 19.0952 19.6904 19L18.238 17.5476Z" />
    </g>
  );

  // Store (uploaded) — navy on light orange.
  const storeIcon = (
    <g transform="translate(42 42) scale(2.3) translate(-12 -12)" fill="#fff">
      <path d="M19.1 2.8C18.72 2.3 18.13 2 17.5 2H6.5C5.87 2 5.28 2.3 4.9 2.8L2.2 6.4C2.07 6.57 2 6.78 2 7V8C2 9.04 2.41 9.98 3.06 10.69C3.03 10.79 3 10.89 3 11V20C3 21.1 3.9 22 5 22H19C20.1 22 21 21.1 21 20V11C21 10.89 20.97 10.79 20.94 10.69C21.59 9.98 22 9.04 22 8V7C22 6.78 21.93 6.57 21.8 6.4L19.1 2.8ZM20 7.33V8C20 9.1 19.1 10 18 10C16.9 10 16 9.1 16 8V7C16 6.92 15.99 6.84 15.97 6.76L15.28 4H17.5L20 7.33ZM10.78 4H13.22L14 7.12V8C14 9.1 13.1 10 12 10C10.9 10 10 9.1 10 8V7.12L10.78 4ZM4 7.33L6.5 4H8.72L8.03 6.76C8.01 6.84 8 6.92 8 7V8C8 9.1 7.1 10 6 10C4.9 10 4 9.1 4 8V7.33ZM10 20V16H14V20H10ZM16 20V16C16 14.9 15.1 14 14 14H10C8.9 14 8 14.9 8 16V20H5V11.86C5.32 11.94 5.65 12 6 12C7.2 12 8.27 11.46 9 10.62C9.73 11.46 10.8 12 12 12C13.2 12 14.27 11.46 15 10.62C15.73 11.46 16.8 12 18 12C18.35 12 18.68 11.94 19 11.86V20H16Z" />
    </g>
  );
  return (
    <div ref={wrapRef} className={"ts-cp" + (live ? " is-live" : "")} onMouseEnter={replay}
         onClick={replay}
         role="img"
         aria-label="Phone whose content adapts to language, location, and date signals.">
      <svg viewBox="0 0 380 480" preserveAspectRatio="xMidYMid meet">
        <defs>
          <filter id="cpPhoneShadow" x="-40%" y="-30%" width="180%" height="170%">
            <feDropShadow dx="0" dy="22" stdDeviation="22" floodColor="#1C2250" floodOpacity="0.26" />
          </filter>
          <filter id="cpChipShadow" x="-60%" y="-60%" width="220%" height="220%">
            <feDropShadow dx="0" dy="8" stdDeviation="10" floodColor="#1C2250" floodOpacity="0.24" />
          </filter>
          <linearGradient id="cpBanner" x1="0" y1="0" x2="0.6" y2="1">
            <stop offset="0" stopColor={CP_BLUE2} />
            <stop offset="1" stopColor={CP_BLUE} />
          </linearGradient>
          <clipPath id="cpScreen">
            <rect x="105" y="35" width="170" height="410" rx="30" />
          </clipPath>
        </defs>

        <g className="ts-cp-device">
          {/* ── Phone (with shadow on the device itself) ── */}
          <g filter="url(#cpPhoneShadow)">
            <rect x="94" y="24" width="192" height="432" rx="40" fill={CP_INK} />
            <rect x="105" y="35" width="170" height="410" rx="30" fill="#fff" />
          </g>
          <rect x="100" y="30" width="180" height="420" rx="35"
                fill="none" stroke="rgba(255,255,255,0.10)" strokeWidth="2" />

          {/* ── On-screen content (clipped to the screen) ── */}
          <g clipPath="url(#cpScreen)">
            {/* status bar */}
            <text x="124" y="62" fontSize="11" fontWeight="700" fill={CP_INK}
                  fontFamily="Montserrat" opacity="0.85">9:41</text>
            <g fill={CP_INK} opacity="0.55">
              <rect x="232" y="55" width="13" height="8" rx="2" />
              <rect x="248" y="53" width="10" height="10" rx="2" />
              <rect x="261" y="51" width="6" height="12" rx="2" />
            </g>

            {/* hero / media banner */}
            <rect x="123" y="78" width="134" height="104" rx="16" fill="url(#cpBanner)" />
            <circle cx="234" cy="102" r="13" fill="rgba(255,255,255,0.6)" />
            <rect x="139" y="150" width="78" height="9" rx="4.5" fill="rgba(255,255,255,0.95)" />
            <rect x="139" y="165" width="50" height="7" rx="3.5" fill="rgba(255,255,255,0.6)" />

            {/* article title */}
            <rect x="123" y="202" width="118" height="13" rx="6.5" fill={CP_BLUE} />
            {/* body copy */}
            <rect x="123" y="226" width="134" height="8" rx="4" fill="#D7DBEF" />
            <rect x="123" y="240" width="134" height="8" rx="4" fill="#E2E5F3" />
            <rect x="123" y="254" width="96" height="8" rx="4" fill="#E2E5F3" />

            {/* meta chips row */}
            <rect x="123" y="280" width="52" height="20" rx="10" fill={CP_PANEL} stroke={CP_LINE} strokeWidth="1.5" />
            <rect x="133" y="287" width="32" height="6" rx="3" fill="#C2C7E4" />
            <rect x="183" y="280" width="64" height="20" rx="10" fill={CP_PANEL} stroke={CP_LINE} strokeWidth="1.5" />
            <rect x="193" y="287" width="44" height="6" rx="3" fill="#C2C7E4" />

            {/* secondary list rows */}
            <rect x="123" y="320" width="36" height="36" rx="10" fill="#EAECF8" />
            <rect x="171" y="326" width="86" height="8" rx="4" fill="#D7DBEF" />
            <rect x="171" y="342" width="58" height="7" rx="3.5" fill="#E2E5F3" />

            {/* primary button */}
            <rect x="123" y="384" width="134" height="38" rx="19" fill={CP_AMBER} />
            <rect x="160" y="399" width="60" height="9" rx="4.5" fill="#1C2250" opacity="0.6" />

            {/* hover light sweep */}
            <rect key={runId} className="ts-cp-sweep" x="60" y="35" width="70" height="410"
                  fill="rgba(255,255,255,0.55)" />
          </g>
        </g>

        {/* ── Floating attribute chips (overlapping the phone edges) ── */}
        <g key={runId}>
          <CPChip cx="92" cy="126" color={CP_AMBER} icon={langIcon} idx={0}
                  label={["Adapt Content by", "Language"]} />
          <CPChip cx="290" cy="150" color={CP_AMBER2} icon={storeIcon} idx={1}
                  label={["Adapt Content by", "Retailer, Branch, Etc"]} />
          <CPChip cx="290" cy="308" color={CP_BLUE2} icon={pinIcon} idx={2}
                  label={["Adapt Content by", "Geolocation"]} />
          <CPChip cx="96" cy="360" color={CP_BLUE} icon={calIcon} idx={3}
                  label={["Adapt Content by", "Time, Date & More"]} />
        </g>
      </svg>
    </div>
  );
}

window.ContextualPhone = ContextualPhone;
