/* global React, Icons, SectionHeading,
   VisGlobe3D, VisRings3D, VisCard3D, VisOrbit3D, VisLineChart3D */
const { useEffect, useState, useRef } = React;

// ============================================================
// VIS 1 — Transferencias / Movimientos table.
// Visual fidelity to the real Meefi platform UI: filter chips,
// column headers, avatars w/ initials, monto, method, +.
// A "selected row" highlight cycles through the table.
// ============================================================
function VisMovements() {
  const [sel, setSel] = useState(0);

  const rows = [
    { date: "May 25", initials: "SO", color: "#FBE3D6", text: "#A65A2C",
      name: "Soluciones Integrales Sa", account: "Principal",
      amount: "−$3,500.00", positive: false, method: "··0001", icon: "bank" },
    { date: "May 25", initials: "RO", color: "#FCEBC2", text: "#806029",
      name: "Roberto", account: "Principal",
      amount: "−$2,800.00", positive: false, method: "··2890", icon: "bank" },
    { date: "May 25", initials: "EM", color: "#C6E8E4", text: "#2E6E66",
      name: "Emilio", account: "Principal",
      amount: "−$1,500.00", positive: false, method: "··4242", icon: "card" },
    { date: "May 17", initials: "m",  color: "#E8F0FE", text: "var(--accent)",
      name: "Hacia Proveedores",       account: "Principal",
      amount: "−$5,000.00", positive: false, method: "Transferencia", icon: "transfer" },
    { date: "May 17", initials: "m",  color: "#E8F0FE", text: "var(--accent)",
      name: "De Principal",            account: "Proveedores",
      amount: "+$5,000.00", positive: true,  method: "Transferencia", icon: "transfer", incoming: true },
    { date: "Abr 12", initials: "TE", color: "#E5E7EB", text: "#4B5563",
      name: "Test Business",           account: "Principal",
      amount: "−$5,000.00", positive: false, method: "··0099", icon: "bank" },
  ];

  useEffect(() => {
    const id = setInterval(() => setSel((i) => (i + 1) % rows.length), 1800);
    return () => clearInterval(id);
    // eslint-disable-next-line
  }, []);

  const MethodIcon = ({ icon }) => {
    if (icon === "card") return (
      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/>
      </svg>
    );
    if (icon === "transfer") return (
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-3)" }}>↔</span>
    );
    return (
      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M3 21h18M3 10v11M21 10v11M5 10h14M7 6l5-3 5 3M7 6v4M17 6v4M11 14v4M13 14v4"/>
      </svg>
    );
  };

  return (
    <div style={{
      position: "absolute", inset: 0, background: "#fff",
      padding: "22px 24px", display: "flex", flexDirection: "column",
      overflow: "hidden",
    }}>
      {/* Title */}
      <h4 style={{
        margin: 0, marginBottom: 14,
        fontFamily: "var(--font-display)", fontWeight: 500,
        fontSize: 22, color: "var(--fg-1)", letterSpacing: "-0.01em",
      }}>Transferencias</h4>

      {/* Filter chips */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 16 }}>
        {[
          { label: "Vista de datos", caret: true },
          { label: "Filtros (1)" },
          { label: "Tipo", caret: true },
          { label: "Estatus", caret: true },
        ].map((c) => (
          <span key={c.label} style={{
            display: "inline-flex", alignItems: "center", gap: 4,
            padding: "5px 10px", fontSize: 10.5, color: "var(--fg-2)",
            background: "#fff",
            border: "1px solid rgba(229,231,235,0.9)",
            borderRadius: 999,
          }}>
            {c.label}
            {c.caret && (
              <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m6 9 6 6 6-6"/></svg>
            )}
          </span>
        ))}
        <span style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          padding: "5px 10px", fontSize: 10.5, color: "var(--accent)",
          background: "rgba(5,48,206,0.08)",
          border: "1px solid rgba(5,48,206,0.20)",
          borderRadius: 999, fontWeight: 500,
        }}>
          ≥ $200.00
          <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M18 6 6 18M6 6l12 12"/></svg>
        </span>
        <span style={{ flex: 1 }}/>
        <span style={{
          display: "inline-flex", alignItems: "center", gap: 4,
          fontSize: 10.5, color: "var(--fg-2)",
        }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
          Exportar
        </span>
      </div>

      {/* Column headers */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "16px 56px minmax(0,1.5fr) minmax(0,1fr) 88px 96px 28px",
        gap: 12,
        alignItems: "center",
        padding: "0 6px 8px",
        fontSize: 10, color: "var(--fg-3)",
        letterSpacing: "0.04em",
        borderBottom: "1px solid rgba(229,231,235,0.6)",
      }}>
        <span/>
        <span>Fecha</span>
        <span>De / Para</span>
        <span>Cuenta</span>
        <span style={{ textAlign: "right" }}>Monto</span>
        <span>Método</span>
        <span/>
      </div>

      {/* Rows */}
      <div style={{ flex: 1, overflow: "hidden", marginTop: 2 }}>
        {rows.map((r, i) => {
          const isSel = sel === i;
          return (
            <div key={i} style={{
              display: "grid",
              gridTemplateColumns: "16px 56px minmax(0,1.5fr) minmax(0,1fr) 88px 96px 28px",
              gap: 12,
              alignItems: "center",
              padding: "10px 6px",
              fontSize: 11.5, color: "var(--fg-1)",
              background: isSel ? "rgba(5,48,206,0.045)" : "transparent",
              borderRadius: 6,
              transition: "background 350ms var(--ease-out-soft)",
              borderBottom: "1px solid rgba(229,231,235,0.4)",
            }}>
              {/* checkbox */}
              <span style={{
                width: 12, height: 12, borderRadius: 3,
                border: "1px solid rgba(229,231,235,1)",
                background: "#fff", display: "inline-block",
              }}/>

              {/* date */}
              <span style={{ color: "var(--fg-2)", fontSize: 11 }}>{r.date}</span>

              {/* avatar + name */}
              <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                <span style={{
                  width: 22, height: 22, borderRadius: "50%",
                  background: r.color, color: r.text,
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  fontSize: 9.5, fontWeight: 600,
                  flex: "0 0 22px",
                }}>{r.initials}</span>
                <span style={{
                  whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
                  fontWeight: isSel ? 500 : 400,
                  transition: "font-weight 200ms ease",
                }}>{r.name}</span>
              </div>

              {/* account */}
              <span style={{ color: "var(--fg-2)", fontSize: 11 }}>{r.account}</span>

              {/* amount */}
              <span style={{
                textAlign: "right",
                fontFamily: "var(--font-mono)",
                fontVariantNumeric: "tabular-nums",
                color: r.positive ? "var(--success)" : "var(--fg-1)",
                fontWeight: 500,
                fontSize: 11.5,
                whiteSpace: "nowrap",
              }}>{r.amount}</span>

              {/* method */}
              <span style={{
                display: "inline-flex", alignItems: "center", gap: 6,
                fontSize: 10.5, color: "var(--fg-2)",
                whiteSpace: "nowrap",
              }}>
                <span style={{ color: "var(--fg-3)" }}>{r.incoming ? "←" : "→"}</span>
                <MethodIcon icon={r.icon}/>
                <span>{r.method}</span>
              </span>

              {/* + button */}
              <span style={{
                width: 22, height: 22, borderRadius: 999,
                border: "1px solid rgba(229,231,235,1)",
                background: isSel ? "var(--accent)" : "#fff",
                color: isSel ? "#fff" : "var(--fg-3)",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                transition: "all 350ms var(--ease-out-soft)",
                boxShadow: isSel ? "0 4px 12px -2px rgba(5,48,206,0.40)" : "none",
              }}>
                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ============================================================
// VIS 2 — Invoice mockup filling the full stage with a slow,
// barely-perceptible Ken Burns drift so the panel stays alive.
// ============================================================
function VisInvoice() {
  return (
    <div style={{ position: "absolute", inset: 0, overflow: "hidden" }}>
      <img
        src="assets/invoice-mockup.png"
        alt="Factura CFDI"
        draggable={false}
        style={{
          position: "absolute",
          inset: 0,
          width: "100%",
          height: "100%",
          objectFit: "cover",
          objectPosition: "center",
          display: "block",
          userSelect: "none",
          pointerEvents: "none",
          animation: "invoiceDrift 22s ease-in-out infinite alternate",
          transformOrigin: "center center",
        }}
      />
      <style>{`
        @keyframes invoiceDrift {
          from { transform: scale(1.00) translate3d(0, 0, 0); }
          to   { transform: scale(1.05) translate3d(-1.2%, -0.8%, 0); }
        }
      `}</style>
    </div>
  );
}

// ============================================================
// VIS — Real product screenshot, filling the stage with a slow
// Ken Burns drift so the panel stays alive. Shared by the
// "Pagos locales", "Cuentas empresariales" y "Tesorería" rows.
// ============================================================
function VisShot({ src, alt }) {
  return (
    <div style={{ position: "absolute", inset: 0, overflow: "hidden", background: "#fff", display: "flex", alignItems: "center", justifyContent: "center", padding: 28 }}>
      <img
        src={src}
        alt={alt}
        draggable={false}
        style={{
          maxWidth: "100%",
          maxHeight: "100%",
          width: "auto",
          height: "auto",
          objectFit: "contain",
          display: "block",
          userSelect: "none",
          pointerEvents: "none",
          animation: "shotDrift 24s ease-in-out infinite alternate",
          transformOrigin: "center center",
        }}
      />
      <style>{`
        @keyframes shotDrift {
          from { transform: scale(1.00) translate3d(0, 0, 0); }
          to   { transform: scale(1.02) translate3d(0, -0.4%, 0); }
        }
      `}</style>
    </div>
  );
}

function VisPagosLocales() {
  // Faithful HTML/CSS recreation of the real "Pago local" wizard with
  // native interaction states. Defined in components/LocalesFlow.jsx.
  return <LocalesFlow/>;
}
function VisPagosMasivos() {
  // Placeholder dispersión-masiva flow in the same visual language as
  // LocalesFlow. Defined in components/MasivosFlow.jsx (swap when the
  // real choreography is defined).
  return <MasivosFlow/>;
}
function VisCuentasEmpresariales() {
  // Faithful HTML/CSS recreation of the real Meefi web app navigation
  // (Dashboard → Cuentas → Detalle). Defined in components/CuentasFlow.jsx.
  return <CuentasFlow/>;
}
function VisTesoreria() {
  // Faithful HTML/CSS recreation of the Tesorería accounts table with a
  // focus spotlight that walks account-by-account. See TesoreriaFlow.jsx.
  return <TesoreriaFlow/>;
}
function VisMultidivisa() {
  // Carousel of the real "Balance en Meefi" dashboard card, rotating the
  // same window across MXN · USD · EUR · GBP · CNY. See MultidivisaFlow.jsx.
  return <MultidivisaFlow/>;
}
function VisGlobeEarth() {
  // Realistic orthographic Earth (SPEI-style), zoomed to bleed past the
  // window and spinning faster. See FeatureGlobe.jsx.
  return <FeatureGlobe/>;
}

// ============================================================
// VIS 3 — Growing bar chart / cobranza
// ============================================================
function VisCobranza() {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 1700);
    return () => clearInterval(id);
  }, []);
  const seed = [42, 68, 55, 82, 71, 95];
  const heights = seed.map((s, i) => 30 + ((s + tick * 4) % 70));

  return (
    <div style={{ position: "absolute", inset: 0, padding: 28, display: "flex", flexDirection: "column" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 10 }}>
        <div>
          <div style={{ fontSize: 11, color: "var(--fg-3)" }}>Cobrado esta semana</div>
          <div style={{ fontSize: 22, fontWeight: 500, color: "var(--fg-1)", fontFamily: "var(--font-display)", letterSpacing: "-0.02em" }}>
            $1.84M
          </div>
        </div>
        <div style={{
          fontSize: 10, padding: "3px 8px", borderRadius: 999,
          background: "#E8F5EE", color: "var(--success)", fontWeight: 500,
          display: "flex", alignItems: "center", gap: 4,
        }}>
          <Icons.TrendingUp size={10} stroke={2.5}/> +18%
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "flex-end", gap: 6, flex: 1, minHeight: 0 }}>
        {heights.map((h, i) => (
          <div
            key={i}
            style={{
              flex: 1,
              height: `${h}%`,
              background: i === heights.length - 1
                ? "var(--accent)"
                : "linear-gradient(180deg, rgba(5,48,206,0.55), rgba(5,48,206,0.18))",
              borderRadius: "6px 6px 2px 2px",
              transition: "height 1000ms var(--ease-out-soft)",
            }}
          />
        ))}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, fontSize: 9, color: "var(--fg-3)" }}>
        {["L","M","M","J","V","S"].map((d, i) => <span key={i}>{d}</span>)}
      </div>
    </div>
  );
}

// ============================================================
// VIS 4 — Checklist ticking
// ============================================================
function VisConcilia() {
  const items = [
    "PPD #4821 · Cliente Norte",
    "PUE #4822 · Logística MX",
    "Complemento de pago · 4821",
    "PPD #4823 · Importadora Sur",
  ];
  const [done, setDone] = useState(0);
  useEffect(() => {
    const id = setInterval(() => {
      setDone((d) => (d + 1) % (items.length + 1));
    }, 1300);
    return () => clearInterval(id);
  }, []);
  return (
    <div style={{ position: "absolute", inset: 0, padding: 28, display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div style={{
        width: "100%", maxWidth: 340,
        background: "rgba(255,255,255,0.92)",
        border: "1px solid rgba(17,24,39,0.05)",
        borderRadius: 16,
        padding: 18,
        boxShadow: "0 10px 28px -8px rgba(27,31,38,0.10)",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 12 }}>
          <span style={{ fontSize: 12, fontWeight: 500, color: "var(--fg-1)" }}>Conciliación automática</span>
          <span style={{ fontSize: 11, color: "var(--fg-3)" }}>{done}/{items.length}</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {items.map((it, i) => {
            const isDone = i < done;
            return (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 10,
                padding: "8px 10px", borderRadius: 8,
                background: isDone ? "rgba(5,48,206,0.04)" : "transparent",
                transition: "background 350ms ease",
              }}>
                <span style={{
                  width: 16, height: 16, borderRadius: 999,
                  background: isDone ? "var(--accent)" : "rgba(229,231,235,0.7)",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  transition: "all 350ms var(--ease-out-soft)",
                }}>
                  {isDone && <Icons.Check size={10} stroke={3} color="#fff"/>}
                </span>
                <span style={{
                  fontSize: 11.5,
                  color: isDone ? "var(--fg-1)" : "var(--fg-2)",
                  textDecoration: isDone ? "none" : "none",
                  flex: 1,
                  fontWeight: isDone ? 500 : 400,
                }}>{it}</span>
                {isDone && <Icons.Check size={11} color="var(--success)" stroke={2.5}/>}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ============================================================
// Features section — Mercury-style accordion list (left) +
// big live visualisation (right). Auto-rotates every ~6s; user
// can click any row to take over (auto-resumes after 12s idle).
// ============================================================
const FEATURES = [
  { Vis: VisGlobeEarth,  title: "Pagos globales",
    description: <>Envía a +70 países<Fn n={3}/> con liquidación el mismo día<Fn n={1}/>. Sin spread oculto.</>,
    badge: "Internacional" },
  { Vis: VisPagosLocales, title: "Pagos locales", dur: 12000,
    description: "Envía un SPEI a cualquier banco de México con confirmación en segundos. Sin filas, sin sucursales, sin horarios.",
    badge: "SPEI" },
  { Vis: VisPagosMasivos, title: "Dispersión masiva", dur: 12000,
    description: "Dispersión masiva: paga a decenas de proveedores o tu nómina completa en un solo movimiento, sin cargar uno por uno.",
    badge: "Dispersión" },
  { Vis: VisCuentasEmpresariales, title: "Cuentas empresariales", dur: 11000,
    description: "Cuenta CLABE en MXN para tu PyME, sin sucursales ni trámites presenciales.",
    badge: "CLABE" },
  { Vis: VisTesoreria, title: "Tesorería", dur: 6200,
    description: "Visibilidad de saldos, flujos y posiciones en tiempo real. Toma decisiones con información, no con suposiciones.",
    badge: "Tesorería" },
  { Vis: VisMultidivisa, title: "Multidivisa", dur: 9600,
    description: "Opera en USD, MXN, EUR, GBP y CNY desde la misma plataforma.",
    badge: "FX" },
];

const ROTATE_MS  = 5500;   // default auto-rotate (per-feature `dur` overrides)
const featDur = (i) => FEATURES[i].dur || ROTATE_MS;

function FeaturesAccordion() {
  const gridRef = useRef(null);
  const [active, setActive] = useState(0);
  const [inView, setInView] = useState(false);
  // versions[i] increments each time feature i becomes active —
  // bumping the key on its <Vis/> remounts the component, resetting
  // its internal animation timer from zero.
  const [versions, setVersions] = useState(() => FEATURES.map(() => 0));

  // Bump version of whichever feature just became active
  useEffect(() => {
    if (active < 0) return;
    setVersions((v) => {
      const next = v.slice();
      next[active] = next[active] + 1;
      return next;
    });
  }, [active]);

  // Always (re)start from the FIRST option whenever the section
  // enters the viewport.
  useEffect(() => {
    const el = gridRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([e]) => {
        if (e.isIntersecting) {
          setActive(0);
          setVersions((v) => { const n = v.slice(); n[0] = n[0] + 1; return n; });
          setInView(true);
        } else {
          setInView(false);
        }
      },
      { threshold: 0.25 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Auto-advance — the timer resets on every `active` change, so
  // picking a row just continues the flow starting from that option.
  useEffect(() => {
    if (!inView || active < 0) return;
    const id = setTimeout(() => {
      setActive((i) => (i + 1) % FEATURES.length);
    }, featDur(active));
    return () => clearTimeout(id);
  }, [active, inView]);

  // Clicking a row selects it and keeps the auto-flow running from there.
  const pick = (i) => {
    setActive(i);
  };

  return (
    <div
      ref={gridRef}
      className="reveal feat-grid"
      style={{
        display: "grid",
        gridTemplateColumns: "minmax(560px, 1fr) min(70vw, 1200px)",
        gap: 0,
        alignItems: "center",
      }}
    >
      {/* LEFT — FAQ-style accordion list (centered within the full blue band) */}
      <div style={{ width: "100%", maxWidth: 480, margin: "0 auto" }}>
        {FEATURES.map((f, i) => {
          const isOpen = active === i;
          return (
            <div
              key={i}
              className={`feat-row ${isOpen ? "is-open" : ""}`}
            >
              <button
                className="feat-q"
                data-hover="1"
                onClick={() => pick(i)}
              >
                <span className="feat-q-title">{f.title}</span>
                <span className="feat-icon">
                  <Icons.Plus size={14} stroke={2}/>
                </span>
              </button>
              <div className="feat-a">
                <div className="feat-a-inner">
                  <p>{f.description}</p>
                  {isOpen && inView && (
                    <span className="feat-progress" aria-hidden="true">
                      <span
                        key={`prog-${i}-${versions[i]}`}
                        className="feat-progress-fill"
                        style={{ animation: `featProgress ${featDur(i)}ms linear forwards` }}
                      />
                    </span>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* RIGHT — big live visualisation */}
      <div className="feat-stage-wrap">
        <div className="feat-stage">
          {FEATURES.map((f, i) => {
            const Vis = f.Vis;
            return (
              <div
                key={i}
                className="feat-stage-slot"
                style={{
                  opacity: active === i ? 1 : 0,
                  transform: active === i ? "scale(1)" : "scale(0.985)",
                  pointerEvents: active === i ? "auto" : "none",
                }}
              >
                {/* Only mount the Vis when active; remount on each activation
                    so the inner animation always plays from t=0. */}
                {active === i && <Vis key={versions[i]}/>}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function FeaturesSection() {
  return (
    <section className="features-dark" data-screen-label="Features" style={{ background: "transparent", position: "relative", overflow: "hidden", isolation: "isolate" }}>
      <div className="features-ambient" aria-hidden="true"/>
      <div className="wrap" style={{ position: "relative", zIndex: 1 }}>
        <SectionHeading
          eyebrow="Features"
          statement="La banca tradicional te pone límites,"
          twist="Meefi te quita los frenos."
        />

        <FeaturesAccordion/>

        {/* Inline pull quote */}
        <div className="reveal" style={{
          marginTop: 96, maxWidth: 720, marginLeft: "auto", marginRight: "auto", textAlign: "center",
        }}>
          <blockquote className="feat-quote" style={{
            margin: 0, fontFamily: "var(--font-display)",
            fontSize: 24, fontWeight: 500,
            lineHeight: 1.45, letterSpacing: "-0.015em", marginBottom: 28,
          }}>
            "Gracias a Meefi hemos ahorrado 20 horas en cierres de mes;
            es una plataforma muy fácil de usar."
          </blockquote>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 12 }}>
            <img
              src="assets/client-logos/paccocsa.png"
              alt="Paccocsa"
              style={{ width: 42, height: 42, borderRadius: 999, objectFit: "contain", padding: 4, background: "rgba(140,160,246,0.10)" }}
            />
            <div style={{ textAlign: "left" }}>
              <p className="feat-quote-name" style={{ margin: 0, fontSize: 14, fontWeight: 500 }}>Patricia Chora</p>
              <p className="feat-quote-role" style={{ margin: 0, fontSize: 12 }}>CFO, Paccocsa</p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
window.FeaturesSection = FeaturesSection;
