/* global React */
// ============================================================
// MasivosFlow — faithful HTML/CSS recreation of the real Meefi
// "Dispersión masiva" flow, in the same visual language as
// LocalesFlow (fixed artboard scaled to fit the stage + an
// animated cursor). Two screens, matching the product 1:1:
//   STEP 0 — "Sube el archivo": batch name + outgoing account +
//            an uploader where a cursor drops "Dispersion.xlsm".
//   STEP 1 — review: "Dispersión masiva" summary card + the
//            "Transferencias importadas" table.
// The same "Regresar / Enviar pagos" action bar is shown on
// both screens (per the reference). CSS namespaced `mpf-`.
// ============================================================
const { useState, useRef, useEffect } = React;

/* ---- icon set (shared line style with LocalesFlow) ---- */
const McIc = {
  upload:  (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 9l5-5 5 5"/><path d="M12 4v12"/></svg>),
  file:    (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg>),
  send:    (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7Z"/></svg>),
  cal:     (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="4.5" width="18" height="17" rx="2.5"/><path d="M3 9h18M8 3v3M16 3v3"/></svg>),
  arrowR:  (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 6l6 6-6 6"/></svg>),
  search:  (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>),
  bookmark:(p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>),
  eye:     (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="2.6"/></svg>),
  bank:    (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 21h18M4 10h16M5 10V8l7-4 7 4v2M6 10v8M10 10v8M14 10v8M18 10v8"/></svg>),
  chevDown:(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>),
  chevL:   (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="m15 6-6 6 6 6"/></svg>),
};
const MAvatar = ({ size = 30 }) => (
  <span className="mpf-m" style={{ width: size, height: size }}>m</span>
);

// Fixed design size for the artboard, scaled (contain) into the live
// stage so nothing clips on phones/tablets — same approach as LocalesFlow.
const MPF_DES_W = 880;
const MPF_DES_H = 810;

const MPF_TROWS = [
  { name: "Importaciones del Pacifico SA de CV", rfc: "IPA180312QF3", acct: "0121 8040 0281 755093", amt: "$1,000.00" },
  { name: "Logistica y Aduanas Noreste SA de CV", rfc: "LAN150724MK9", acct: "0725 8021 1496 300745", amt: "$1,000.00" },
  { name: "Comercializadora Textil Andina SRL",   rfc: "CTA210905J27", acct: "0146 5055 0038 920174", amt: "$1,000.00" },
  { name: "Roberto Mendez Salinas",               rfc: "MESR900215H41",acct: "0218 7060 0147 723082", amt: "$1,000.00" },
  { name: "Suministros Industriales del Bajio SA",rfc: "SIB170630TX8", acct: "0021 2070 0366 509216", amt: "$1,000.00" },
];

function MasivosFlow() {
  const [step, setStep]       = useState(0);
  const [hoverDrop, setHoverDrop] = useState(false);
  const [uploaded, setUploaded]   = useState(false);
  const [btn, setBtn]         = useState(null);  // 'hover' | 'press'
  const [rowsIn, setRowsIn]   = useState(0);     // staggered review rows
  const [cur, setCur]         = useState({ x: 60, y: 80, show: false });
  const [press, setPress]     = useState(false);
  const [click, setClick]     = useState(null);
  const [scale, setScale]     = useState(1);

  const artRef     = useRef(null);
  const dropRef    = useRef(null);
  const primaryRef = useRef(null);
  const lastPos    = useRef({ x: 60, y: 80 });

  // Scale the fixed artboard to fit the stage (never upscale past 1).
  useEffect(() => {
    const st = artRef.current;
    const measure = () => {
      if (!st) return;
      setScale(Math.min(st.clientWidth / MPF_DES_W, st.clientHeight / MPF_DES_H, 1));
    };
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, []);

  // Cursor choreography:
  //   upload screen → drop file → click "Enviar pagos" → review screen.
  useEffect(() => {
    const timers = [];
    const at = (ms, fn) => timers.push(setTimeout(fn, ms));
    let k = 0;

    const moveTo = (ref, dx = 0, dy = 0) => {
      const art = artRef.current, el = ref.current;
      if (!art || !el) return;
      const a = art.getBoundingClientRect();
      const r = el.getBoundingClientRect();
      const x = r.left - a.left + r.width / 2 + dx;
      const y = r.top - a.top + r.height / 2 + dy;
      lastPos.current = { x, y };
      setCur({ x, y, show: true });
    };
    const pulse = () => {
      const { x, y } = lastPos.current;
      setPress(true); setClick({ x, y, k: ++k });
      timers.push(setTimeout(() => setPress(false), 190));
    };

    // ---------- STEP 0 — Sube el archivo ----------
    setStep(0); setUploaded(false); setRowsIn(0); setBtn(null);
    setCur((c) => ({ ...c, show: false }));
    at(650,  () => moveTo(dropRef));
    at(760,  () => setHoverDrop(true));
    at(1700, () => { pulse(); setUploaded(true); });
    at(2050, () => setHoverDrop(false));
    at(2550, () => { moveTo(primaryRef); setBtn("hover"); });
    at(3550, () => { setBtn("press"); pulse(); });
    at(3850, () => setBtn(null));
    at(4150, () => setStep(1));

    // ---------- STEP 1 — Revisión / dispersión ----------
    at(4600, () => { moveTo(primaryRef); setBtn("hover"); });
    MPF_TROWS.forEach((_, i) => at(4500 + i * 170, () => setRowsIn(i + 1)));
    // hold on the "Enviar pagos" button until the feature rotates away

    return () => timers.forEach(clearTimeout);
  }, []);

  return (
    <div className="mpf-stage" ref={artRef}>
      <div className="mpf-art" style={{ transform: `translate(-50%, -50%) scale(${scale})` }}>
        <div className="mpf-body">

          {/* ---------------- STEP 0 — upload ---------------- */}
          {step === 0 && (
            <div className="mpf-step mpf-upload">
              <h3 className="mpf-h">Sube el archivo</h3>
              <p className="mpf-sub">
                Antes de subir el archivo, <span className="mpf-link">descarga la plantilla</span> o <span className="mpf-link">consulta las instrucciones.</span>
              </p>

              <div className="mpf-label">Nombre del lote</div>
              <div className="mpf-input">Proveedores</div>

              <div className="mpf-label">Cuenta de salida</div>
              <div className="mpf-dd-field">
                <MAvatar/>
                <div className="mpf-dd-meta">
                  <span className="mpf-dd-name">Principal</span>
                  <span className="mpf-dd-sub">$6,636.95 / USD ••0008</span>
                </div>
                <span className="mpf-dd-caret"><McIc.chevDown width="18" height="18"/></span>
              </div>

              <div className="mpf-label">Archivo</div>
              <div ref={dropRef} className={`mpf-drop ${hoverDrop ? "is-hover" : ""} ${uploaded ? "is-filled" : ""}`}>
                <span className="mpf-drop-ic"><McIc.upload width="22" height="22"/></span>
                {uploaded && <div className="mpf-drop-file">Dispersion.xlsm</div>}
                <div className="mpf-drop-hint">Arrastra y suelta o haz clic para subir un archivo</div>
              </div>
            </div>
          )}

          {/* ---------------- STEP 1 — review ---------------- */}
          {step === 1 && (
            <div className="mpf-step mpf-review">
              {/* summary card */}
              <div className="mpf-card mpf-summary">
                <div className="mpf-sum-top">
                  <span className="mpf-label mpf-label-tight">Dispersión masiva</span>
                  <div className="mpf-pills">
                    <span className="mpf-pill"><McIc.send width="13" height="13"/>5 pagos</span>
                    <span className="mpf-pill"><McIc.file width="13" height="13"/>Dispersion.xlsm</span>
                  </div>
                </div>
                <div className="mpf-sum-amt">$5,000.00<span className="mpf-cur-tag">USD</span></div>
                <div className="mpf-sum-sub">Total a enviar</div>
                <div className="mpf-sum-div"/>
                <div className="mpf-sum-foot">
                  <span><McIc.cal width="15" height="15"/> Pago inmediato · 24 junio 2026</span>
                  <span className="mpf-sum-spei"><McIc.arrowR width="15" height="15"/> WIRE</span>
                </div>
                <div className="mpf-label mpf-label-tight" style={{ marginTop: 18 }}>Cuenta de salida</div>
                <div className="mpf-sum-acct">
                  <MAvatar/>
                  <div className="mpf-dd-meta">
                    <span className="mpf-dd-name">Multi-Procesador Test</span>
                    <span className="mpf-dd-sub">$10,000.00 / USD ••0027</span>
                  </div>
                </div>
              </div>

              {/* imported transfers table */}
              <div className="mpf-card mpf-table">
                <div className="mpf-table-head">
                  <div className="mpf-table-title">Transferencias importadas <span className="mpf-count">5</span></div>
                  <div className="mpf-table-controls">
                    <div className="mpf-search-sm">
                      <McIc.search width="15" height="15"/>
                      <span>Buscar...</span>
                    </div>
                    <span className="mpf-ctrl-btn"><McIc.bookmark width="14" height="14"/>Vista de datos<McIc.chevDown width="14" height="14"/></span>
                    <span className="mpf-ctrl-icon"><McIc.eye width="16" height="16"/></span>
                  </div>
                </div>
                <div className="mpf-cols">
                  <span>Beneficiario</span>
                  <span>Cuenta destino</span>
                  <span className="mpf-r">Monto</span>
                </div>
                <div className="mpf-trows">
                  {MPF_TROWS.map((r, i) => (
                    <div key={i} className={`mpf-trow ${i < rowsIn ? "is-in" : ""}`}>
                      <div className="mpf-ben">
                        <span className="mpf-ben-name">{r.name}</span>
                        <span className="mpf-ben-rfc">{r.rfc}</span>
                      </div>
                      <div className="mpf-dest">
                        <span className="mpf-acct-num">{r.acct}</span>
                        <span className="mpf-clabe"><McIc.bank width="12" height="12"/>SWIFT</span>
                      </div>
                      <span className="mpf-amt">{r.amt}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>

        {/* shared action bar — shown on both screens */}
        <div className="mpf-bar">
          <button className="mpf-btn mpf-btn-ghost"><McIc.chevL width="15" height="15"/>Regresar</button>
          <button ref={primaryRef} className={`mpf-btn mpf-btn-primary ${btn ? "is-" + btn : ""}`}>{step === 0 ? "Continuar" : "Enviar pagos"}</button>
        </div>
      </div>

      {/* cursor + click ripple (children of stage → exact alignment) */}
      {cur.show && (
        <span className={`mpf-cursor ${press ? "is-press" : ""}`} style={{ left: cur.x, top: cur.y }}>
          <svg width="21" height="21" viewBox="0 0 24 24" fill="#1b1f26" stroke="#ffffff" strokeWidth="1.5" strokeLinejoin="round"><path d="M5.5 2.6 L5.5 19.4 L9.7 15.4 L12.5 21.2 L14.9 20 L12.1 14.3 L17.6 14.3 Z"/></svg>
        </span>
      )}
      {click && <span key={click.k} className="mpf-click" style={{ left: click.x, top: click.y }}/>}

      <style>{MPF_CSS}</style>
    </div>
  );
}

const MPF_CSS = `
.mpf-stage,.mpf-stage *{font-family:'Montserrat',sans-serif !important;box-sizing:border-box;}
.mpf-stage{position:absolute;inset:0;background:#fff;overflow:hidden;
  color:#2b3140;-webkit-font-smoothing:antialiased;}
.mpf-art{position:absolute;left:50%;top:50%;width:880px;height:810px;
  transform-origin:center center;display:flex;flex-direction:column;}
.mpf-body{flex:1;min-height:0;display:flex;flex-direction:column;}
.mpf-step{flex:1;min-height:0;display:flex;flex-direction:column;
  padding:26px clamp(40px,7%,80px) 12px;
  animation:mpfIn .5s cubic-bezier(.22,.61,.36,1) both;}
@keyframes mpfIn{from{opacity:0;transform:translateY(12px);}to{opacity:1;transform:none;}}

/* the upload step is a narrower, vertically-centred column */
.mpf-upload{justify-content:center;align-items:stretch;}
.mpf-upload>*{width:100%;max-width:600px;margin-left:auto;margin-right:auto;}
.mpf-review>*{width:100%;max-width:840px;margin-left:auto;margin-right:auto;}

.mpf-h{font-weight:400;font-size:clamp(24px,2.6vw,33px);color:#222a37;
  letter-spacing:-.01em;margin:0 auto 6px;}
.mpf-sub{font-size:15px;color:#8a93a3;margin:0 auto 26px;line-height:1.5;}
.mpf-link{color:#2b59d6;cursor:default;}

.mpf-label{font-size:14px;color:#9c9488;margin-bottom:9px;}
.mpf-label-tight{margin-bottom:0;}
.mpf-input{display:flex;align-items:center;background:#f7f9fc;border:1px solid #e6eaf1;
  border-radius:12px;padding:15px 16px;font-size:16px;color:#2b3240;margin-bottom:22px;}

/* outgoing-account field / avatar */
.mpf-m{display:inline-flex;align-items:center;justify-content:center;flex:none;border-radius:999px;
  background:#e9edfb;color:#3a5bd9;font-weight:700;font-size:14px;line-height:1;}
.mpf-dd-field{display:flex;align-items:center;gap:12px;border:1px solid #e6eaf1;border-radius:12px;
  padding:12px 16px;background:#fff;margin-bottom:22px;}
.mpf-dd-meta{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0;}
.mpf-dd-name{font-size:15px;font-weight:600;color:#2a3a8f;}
.mpf-dd-sub{font-size:13px;color:#9aa2b1;white-space:nowrap;}
.mpf-dd-caret{color:#9aa2b1;display:flex;}

/* uploader dropzone */
.mpf-drop{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;
  border:1px solid #e6eaf1;border-radius:14px;padding:34px 20px;background:#fff;
  transition:border-color .2s ease,background .2s ease,box-shadow .2s ease;}
.mpf-drop.is-hover{border-color:#c3cdf2;background:#fafbff;box-shadow:0 0 0 3px rgba(90,116,236,.10);}
.mpf-drop-ic{width:44px;height:44px;border-radius:11px;background:#f1f3f6;color:#5c6678;
  display:inline-flex;align-items:center;justify-content:center;margin-bottom:4px;}
.mpf-drop-file{font-size:16px;color:#2b59d6;font-weight:500;animation:mpfPop .42s cubic-bezier(.2,.7,.2,1) both;}
@keyframes mpfPop{from{opacity:0;transform:translateY(4px) scale(.96);}to{opacity:1;transform:none;}}
.mpf-drop-hint{font-size:13px;color:#9aa2b1;}

/* ---- review: summary card ---- */
.mpf-card{background:#fff;border:1px solid #e8eaef;border-radius:16px;
  box-shadow:0 18px 44px -28px rgba(15,23,42,.26);}
.mpf-summary{padding:22px 24px;margin-bottom:14px;}
.mpf-sum-top{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;}
.mpf-pills{display:flex;align-items:center;gap:8px;}
.mpf-pill{display:inline-flex;align-items:center;gap:7px;padding:6px 12px;border:1px solid #e3e7ef;
  border-radius:999px;font-size:12.5px;font-weight:500;color:#5c6678;background:#fff;white-space:nowrap;}
.mpf-pill svg{color:#8893a6;}
.mpf-sum-amt{font-weight:300;font-size:44px;color:#222a37;letter-spacing:-.025em;margin:8px 0 2px;line-height:1.05;display:flex;align-items:baseline;gap:10px;}
.mpf-cur-tag{font-size:14px;font-weight:600;letter-spacing:.05em;color:#9aa2b1;}
.mpf-sum-sub{font-size:14px;color:#9c9488;}
.mpf-sum-div{height:1px;background:#eef0f3;margin:16px 0;}
.mpf-sum-foot{display:flex;align-items:center;justify-content:space-between;color:#8a93a3;font-size:13.5px;}
.mpf-sum-foot>span{display:inline-flex;align-items:center;gap:8px;}
.mpf-sum-foot svg{color:#aab2c2;}
.mpf-sum-acct{display:flex;align-items:center;gap:13px;margin-top:11px;}

/* ---- review: imported transfers table ---- */
.mpf-table{padding:18px 22px 6px;}
.mpf-table-head{display:flex;align-items:center;justify-content:space-between;gap:14px;margin-bottom:14px;}
.mpf-table-title{font-size:15px;font-weight:600;color:#2b3240;display:flex;align-items:center;gap:9px;}
.mpf-count{color:#2b59d6;font-weight:700;font-size:14px;}
.mpf-table-controls{display:flex;align-items:center;gap:9px;}
.mpf-search-sm{display:flex;align-items:center;gap:8px;background:#f7f9fc;border:1px solid #e6eaf1;
  border-radius:9px;padding:8px 12px;color:#9aa2b1;font-size:13px;min-width:190px;}
.mpf-search-sm svg{color:#aab2c2;}
.mpf-ctrl-btn{display:inline-flex;align-items:center;gap:7px;border:1px solid #e6eaf1;border-radius:9px;
  padding:8px 11px;font-size:13px;color:#5c6678;background:#fff;white-space:nowrap;}
.mpf-ctrl-btn svg{color:#8893a6;}
.mpf-ctrl-icon{display:inline-flex;align-items:center;justify-content:center;width:36px;height:34px;
  border:1px solid #e6eaf1;border-radius:9px;color:#7c8698;background:#fff;}
.mpf-cols{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(0,1.5fr) 110px;gap:14px;
  padding:0 4px 10px;font-size:12.5px;color:#9aa2b1;border-bottom:1px solid #eef0f3;}
.mpf-cols .mpf-r{text-align:right;}
.mpf-trows{}
.mpf-trow{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(0,1.5fr) 110px;gap:14px;
  align-items:center;padding:11px 4px;border-bottom:1px solid #f3f4f7;
  opacity:0;transform:translateY(5px);transition:opacity .35s ease,transform .35s ease;}
.mpf-trow.is-in{opacity:1;transform:none;}
.mpf-ben{display:flex;flex-direction:column;gap:3px;min-width:0;}
.mpf-ben-name{font-size:14px;font-weight:500;color:#2b3a6b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.mpf-ben-rfc{font-size:12px;color:#9aa2b1;letter-spacing:.02em;}
.mpf-dest{display:flex;align-items:center;gap:10px;min-width:0;}
.mpf-acct-num{font-size:13.5px;color:#2b3240;letter-spacing:.04em;font-variant-numeric:tabular-nums;white-space:nowrap;}
.mpf-clabe{display:inline-flex;align-items:center;gap:5px;padding:3px 9px;border-radius:999px;
  background:#eef1f6;color:#6b7588;font-size:11.5px;font-weight:500;white-space:nowrap;flex:none;}
.mpf-clabe svg{color:#8893a6;}
.mpf-amt{text-align:right;font-size:14px;font-weight:600;color:#2b3240;font-variant-numeric:tabular-nums;white-space:nowrap;}

/* ---- shared action bar ---- */
.mpf-bar{display:flex;align-items:center;justify-content:flex-end;gap:12px;
  padding:16px clamp(40px,7%,80px);border-top:1px solid #ececf0;background:#fff;}
.mpf-btn{display:inline-flex;align-items:center;gap:7px;border-radius:999px;font-size:14.5px;
  font-weight:500;cursor:default;border:1px solid transparent;padding:11px 22px;
  transition:transform .12s ease,background .18s ease,box-shadow .18s ease;}
.mpf-btn-ghost{background:#f1f3f6;border-color:#e6eaf1;color:#3a4250;}
.mpf-btn-ghost svg{color:#8893a6;}
.mpf-btn-primary{background:#1f3cd6;color:#fff;box-shadow:0 8px 20px -8px rgba(31,60,214,.55);}
.mpf-btn-primary.is-hover{background:#1a34bd;}
.mpf-btn-primary.is-press{transform:scale(.96);background:#172da6;}

/* ---- cursor ---- */
.mpf-cursor{position:absolute;width:22px;height:22px;margin:-1px 0 0 -1px;z-index:30;pointer-events:none;
  filter:drop-shadow(0 2px 3px rgba(0,0,0,.32));
  transition:left 1s cubic-bezier(.33,0,.2,1),top 1s cubic-bezier(.33,0,.2,1),transform .18s ease;}
.mpf-cursor.is-press{transform:scale(.8);}
.mpf-click{position:absolute;width:30px;height:30px;margin:-15px 0 0 -15px;z-index:25;pointer-events:none;
  border-radius:50%;border:2px solid rgba(31,60,214,.5);animation:mpfClick .6s cubic-bezier(.2,.7,.2,1) forwards;}
@keyframes mpfClick{0%{opacity:.85;transform:scale(.3);}100%{opacity:0;transform:scale(1.5);}}
`;

window.MasivosFlow = MasivosFlow;
