/* FlowAnimation — the cinematic 3-step.
   Auto-cycles through 3 stages: Dictado → Procesamiento IA → Validación y Firma.
   Each stage has its own micro-animation that plays when active.
   A "data pulse" travels along the connector between cards. */

function Waveform() {
  // 32 bars with randomized animation delays + speeds for a believable audio waveform.
  const bars = React.useMemo(() => Array.from({length: 32}, (_,i) => ({
    delay: (Math.random() * 1.5).toFixed(2) + "s",
    dur: (0.6 + Math.random() * 0.6).toFixed(2) + "s",
  })), []);
  return (
    <div className="waveform">
      {bars.map((b, i) => (
        <i key={i} style={{ animationDelay: b.delay, "--wd": b.dur }} />
      ))}
    </div>
  );
}

function NeuralNet() {
  // Two columns of nodes, with crossing connections. Cyan node in the center column is the "AI core".
  const cols = [
    [{x:30, y:40},{x:30, y:90},{x:30, y:140}],
    [{x:120, y:55, c:true},{x:120, y:125, c:true}],
    [{x:210, y:40},{x:210, y:90},{x:210, y:140}],
  ];
  const lines = [];
  cols[0].forEach(a => cols[1].forEach(b => lines.push([a,b])));
  cols[1].forEach(a => cols[2].forEach(b => lines.push([a,b])));
  return (
    <svg className="neural" viewBox="0 0 240 180" preserveAspectRatio="none">
      {lines.map((l, i) => <line key={i} x1={l[0].x} y1={l[0].y} x2={l[1].x} y2={l[1].y} />)}
      {cols.flat().map((n, i) => (
        <circle key={i} className={`node${n.c ? " c" : ""}`} cx={n.x} cy={n.y} r="3.5" style={{animationDelay: (i * 0.18) + "s"}}/>
      ))}
    </svg>
  );
}

function SignedDoc({ active }) {
  return (
    <div className="signed-doc">
      <div className="docline" />
      <div className="docline mid" />
      <div className="docline short" />
      <div className="docline" />
      <div className="docline mid" />
      <div className="docline short" />
      <svg viewBox="0 0 200 50" style={{width:"60%", height:30, marginTop:6}}>
        <path className="sigpath"
          d="M5 35 Q 15 5, 30 30 T 60 25 Q 75 5, 90 35 Q 100 45, 115 22 T 150 30 Q 165 10, 180 28" />
      </svg>
      <div className="stamp" aria-hidden="true">
        <I.Check style={{width:24, height:24, strokeWidth:2.2}}/>
      </div>
    </div>
  );
}

function FlowAnimation({ speed = 1 }) {
  const [active, setActive] = React.useState(0);
  const [tick, setTick] = React.useState(0); // bump to re-trigger animations on same step

  React.useEffect(() => {
    const dwell = 4800 / speed;
    const t = setTimeout(() => {
      setActive(a => (a + 1) % 3);
      setTick(x => x + 1);
    }, dwell);
    return () => clearTimeout(t);
  }, [active, speed]);

  const steps = [
    {
      key: "dict", num: "01", title: "Carga de hallazgos",
      desc: "Dictá los hallazgos clave o cargá tus notas. DeltAi escucha y transcribe en tiempo real.",
      cls: "",
    },
    {
      key: "ai", num: "02", title: "Procesamiento IA",
      desc: "El modelo radiológico estructura el informe completo: técnica, hallazgos y conclusión jerarquizada.",
      cls: "consult",
    },
    {
      key: "sign", num: "03", title: "Validación y firma",
      desc: "Revisá y editá si querés. Validá. El informe queda firmado y disponible en RIS/PACS.",
      cls: "success",
    },
  ];

  return (
    <div className="flow-wrap">
      <div className="flow-stage">
        <div className={`connector c1 ${active === 0 ? "active" : ""}`}><i /></div>
        <div className={`connector c2 ${active === 1 ? "active" : ""}`}><i /></div>

        {/* === Step 1 — Dictado === */}
        <article className={`flow-card ${active === 0 ? "active" : ""}`}>
          <header className="step-head">
            <span className="step-num">{steps[0].num}</span>
            <div>
              <h3>{steps[0].title}</h3>
            </div>
          </header>
          <div className="stage-canvas">
            <div className="stage-dict" key={`d-${tick}-${active === 0}`}>
              <div className="mic">
                <span className="mic-circle"><I.Mic style={{width:18, height:18}}/></span>
                <div className="mic-meta">
                  <span className="who">Dictado · Dra. Pérez</span>
                  <span className="time">00:12 / 02:48</span>
                </div>
              </div>
              <Waveform />
              <div className="dict-lines">
                <span className="dict-line">"RMN de rodilla derecha…"</span>
                <span className="dict-line">"lesión sólida cóndilo interno…"</span>
                <span className="dict-line">"10 × 8 milímetros, márgenes definidos…"</span>
              </div>
            </div>
          </div>
          <p className="step-desc">{steps[0].desc}</p>
        </article>

        {/* === Step 2 — AI === */}
        <article className={`flow-card consult ${active === 1 ? "active" : ""}`}>
          <header className="step-head">
            <span className="step-num">{steps[1].num}</span>
            <div>
              <h3>{steps[1].title}</h3>
            </div>
          </header>
          <div className="stage-canvas">
            <div className="stage-ai" key={`a-${tick}-${active === 1}`}>
              <NeuralNet />
              <div className="ai-overlay">
                <div className="ai-stream">
                  <div className="tag"><i/> Modelo radiológico · DeltAi-R3</div>
                  <div className="line">› Estructurando técnica…</div>
                  <div className="line">› Jerarquizando hallazgos…</div>
                  <div className="line">› Redactando conclusión<span className="blink"/></div>
                </div>
              </div>
            </div>
          </div>
          <p className="step-desc">{steps[1].desc}</p>
        </article>

        {/* === Step 3 — Validation === */}
        <article className={`flow-card success ${active === 2 ? "active" : ""}`}>
          <header className="step-head">
            <span className="step-num">{steps[2].num}</span>
            <div>
              <h3>{steps[2].title}</h3>
            </div>
          </header>
          <div className="stage-canvas">
            <div className="stage-sign" key={`s-${tick}-${active === 2}`}>
              <SignedDoc active={active === 2} />
              <div className="sign-meta">
                <div className="who">
                  <span className="avatar">MP</span>
                  <div>
                    <div className="name">Dra. M. Pérez</div>
                    <div className="lic">MN · 138.420</div>
                  </div>
                </div>
                <span className="saved"><i/> Validado</span>
              </div>
            </div>
          </div>
          <p className="step-desc">{steps[2].desc}</p>
        </article>
      </div>

      <div className="flow-progress" role="tablist" aria-label="Paso activo">
        {[0,1,2].map(i => (
          <i
            key={i}
            className={i === active ? "active" : ""}
            onClick={() => { setActive(i); setTick(x => x+1); }}
            role="tab"
            aria-selected={i === active}
          />
        ))}
      </div>
    </div>
  );
}

window.FlowAnimation = FlowAnimation;
