/* global React */
// ============================================================
// MultidivisaFlow — Multidivisa feature animation.
//
// A horizontal carousel (same vocabulary as the client-logos
// marquee) that rotates a pixel-faithful recreation of the
// real Meefi "Balance en Meefi" dashboard card. The same window
// repeats across the five supported currencies — USD · MXN ·
// EUR · GBP · CNY — each showing the balance in its own symbol
// with a slightly different 7-day trend line.
//
// The balance card markup + styling is copied 1:1 from the real
// `.caf-bal` card in CuentasFlow.jsx, re-prefixed `mdv-` to keep
// the scopes independent.
// ============================================================
const { useMemo: mdvUseMemo, useState: mdvUseState, useRef: mdvUseRef, useEffect: mdvUseEffect } = React;

// --- Icons (copied exactly from the CuentasFlow icon set) ---
const MDV_Shield = (p) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
    <path d="M12 3 5 6v6c0 4 3 6.5 7 9 4-2.5 7-5 7-9V6l-7-3Z"/><path d="m9 12 2 2 4-4"/>
  </svg>
);
const MDV_Trend = (p) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
    <path d="M3 17l6-6 4 4 7-8"/>
  </svg>
);
const MDV_Cells = (p) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
    <rect x="3" y="3" width="8" height="8" rx="1.5"/><rect x="13" y="3" width="8" height="8" rx="1.5"/>
    <rect x="3" y="13" width="8" height="8" rx="1.5"/><rect x="13" y="13" width="8" height="8" rx="1.5"/>
  </svg>
);
const MDV_Chev = (p) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
    <path d="m6 9 6 6 6-6"/>
  </svg>
);

// Same underlying balance, expressed in each currency. Each gets
// its own gently-rising 7-day trend path so the cards don't look
// like carbon copies.
const MDV_CURRENCIES = [
  { code: "USD", symbol: "$", amount: "2,698.40",
    path: "M0,96 L180,96 C260,96 280,138 380,136 C500,134 540,150 640,150 L820,150" },
  { code: "MXN", symbol: "$", amount: "49,898.98",
    path: "M0,150 L150,150 C230,150 250,120 340,118 L470,118 C560,118 580,70 690,68 L820,66" },
  { code: "EUR", symbol: "€", amount: "2,481.10",
    path: "M0,120 C110,120 150,150 250,150 C360,150 400,60 520,58 C640,56 700,104 820,104" },
  { code: "GBP", symbol: "£", amount: "2,131.55",
    path: "M0,150 L120,150 C210,150 240,86 360,86 L470,86 C560,86 600,128 700,126 L820,60" },
  { code: "CNY", symbol: "¥", amount: "19,562.00",
    path: "M0,72 L160,72 C250,72 270,118 380,116 C500,114 540,150 660,150 C740,150 770,108 820,96" },
];

const MDV_DATES = ["May 22", "May 23", "May 24", "May 25", "May 26", "May 27"];

function MdvBalanceCard({ symbol, amount, code, width }) {
  const cur = MDV_CURRENCIES.find((c) => c.code === code);
  const gid = `mdvg-${code}`;
  const compact = width != null && width < 360;
  return (
    <div className="mdv-card" style={width != null ? { width, padding: compact ? "20px" : "26px" } : undefined}>
      <div className="mdv-bal-top">
        <span className="mdv-bal-title">Balance en Meefi <MDV_Shield width="15" height="15"/></span>
        <span className="mdv-bal-tg">
          <span className="mdv-tg-on"><MDV_Trend width="15" height="15"/></span>
          <span className="mdv-tg-off"><MDV_Cells width="15" height="15"/></span>
        </span>
      </div>
      <div className="mdv-bal-amt">{symbol}{amount}<span className="mdv-cur-code">{code}</span></div>
      <div className="mdv-bal-range">Últimos 7 días <MDV_Chev width="13" height="13"/></div>
      <div className="mdv-chart">
        <svg viewBox="0 0 820 190" preserveAspectRatio="none">
          <defs>
            <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="rgba(90,116,236,.22)"/>
              <stop offset="100%" stopColor="rgba(90,116,236,0)"/>
            </linearGradient>
          </defs>
          <path d={`${cur.path} L820,190 L0,190 Z`} fill={`url(#${gid})`}/>
          <path d={cur.path} fill="none" stroke="#5a74ec" strokeWidth="2.4"/>
        </svg>
      </div>
      <div className="mdv-chart-x">{MDV_DATES.map((d, i) => <span key={i}>{d}</span>)}</div>
    </div>
  );
}

function MultidivisaFlow() {
  const N = MDV_CURRENCIES.length;
  // Flank the real set with a clone of the LAST currency at the head and a
  // clone of the FIRST at the tail, so when MXN is centered you glimpse CNY
  // to its left, and when CNY is centered you glimpse MXN to its right.
  const display = mdvUseMemo(
    () => [MDV_CURRENCIES[N - 1], ...MDV_CURRENCIES, MDV_CURRENCIES[0]],
    [N]
  );
  const [active, setActive] = mdvUseState(0);
  const [tx, setTx] = mdvUseState(0);
  // Card width adapts to the stage so it never overflows on narrow
  // (mobile) stages — the carousel centering math reads live offsets,
  // so shrinking the card keeps the active card perfectly centered.
  const [cardW, setCardW] = mdvUseState(420);

  const stageRef = mdvUseRef(null);
  const cardRefs = mdvUseRef([]);

  const computeCardW = () => {
    const stage = stageRef.current;
    if (!stage) return;
    const sw = stage.clientWidth;
    setCardW(Math.max(248, Math.min(420, Math.round(sw * 0.84))));
  };

  // Slide the track so the active card sits in the middle of the stage.
  // Real card `i` lives at display position `i + 1` (head clone is at 0).
  const center = (i) => {
    const stage = stageRef.current, card = cardRefs.current[i + 1];
    if (!stage || !card) return;
    const cardCenter = card.offsetLeft + card.offsetWidth / 2;
    setTx(stage.clientWidth / 2 - cardCenter);
  };

  mdvUseEffect(() => {
    computeCardW();
    const onR = () => computeCardW();
    window.addEventListener("resize", onR);
    return () => window.removeEventListener("resize", onR);
    // eslint-disable-next-line
  }, []);

  // Re-center synchronously whenever the active card OR the card width
  // changes — reading offsetLeft forces a layout flush, so the new width
  // is already reflected. (rAF here raced the stepper and left tx at 0.)
  mdvUseEffect(() => {
    center(active);
    // eslint-disable-next-line
  }, [active, cardW]);

  // Step card-by-card with a dwell on each; hold on the last until the
  // parent rotates this feature away (then it remounts back at card 0).
  mdvUseEffect(() => {
    const STEP = 2100;            // pop (~0.85s) + pause before advancing
    let i = 0;
    setActive(0);
    const id = setInterval(() => {
      i += 1;
      if (i >= N) { clearInterval(id); return; }
      setActive(i);
    }, STEP);
    return () => clearInterval(id);
    // eslint-disable-next-line
  }, []);

  return (
    <div className="mdv-stage" ref={stageRef}>
      <div className="mdv-track" style={{ transform: `translateX(${tx}px)` }}>
        {display.map((c, di) => (
          <div
            key={di}
            ref={(el) => (cardRefs.current[di] = el)}
            className={`mdv-cardwrap ${di === active + 1 ? "is-active" : ""}`}
          >
            <MdvBalanceCard symbol={c.symbol} amount={c.amount} code={c.code} width={cardW}/>
          </div>
        ))}
      </div>
      <style>{MDV_CSS}</style>
    </div>
  );
}

const MDV_CSS = `
.mdv-stage,.mdv-stage *{font-family:'Montserrat',sans-serif !important;box-sizing:border-box;}
.mdv-stage{position:absolute;inset:0;overflow:hidden;display:flex;align-items:center;
  -webkit-font-smoothing:antialiased;
  -webkit-mask-image:linear-gradient(to right,transparent 0%,#000 9%,#000 91%,transparent 100%);
          mask-image:linear-gradient(to right,transparent 0%,#000 9%,#000 91%,transparent 100%);}
.mdv-track{display:flex;align-items:center;width:max-content;
  transition:transform .5s cubic-bezier(.4,0,.2,1);will-change:transform;}

/* Each card sits in a wrapper that handles spacing + the pop effect, so
   the pop scale never fights the track's translate. */
.mdv-cardwrap{flex:none;margin:0 18px;transform-origin:center center;
  opacity:.42;filter:saturate(.9);
  transition:opacity .55s ease,filter .55s ease;}
.mdv-cardwrap.is-active{opacity:1;filter:none;
  animation:mdvPop .85s cubic-bezier(.34,1.32,.5,1) both;}
@keyframes mdvPop{
  0%  {transform:scale(1);}
  45% {transform:scale(1.06);}
  100%{transform:scale(1);}
}

/* ---- Balance card — 1:1 with the real Meefi dashboard card ---- */
.mdv-card{width:420px;background:#fff;
  border:1px solid #ebedf1;border-radius:16px;padding:26px;color:#2b3240;
  box-shadow:0 1px 0 rgba(15,23,42,.02),0 26px 60px -28px rgba(4,10,34,.6);}
.mdv-bal-top{display:flex;align-items:center;justify-content:space-between;}
.mdv-bal-title{display:inline-flex;align-items:center;gap:8px;font-size:15px;color:#5b6475;}
.mdv-bal-title svg{color:#3a5bd9;}
.mdv-bal-tg{display:inline-flex;gap:0;border:1px solid #e6e8ee;border-radius:9px;overflow:hidden;}
.mdv-tg-on{padding:6px 9px;background:#f3f5f8;color:#2b3240;display:flex;}
.mdv-tg-off{padding:6px 9px;color:#9aa2b1;display:flex;}
.mdv-bal-amt{font-size:34px;font-weight:400;color:#222a37;letter-spacing:-.01em;
  margin:16px 0 4px;display:flex;align-items:baseline;gap:9px;}
.mdv-cur-code{font-size:13px;font-weight:600;letter-spacing:.04em;color:#9aa2b1;}
.mdv-bal-range{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:#8a93a3;margin-bottom:10px;}
.mdv-chart{height:150px;}
.mdv-chart svg{width:100%;height:100%;display:block;}
.mdv-chart-x{display:flex;justify-content:space-between;font-size:11.5px;color:#aab2c2;margin-top:6px;}

@media (prefers-reduced-motion: reduce){
  .mdv-track{transition:none;}
  .mdv-cardwrap.is-active{animation:none;}
}
`;

window.MultidivisaFlow = MultidivisaFlow;
