/* global React */
// ============================================================
// Audiences — "Para quién es Meefi"
//
// Single unified hub diagram. The meefi SPHERE sits at the
// center:
//   ← LEFT   incoming payments from clients worldwide
//   → RIGHT  outgoing payments that arrive "today"
//   ↑ UP     vertical link to "Tu empresa"
//   ↓ DOWN   vertical link to "Tu cuenta"
//
// Connectors run CENTER → CENTER inside one fixed-coordinate SVG
// (viewBox 1000×460). The labeled boxes + sphere are opaque HTML
// overlays painted ABOVE the SVG, so each line tucks under its
// node and always meets it — regardless of box width.
// ============================================================

const { useState: audUseState, useRef: audUseRef, useEffect: audUseEffect } = React;

const VBW = 1000, VBH = 460;
// Fixed artboard size for the scaled-down mobile rendering. 760 wide keeps
// the columns/rows spaced exactly like desktop (no overlap, no clipped text).
const AUDX_DES_W = 760, AUDX_DES_H = 350;
const ROWS_Y = [70, 177, 283, 390];
const HUB = { x: 500, y: 230 };
const CLIENT_X = 126, DEST_X = 874;
const TOP_Y = 56, BOT_Y = 368;

const CLIENTS = [
  { title: "Cliente USA",    sub: "USD",       flag: "us" },
  { title: "Cliente Europa", sub: "EUR",       flag: "eu" },
  { title: "Cliente LATAM",  sub: "BRL · COP", flag: "br" },
  { title: "Cliente Asia",   sub: "CNY · JPY", flag: "cn" },
];
const DESTINOS = [
  { title: "México",   sub: "Llega hoy", flag: "mx" },
  { title: "Miami",    sub: "Llega hoy", flag: "us" },
  { title: "Shanghái", sub: "Llega hoy", flag: "cn" },
  { title: "Madrid",   sub: "Llega hoy", flag: "es" },
];

const Pct = (x, y) => ({ left: `${(x / VBW) * 100}%`, top: `${(y / VBH) * 100}%` });

function AudiencesSection() {
  // Below 700px viewport we switch the diagram to a fixed-size artboard
  // scaled to fit, so it reads as a clean miniature of the desktop layout
  // instead of compressing until boxes overlap. `box` is null on
  // desktop/tablet (fluid) or the scale factor on phones.
  const scrollRef = audUseRef(null);
  const [box, setBox] = audUseState(null);
  // Phone (≤640px): stack the hub diagram into a single vertical column
  // (cobras → meefi → pagas) instead of shrinking the whole 2-column artboard
  // to a tiny, hard-to-read miniature. Tablet (641–1024px) keeps the scaled
  // artboard; desktop (>1024px) keeps the fluid diagram. Untouched above 640px.
  const [stack, setStack] = audUseState(false);

  audUseEffect(() => {
    const measure = () => {
      const el = scrollRef.current;
      const phone = window.innerWidth <= 640;
      setStack(phone);
      // Tablet (641–1024px) renders the fixed-artboard miniature scaled DOWN
      // to fit — a faithful shrink of the desktop diagram instead of the fluid
      // layout (whose fixed-px node boxes crowd at narrow widths).
      // Cap at 1 so it never upscales past the original composition.
      if (!phone && window.innerWidth <= 1024 && el) {
        setBox(Math.min(1, el.clientWidth / AUDX_DES_W));
      } else {
        setBox(null);
      }
    };
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, []);

  // center→center paths (ends hidden under the opaque nodes)
  const cx = (a, b) => (a + b) / 2;
  const leftPaths  = ROWS_Y.map((y) => `M${CLIENT_X},${y} C${cx(CLIENT_X, HUB.x)},${y} ${cx(CLIENT_X, HUB.x)},${HUB.y} ${HUB.x},${HUB.y}`);
  const rightPaths = ROWS_Y.map((y) => `M${HUB.x},${HUB.y} C${cx(HUB.x, DEST_X)},${HUB.y} ${cx(HUB.x, DEST_X)},${y} ${DEST_X},${y}`);
  const LANE = 9;
  const upOut = `M${HUB.x - LANE},${TOP_Y} L${HUB.x - LANE},${HUB.y}`; // Tu empresa → meefi (sale)
  const upIn  = `M${HUB.x + LANE},${HUB.y} L${HUB.x + LANE},${TOP_Y}`; // meefi → Tu empresa (entra)

  const Conn = ({ d, i = 0 }) => (
    <g>
      <path className="audx-line" d={d} vectorEffect="non-scaling-stroke" />
      <path
        className="audx-beam" d={d} pathLength="100" vectorEffect="non-scaling-stroke"
        style={{ animationDelay: `${i * -0.7}s` }}
      />
    </g>
  );

  const Box = ({ title, sub, kind, flag }) => (
    <div className="audx-box">
      <span className="audx-box-title">{title}</span>
      {sub && (
        <span className={`audx-box-sub ${kind === "src" ? "audx-sub-cur" : kind === "dest" ? "audx-sub-good" : ""}`}>
          {flag && (
            <img
              className="audx-flag"
              src={`https://flagcdn.com/w40/${flag}.png`}
              srcSet={`https://flagcdn.com/w80/${flag}.png 2x`}
              width={15} height={10} alt="" loading="lazy" draggable="false"
            />
          )}
          {sub}
        </span>
      )}
    </div>
  );

  return (
    <section className="audm-section" data-screen-label="Audiencias">
      <div className="audm-wrap">
        <header className="audm-header">
          <h2 className="audm-headline reveal" style={{ "--reveal-delay": "70ms" }}>
            Para empresas que <span className="audm-headline-accent">cruzan fronteras.</span>
          </h2>
          <p className="audm-lede reveal" style={{ "--reveal-delay": "140ms" }}>
            Importadoras que pagan a proveedores y empresas que cobran del
            extranjero. Los dos lados del flujo, una sola plataforma.
          </p>
        </header>

        <div
          className="audx-scroll reveal"
          ref={scrollRef}
          style={{ "--reveal-delay": "200ms", ...(!stack && box != null ? { height: `${AUDX_DES_H * box}px` } : {}) }}
        >
          {stack ? (
            /* ---- Phone: vertical stack (cobras → meefi → pagas) ---- */
            <div className="audx-stack">
              <div className="audx-stack-col">
                <span className="audx-stack-label">Cobras del extranjero</span>
                <div className="audx-stack-list">
                  {CLIENTS.map((c) => (
                    <Box key={c.title} title={c.title} sub={c.sub} kind="src" flag={c.flag} />
                  ))}
                </div>
              </div>

              <div className="audx-stack-mid">
                <span className="audx-stack-arrow" aria-hidden="true" />
                <div className="audx-sphere">
                  <img src="assets/meefi-sphere.png" alt="Meefi" draggable="false" />
                </div>
                <span className="audx-stack-company">Tu empresa</span>
                <span className="audx-stack-arrow" aria-hidden="true" />
              </div>

              <div className="audx-stack-col">
                <span className="audx-stack-label">Pagas · Mismo día</span>
                <div className="audx-stack-list">
                  {DESTINOS.map((d) => (
                    <Box key={d.title} title={d.title} sub={d.sub} kind="dest" flag={d.flag} />
                  ))}
                </div>
              </div>
            </div>
          ) : (
          <div
            className="audx-diagram"
            style={box != null ? {
              width: `${AUDX_DES_W}px`, height: `${AUDX_DES_H}px`,
              maxWidth: "none", aspectRatio: "auto", margin: 0,
              transform: `scale(${box})`, transformOrigin: "top left",
              animation: "none",
            } : undefined}
          >
            <svg className="audx-svg" viewBox={`0 0 ${VBW} ${VBH}`} preserveAspectRatio="xMidYMid meet" aria-hidden="true">
              {leftPaths.map((d, i)  => <Conn key={`l${i}`} d={d} i={i} />)}
              {rightPaths.map((d, i) => <Conn key={`r${i}`} d={d} i={i} />)}
              <Conn d={upOut} i={1} />
              <Conn d={upIn}  i={3} />
            </svg>

            <div className="audx-overlay">
              <span className="audx-side audx-side-l" style={Pct(CLIENT_X, 4)}>Cobras del extranjero</span>
              <span className="audx-side audx-side-r" style={Pct(DEST_X, 4)}>Pagas · Mismo día</span>

              {CLIENTS.map((c, i) => (
                <div key={c.title} className="audx-node" style={Pct(CLIENT_X, ROWS_Y[i])}>
                  <Box title={c.title} sub={c.sub} kind="src" flag={c.flag} />
                </div>
              ))}
              {DESTINOS.map((d, i) => (
                <div key={d.title} className="audx-node" style={Pct(DEST_X, ROWS_Y[i])}>
                  <Box title={d.title} sub={d.sub} kind="dest" flag={d.flag} />
                </div>
              ))}

              <div className="audx-node" style={Pct(HUB.x, TOP_Y)}>
                <Box title="Tu empresa" />
              </div>

              <div className="audx-node" style={Pct(HUB.x, HUB.y)}>
                <div className="audx-sphere">
                  <img src="assets/meefi-sphere.png" alt="Meefi" draggable="false" />
                </div>
              </div>
            </div>
          </div>
          )}
        </div>
      </div>
    </section>
  );
}

window.AudiencesSection = AudiencesSection;
