/* global React */
// ============================================================
// CASOS DE USO — coverflow carousel
//
// Sits right after Audiences ("para empresas que cruzan
// fronteras"): Audiences shows the abstract cross-border flow,
// this section zooms into the 4 concrete operating models.
//
// A 3D coverflow: the CENTER card is in focus (sharp, 100%
// scale, elevated, prominent shadow); the lateral cards are
// smaller, blurred, lower opacity and pushed back in depth so
// you can intuit what comes next. Auto-rotates every 4s with a
// brisk ease-out; loops infinitely; manual nav via the dots.
// ============================================================

const { useState: cuUseState, useEffect: cuUseEffect, useRef: cuUseRef } = React;

// ---- Flag helper (same source as Audiences) ----
const CuFlag = ({ code }) => (
  <img
    className="cu-flag"
    src={`https://flagcdn.com/w40/${code}.png`}
    srcSet={`https://flagcdn.com/w80/${code}.png 2x`}
    width={18} height={13} alt="" loading="lazy" draggable="false"
  />
);

// ---- Mini-visuals, one per case ----

// CARD 1 · Startups — FX comparison: a high rate (struck out, grey) vs.
// Meefi's better rate (highlighted), with a green "same-day" settlement chip.
function CuVisualStartups() {
  return (
    <div className="cu-vis cu-panel">
      <div className="cu-panel-head">
        <span className="cu-panel-title">USD/MXN exchange rate</span>
        <span className="cu-pill cu-pill-sent"><span className="cu-pill-dot" />Same day</span>
      </div>
      <div className="cu-fx">
        <div className="cu-fx-row cu-fx-row-old">
          <span className="cu-fx-label">Traditional bank</span>
          <span className="cu-fx-rate cu-fx-rate-old">$17.10</span>
        </div>
        <div className="cu-fx-row cu-fx-row-new">
          <span className="cu-fx-label">
            <span className="cu-fx-spark" aria-hidden="true" />Meefi exchange rate
          </span>
          <span className="cu-fx-rate cu-fx-rate-new">$17.30</span>
        </div>
      </div>
      <div className="cu-fx-foot">
        <span className="cu-fx-save">You save <strong>$1.65</strong> per dollar</span>
        <span className="cu-fx-bps">− 8.7%</span>
      </div>
    </div>
  );
}

// CARD 2 · Importadoras — outgoing payments, status "Enviado"
function CuVisualImport() {
  const rows = [
    { code: "cn", name: "Supplier · Shenzhen", amt: "$48,200 USD" },
    { code: "us", name: "Supplier · Miami",     amt: "$12,500 USD" },
    { code: "eu", name: "Factory · Milan",      amt: "€9,800 EUR" },
  ];
  return (
    <div className="cu-vis cu-panel">
      <div className="cu-panel-head">
        <span className="cu-panel-title">Outgoing payments</span>
        <span className="cu-panel-sub">Today</span>
      </div>
      <ul className="cu-rows">
        {rows.map((r) => (
          <li key={r.name} className="cu-row">
            <span className="cu-row-l"><CuFlag code={r.code} /><span className="cu-row-name">{r.name}</span></span>
            <span className="cu-row-r">
              <span className="cu-amt">{r.amt}</span>
              <span className="cu-pill cu-pill-sent"><span className="cu-pill-dot" />Sent</span>
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}

// CARD 3 · Exportadoras — incoming foreign currency → one MXN account
function CuVisualExport() {
  const rows = [
    { code: "us", name: "USA client",    amt: "+$32,000 USD" },
    { code: "eu", name: "Europe client", amt: "+€18,400 EUR" },
    { code: "cn", name: "Asia client",   amt: "+¥120,000 CNY" },
  ];
  return (
    <div className="cu-vis cu-panel">
      <div className="cu-panel-head">
        <span className="cu-panel-title">Incoming payments</span>
        <span className="cu-panel-sub">Settled</span>
      </div>
      <ul className="cu-rows">
        {rows.map((r) => (
          <li key={r.name} className="cu-row">
            <span className="cu-row-l"><CuFlag code={r.code} /><span className="cu-row-name">{r.name}</span></span>
            <span className="cu-amt cu-amt-in">{r.amt}</span>
          </li>
        ))}
      </ul>
      <div className="cu-panel-foot">
        <span className="cu-foot-l"><CuFlag code="mx" />Your MXN account</span>
        <span className="cu-foot-r">$1,184,600 MXN</span>
      </div>
    </div>
  );
}

// CARD 4 · Empresas de servicios — CFDI ligado al SAT + conciliación
function CuVisualServicios() {
  return (
    <div className="cu-vis cu-panel cu-panel-doc">
      <div className="cu-doc-head">
        <span className="cu-doc-kind">CFDI invoice</span>
        <span className="cu-pill cu-pill-sat"><span className="cu-pill-dot" />SAT · Validated</span>
      </div>
      <div className="cu-doc-meta">
        <span className="cu-doc-row"><span>Folio</span><span className="cu-mono">A-2048</span></span>
        <span className="cu-doc-row"><span>UUID</span><span className="cu-mono">3F9C…E1A7</span></span>
        <span className="cu-doc-row"><span>Total</span><span className="cu-mono">$58,000 MXN</span></span>
      </div>
      <div className="cu-doc-recon">
        <span className="cu-recon-check" aria-hidden="true">
          <svg viewBox="0 0 16 16" fill="none"><path d="M3.5 8.5 L6.5 11.5 L12.5 4.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>
        </span>
        Automatically reconciled with the payment
      </div>
    </div>
  );
}

// ---- Cards ----
const CASOS_CARDS = [
  {
    tag: "Startups",
    title: <>Move money at the best exchange rate<Fn n={4}/>, no matter where your HQ is.</>,
    Visual: CuVisualStartups,
    anchor: "Better FX · same day",
  },
  {
    tag: "Importers",
    title: <>Pay your suppliers worldwide, the same day<Fn n={1}/>.</>,
    Visual: CuVisualImport,
    anchor: "70+ countries · same day",
  },
  {
    tag: "Exporters",
    title: "Collect from your foreign clients, no middlemen.",
    Visual: CuVisualExport,
    anchor: "Straight to your MX account",
  },
  {
    tag: "Service companies",
    title: "Invoice, collect and reconcile from one place.",
    Visual: CuVisualServicios,
    anchor: "Integrated with the SAT",
  },
];

const CU_N = CASOS_CARDS.length;

function CasosUsoSection() {
  const [active, setActive] = cuUseState(0);
  const [started, setStarted] = cuUseState(false);
  const sectionRef = cuUseRef(null);

  // Kick off the carousel the first time the section scrolls into view, then
  // disconnect. Once started it runs forever — no pausing on hover, scroll-out
  // or tab change.
  cuUseEffect(() => {
    const el = sectionRef.current;
    if (!el || typeof IntersectionObserver !== "function") { setStarted(true); return; }
    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) { setStarted(true); io.disconnect(); }
      },
      { threshold: 0.25 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Auto-advance: 4s dwell per card, looping infinitely once started.
  cuUseEffect(() => {
    if (!started) return;
    const id = setTimeout(() => setActive((a) => (a + 1) % CU_N), 4000);
    return () => clearTimeout(id);
  }, [active, started]);

  // Footer "Solutions" links open a specific card. Start the carousel
  // (in case it hasn't yet) and jump to it; the dwell timer above resets
  // on the active change, so it lingers a full beat before advancing.
  cuUseEffect(() => {
    const onGoto = (e) => {
      if (typeof e.detail !== "number") return;
      setStarted(true);
      setActive(e.detail);
    };
    window.addEventListener("meefi:caso", onGoto);
    return () => window.removeEventListener("meefi:caso", onGoto);
  }, []);

  // Relative offset of card i from the active one, wrapped into (-CU_N/2, CU_N/2].
  const relOffset = (i) => {
    let rel = (i - active + CU_N) % CU_N;
    if (rel > CU_N / 2) rel -= CU_N;
    return rel;
  };

  // Coverflow transform per relative offset (% shifts are relative to card width).
  const cardStyle = (rel) => {
    const sign = Math.sign(rel);
    const abs = Math.abs(rel);
    if (rel === 0) {
      return { transform: "translateX(-50%) translateY(-10px) scale(1)", opacity: 1, filter: "none", zIndex: 30 };
    }
    if (abs === 1) {
      return {
        transform: `translateX(calc(-50% + ${sign * 76}%)) scale(0.88) rotateY(${-sign * 16}deg)`,
        opacity: 0.5, filter: "blur(1.6px)", zIndex: 20,
      };
    }
    // far / behind (rel === ±2)
    return {
      transform: `translateX(calc(-50% + ${sign * 118}%)) scale(0.78) rotateY(${-sign * 22}deg)`,
      opacity: 0, filter: "blur(3px)", zIndex: 10, pointerEvents: "none",
    };
  };

  return (
    <section
      className="cu-section"
      id="casos-uso"
      data-screen-label="Use cases"
      ref={sectionRef}
    >
      <div className="cu-ambient" aria-hidden="true" />

      <div className="cu-wrap">
        <header className="cu-header">
          <span className="cu-badge reveal">
            <span className="cu-badge-dot" aria-hidden="true" />
            Use cases
          </span>
          <h2 className="cu-headline reveal" style={{ "--reveal-delay": "80ms" }}>
            Built for <span className="cu-grad">how your company operates.</span>
          </h2>
          <p className="cu-lede reveal" style={{ "--reveal-delay": "160ms" }}>
            Every business moves its money differently. Meefi adapts to yours.
          </p>
        </header>

        <div className="cu-stage reveal" style={{ "--reveal-delay": "220ms" }}>
          <div className="cu-track">
            {CASOS_CARDS.map((c, i) => {
              const rel = relOffset(i);
              const isActive = rel === 0;
              const Visual = c.Visual;
              return (
                <article
                  key={c.tag}
                  className={`cu-card${isActive ? " is-active" : ""}`}
                  style={cardStyle(rel)}
                  aria-hidden={!isActive}
                  onClick={() => !isActive && setActive(i)}
                >
                  <div className="cu-card-inner">
                    <span className="cu-tag">{c.tag}</span>
                    <h3 className="cu-card-title">
                      {c.title}
                    </h3>
                    <Visual />
                    <div className="cu-anchor">
                      <span className="cu-anchor-dot" aria-hidden="true" />
                      <span className="cu-anchor-text">{c.anchor}</span>
                    </div>
                  </div>
                </article>
              );
            })}
          </div>
        </div>

        <div className="cu-dots" role="tablist" aria-label="Use cases">
          {CASOS_CARDS.map((c, i) => (
            <button
              key={c.tag}
              className={`cu-dot${i === active ? " is-active" : ""}`}
              role="tab"
              aria-selected={i === active}
              aria-label={c.tag}
              onClick={() => setActive(i)}
            />
          ))}
        </div>
      </div>
    </section>
  );
}

window.CasosUsoSection = CasosUsoSection;
