// VeryPay — System (Network Graph)
function System() {
  const nodes = [
    {
      id: "taxa",
      label: "Taxa otimizada",
      title: "Taxa otimizada por perfil",
      desc: "Negociamos sua taxa caso a caso. Quanto mais o seu negócio cresce, melhor a sua taxa fica — sem você precisar pedir.",
      icon: "tag",
      angle: -90
    },
    {
      id: "antec",
      label: "Antecipação inteligente",
      title: "Antecipação inteligente",
      desc: "Antecipamos quando faz sentido pro seu caixa, não quando faz sentido pra adquirente. Critério, não automatismo.",
      icon: "fast",
      angle: -30
    },
    {
      id: "split",
      label: "Split de pagamento",
      title: "Split de pagamento",
      desc: "Configuração e gestão do split entre sócios, fornecedores, marketplaces ou plataformas. Conciliação automática.",
      icon: "split",
      angle: 30
    },
    {
      id: "conta",
      label: "Conta integrada",
      title: "Conta integrada",
      desc: "Saldo da maquininha cai direto na sua conta VeryPay. Pix, boletos, transferências, rendimento automático.",
      icon: "wallet",
      angle: 90
    },
    {
      id: "rel",
      label: "Relatórios que conversam",
      title: "Relatórios que conversam",
      desc: "Dashboard mensal com o que importa: faturamento por canal, custo real do recebimento, oportunidades não exploradas.",
      icon: "chart",
      angle: 150
    },
    {
      id: "time",
      label: "Time consultivo",
      title: "Time consultivo",
      desc: "Especialista atribuído. Não é call center. Quem te atende sabe seu negócio pelo nome.",
      icon: "people",
      angle: 210
    }
  ];

  // extra cross-connections (besides node↔center)
  const crossLinks = [
    ["taxa", "antec"],
    ["split", "conta"],
    ["conta", "rel"],
    ["rel", "time"],
    ["antec", "rel"]
  ];

  const [hovered, setHovered] = useState(null);
  const [pinned, setPinned] = useState("taxa");
  const stageRef = useRef(null);
  const stageInView = useInView(stageRef, { threshold: 0.2 });
  const [openMobile, setOpenMobile] = useState("taxa");

  const active = hovered || pinned;
  const activeNode = nodes.find(n => n.id === active);

  // node positions
  const positions = nodes.map(n => {
    const rad = (n.angle * Math.PI) / 180;
    const r = 38; // percent of half-shorter side
    return { x: 50 + Math.cos(rad) * r, y: 50 + Math.sin(rad) * r };
  });

  // connections
  const links = [
    ...nodes.map((n, i) => ({ a: { x: 50, y: 50 }, b: positions[i], from: "center", to: n.id })),
    ...crossLinks.map(([a, b]) => {
      const ai = nodes.findIndex(n => n.id === a);
      const bi = nodes.findIndex(n => n.id === b);
      return { a: positions[ai], b: positions[bi], from: a, to: b };
    })
  ];

  return (
    <section id="sistema" className="dark halo-magenta" style={{ overflow: "hidden" }}>
      <div className="container">
        <SectionMeta label="O SISTEMA" index="06" />
        <h2 className="display" style={{ maxWidth: "14ch" }}>
          <Reveal>Não é uma feature.</Reveal>
          <br />
          <Reveal delay={0.1}>É um <UnderlineMagenta>sistema</UnderlineMagenta>.</Reveal>
        </h2>
        <p style={{ maxWidth: 580, marginTop: 28, fontSize: 18, color: "rgba(255,255,255,0.72)", lineHeight: 1.55 }}>
          Cada solução conecta com as outras. Você não compra produtos isolados — recebe
          uma operação inteira que conversa entre si.
        </p>

        <div className="network-wrap">
          <div
            ref={stageRef}
            className={"network-stage" + ((hovered || (pinned && pinned !== "")) ? " dimmed" : "")}
          >
            {/* SVG lines layer */}
            <svg
              viewBox="0 0 100 100"
              preserveAspectRatio="none"
              style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none" }}
            >
              {links.map((l, i) => {
                const isHi = active && (l.from === active || l.to === active);
                const otherDim = active && !isHi;
                return (
                  <line
                    key={i}
                    x1={l.a.x}
                    y1={l.a.y}
                    x2={l.b.x}
                    y2={l.b.y}
                    stroke={isHi ? "#BA2F7D" : "rgba(238,67,137,0.25)"}
                    strokeWidth={isHi ? "0.28" : "0.12"}
                    opacity={stageInView ? (otherDim ? 0.12 : 1) : 0}
                    style={{
                      transition: "all 0.45s cubic-bezier(.2,.8,.2,1)",
                      transitionDelay: stageInView ? `${0.4 + i * 0.05}s` : "0s"
                    }}
                  />
                );
              })}
            </svg>

            {/* Nodes */}
            <div className="network-node center" style={{ left: "50%", top: "50%" }}>
              <div className="bubble">
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                  <circle cx="12" cy="12" r="9"/>
                  <path d="M8 12h8M12 8v8"/>
                </svg>
              </div>
              <div className="label" style={{ color: "#fff" }}>Seu negócio</div>
            </div>

            {nodes.map((n, i) => (
              <div
                key={n.id}
                className={"network-node" + (active === n.id ? " active" : "")}
                style={{
                  left: positions[i].x + "%",
                  top: positions[i].y + "%",
                  opacity: stageInView ? 1 : 0,
                  transition: `opacity 0.6s ${0.15 + i * 0.08}s, transform 0.5s`,
                }}
                onMouseEnter={() => setHovered(n.id)}
                onMouseLeave={() => setHovered(null)}
                onClick={() => setPinned(n.id)}
                role="button"
                tabIndex={0}
              >
                <div className="bubble">
                  <NodeIcon name={n.icon} />
                </div>
                <div className="label">{n.label}</div>
              </div>
            ))}
          </div>

          {/* Info panel */}
          <div className="network-info">
            <div>
              <div className="tag">SOLUÇÃO {nodes.findIndex(n => n.id === active) + 1 || 1} <Slash /> 06</div>
              <h4>{activeNode?.title}</h4>
              <p>{activeNode?.desc}</p>
            </div>
            <div className="hint">
              <Slash /> Passe o mouse nos nós para ver as conexões
            </div>
          </div>
        </div>

        {/* Mobile constellation — interactive */}
        <MobileConstellation nodes={nodes} active={openMobile} onSelect={setOpenMobile} />
      </div>
    </section>
  );
}

function NodeIcon({ name }) {
  const props = { width: 28, height: 28, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "tag":
      return <svg {...props}><path d="M20.6 13.4 13.4 20.6a2 2 0 0 1-2.8 0L3 13V3h10l7.6 7.6a2 2 0 0 1 0 2.8z"/><circle cx="8" cy="8" r="1.5"/></svg>;
    case "fast":
      return <svg {...props}><path d="M13 2 3 14h7l-1 8 10-12h-7l1-8z"/></svg>;
    case "split":
      return <svg {...props}><path d="M16 3h5v5"/><path d="M4 20 21 3"/><path d="M21 16v5h-5"/><path d="M15 15l6 6"/><path d="M4 4l5 5"/></svg>;
    case "wallet":
      return <svg {...props}><rect x="2" y="6" width="20" height="14" rx="2"/><path d="M16 14h2"/><path d="M2 10h20"/></svg>;
    case "chart":
      return <svg {...props}><path d="M3 3v18h18"/><path d="M7 14l4-4 4 4 5-6"/></svg>;
    case "people":
      return <svg {...props}><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>;
    default:
      return null;
  }
}

window.System = System;

function MobileConstellation({ nodes, active, onSelect }) {
  const activeNode = nodes.find(n => n.id === active) || nodes[0];

  return (
    <div className="mobile-constellation">
      {/* Center pulse */}
      <div className="mc-center">
        <div className="mc-center-bubble">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
            <circle cx="12" cy="12" r="9"/>
            <path d="M8 12h8M12 8v8"/>
          </svg>
        </div>
        <div className="mc-center-label">Seu negócio</div>
      </div>

      {/* Grid of 6 nodes with SVG lines overlay */}
      <div className="mc-grid-wrap">
        <svg className="mc-lines" viewBox="0 0 300 200" preserveAspectRatio="none">
          {/* Center top: x=150, y=-20 (above grid). 6 cells: positions */}
          {[
            { x: 50,  y: 50 },  // top-left
            { x: 150, y: 50 },  // top-mid
            { x: 250, y: 50 },  // top-right
            { x: 50,  y: 150 }, // bot-left
            { x: 150, y: 150 }, // bot-mid
            { x: 250, y: 150 }, // bot-right
          ].map((p, i) => {
            const n = nodes[i];
            if (!n) return null;
            const isActive = active === n.id;
            return (
              <line
                key={n.id}
                x1="150"
                y1="-10"
                x2={p.x}
                y2={p.y}
                stroke={isActive ? "#BA2F7D" : "rgba(238,67,137,0.3)"}
                strokeWidth={isActive ? "1.2" : "0.6"}
                opacity={isActive ? 1 : 0.5}
                style={{ transition: "all 0.4s cubic-bezier(.2,.8,.2,1)" }}
              />
            );
          })}
        </svg>

        <div className="mc-grid">
          {nodes.slice(0, 6).map((n) => (
            <button
              key={n.id}
              type="button"
              className={"mc-node" + (active === n.id ? " active" : "")}
              onClick={() => onSelect(n.id)}
              aria-pressed={active === n.id}
            >
              <span className="mc-node-bubble">
                <NodeIcon name={n.icon} />
              </span>
              <span className="mc-node-label">{n.label}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Detail panel */}
      <div className="mc-panel" key={active}>
        <div className="tag">
          SOLUÇÃO {(nodes.findIndex(n => n.id === active) + 1) || 1} <Slash /> 06
        </div>
        <h4>{activeNode.title}</h4>
        <p>{activeNode.desc}</p>
      </div>
    </div>
  );
}

window.MobileConstellation = MobileConstellation;
