/* global React */

const _ULA = window.BOLDER_LOCAL_ASSETS || 'assets/';
const DEMO_IMGS = [
  _ULA + 'upload-demo/img-1.jpg',
  _ULA + 'upload-demo/img-2.jpg',
  _ULA + 'upload-demo/img-3.jpg',
  _ULA + 'upload-demo/img-4.webp',
];
const OUTPUT_IMG = _ULA + 'upload-demo/output.png';

function UploadDemo() {
  // phase 0=idle 1=uploading 2=sent 3..6=steps lighting up 7=all done
  const [phase, setPhase]           = React.useState(0);
  const [visible, setVisible]       = React.useState([]);
  const [progress, setProgress]     = React.useState(0);
  const [hiddenSteps, setHiddenSteps] = React.useState([]); // indices of collapsed steps
  const [showOutput, setShowOutput] = React.useState(false);
  const timerRef = React.useRef([]);

  function clearAll() { timerRef.current.forEach(clearTimeout); timerRef.current = []; }

  function runDemo() {
    clearAll();
    setPhase(1); setVisible([]); setProgress(0); setHiddenSteps([]); setShowOutput(false);

    DEMO_IMGS.forEach((_, i) => {
      const t = setTimeout(() => {
        setVisible(v => [...v, i]);
        setProgress(Math.round(((i + 1) / DEMO_IMGS.length) * 100));
      }, 300 + i * 450);
      timerRef.current.push(t);
    });

    const B = 300 + DEMO_IMGS.length * 450; // base offset after uploads

    [
      [B + 400,  () => setPhase(2)],
      [B + 1000, () => setPhase(3)],
      [B + 1900, () => setPhase(4)],
      [B + 2800, () => setPhase(5)],
      [B + 3700, () => setPhase(6)],
      [B + 4400, () => setPhase(7)],
      // steps disappear one by one
      [B + 5000, () => setHiddenSteps([0])],
      [B + 5220, () => setHiddenSteps([0, 1])],
      [B + 5440, () => setHiddenSteps([0, 1, 2])],
      [B + 5660, () => setHiddenSteps([0, 1, 2, 3])],
      // output slides in
      [B + 5950, () => setShowOutput(true)],
      // reset
      [B + 10000, () => { setPhase(0); setVisible([]); setProgress(0); setHiddenSteps([]); setShowOutput(false); }],
    ].forEach(([delay, fn]) => {
      const t = setTimeout(fn, delay);
      timerRef.current.push(t);
    });
  }

  React.useEffect(() => {
    const start = setTimeout(runDemo, 800);
    return () => { clearAll(); clearTimeout(start); };
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  React.useEffect(() => {
    if (phase === 0) { const t = setTimeout(runDemo, 700); timerRef.current.push(t); }
  }, [phase]); // eslint-disable-line react-hooks/exhaustive-deps

  const steps = [
    { n: "01", k: "Ticket criado",     d: "Pedido entra na fila com prioridade e SLA definidos.",                   activeAt: 3 },
    { n: "02", k: "Blueprint analisa", d: "O modelo proprietário interpreta o briefing e aplica o estilo da marca.", activeAt: 4 },
    { n: "03", k: "Produção arranca",  d: "IA gera, humano valida. Cada decisão é registada.",                      activeAt: 5 },
    { n: "04", k: "Entrega + revisão", d: "Assets entregues na plataforma. 2 rondas de revisão incluídas.",         activeAt: 6 },
  ];

  return (
    <Section id="upload-demo" tone="cream">
      <SectionHead
        num="03 / Fluxo"
        title="O pedido entra.<br/><em>O motor arranca.</em>"
        sub="O cliente carrega os assets, define o briefing e envia. A partir daí a Bolder trata de tudo, do Blueprint à entrega."
      />

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32, alignItems: "start" }} className="upload-grid">

        {/* ── ESQUERDA ── */}
        <Reveal>
          <div className="card" style={{ background: "var(--paper)", padding: "clamp(20px,2.5vw,32px)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
              <span className="chip">
                <span className="dot" style={{ background: phase >= 2 ? "#22c55e" : "var(--coral)" }} />
                {phase >= 2 ? "Pedido enviado" : "Novo Pedido · Cliente"}
              </span>
              <span className="mono" style={{ fontSize: 10 }}>BLDR-REQ-2026</span>
            </div>

            <div style={{
              border: `2px dashed ${phase === 1 ? "var(--coral)" : phase >= 2 ? "#22c55e" : "var(--rule-strong)"}`,
              borderRadius: 10, minHeight: 156, padding: 12,
              background: phase === 1 ? "var(--coral-soft)" : phase >= 2 ? "rgba(34,197,94,0.05)" : "transparent",
              transition: "all 400ms var(--easing)",
              display: "flex", flexWrap: "wrap", gap: 8, alignItems: "flex-start"
            }}>
              {visible.length === 0 && phase === 0 && (
                <div style={{ width: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", minHeight: 130, gap: 8 }}>
                  <span style={{ fontSize: 28 }}>↓</span>
                  <span className="mono" style={{ color: "var(--muted)", fontSize: 12 }}>Arrasta ou seleciona ficheiros</span>
                </div>
              )}
              {DEMO_IMGS.map((src, i) => (
                <div key={i} style={{
                  width: 72, height: 72, borderRadius: 6, overflow: "hidden",
                  opacity: visible.includes(i) ? 1 : 0,
                  transform: visible.includes(i) ? "translateY(0) scale(1)" : "translateY(-16px) scale(0.85)",
                  transition: "opacity 350ms ease, transform 350ms cubic-bezier(0.34,1.56,0.64,1)",
                  flexShrink: 0
                }}>
                  <img src={src} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                </div>
              ))}
            </div>

            <div style={{ marginTop: 10, height: 4, background: "var(--rule)", borderRadius: 99, overflow: "hidden" }}>
              <div style={{
                height: "100%", borderRadius: 99,
                width: `${phase >= 2 ? 100 : progress}%`,
                background: phase >= 2 ? "#22c55e" : "var(--coral)",
                transition: "width 300ms ease, background 400ms ease"
              }} />
            </div>
            <span className="mono" style={{ fontSize: 10, color: "var(--muted)", display: "block", marginTop: 4 }}>
              {phase === 0 ? "Aguarda ficheiros" : phase >= 2 ? "✓ Upload completo" : `A carregar… ${progress}%`}
            </span>

            <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ padding: "10px 14px", border: "1px solid var(--rule)", borderRadius: 8, fontSize: 14, background: "#fff" }}>
                <span className="mono" style={{ fontSize: 10, color: "var(--muted)", display: "block", marginBottom: 2 }}>Briefing</span>
                Campanha Verão 2026 · editorial de produto
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                <div style={{ padding: "10px 14px", border: "1px solid var(--rule)", borderRadius: 8, fontSize: 13, background: "#fff" }}>
                  <span className="mono" style={{ fontSize: 10, color: "var(--muted)", display: "block" }}>Tipo</span>
                  Editorial · 1 imagem
                </div>
                <div style={{ padding: "10px 14px", border: "1px solid var(--rule)", borderRadius: 8, fontSize: 13, background: "#fff" }}>
                  <span className="mono" style={{ fontSize: 10, color: "var(--muted)", display: "block" }}>Tokens</span>
                  <span style={{ color: "var(--coral)", fontWeight: 600 }}>1</span>
                  <span style={{ color: "var(--muted)" }}> / 25</span>
                </div>
              </div>
            </div>

            <button onClick={runDemo} style={{
              marginTop: 18, width: "100%", padding: "13px 20px",
              border: "none", borderRadius: 8, cursor: "pointer",
              fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.06em",
              background: phase >= 2 ? "#22c55e" : "var(--ink)", color: "#fff",
              transition: "background 400ms ease",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 8
            }}>
              {phase >= 2 ? "✓ Em produção" : phase === 1 ? "A carregar…" : "Enviar pedido →"}
            </button>
          </div>
        </Reveal>

        {/* ── DIREITA — passos que somem + output ── */}
        <Reveal delay={1}>
          <div style={{ position: "relative" }}>
            <span className="mono mono-ink" style={{ display: "block", marginBottom: 12 }}>O que acontece a seguir</span>

            {/* Steps — colapsam sequencialmente */}
            <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
              {steps.map((s, i) => {
                const active  = phase >= s.activeAt;
                const done    = phase > s.activeAt;
                const hidden  = hiddenSteps.includes(i);
                return (
                  <div key={i} style={{
                    overflow: "hidden",
                    maxHeight: hidden ? 0 : 120,
                    opacity: hidden ? 0 : 1,
                    marginBottom: hidden ? 0 : 12,
                    transform: hidden ? "translateY(-6px) scale(0.97)" : "translateY(0) scale(1)",
                    transition: "max-height 300ms ease, opacity 280ms ease, margin-bottom 300ms ease, transform 280ms ease"
                  }}>
                    <div style={{
                      padding: "13px 16px",
                      border: `1px solid ${done ? "#22c55e" : active ? "var(--coral)" : "var(--rule)"}`,
                      borderRadius: 10,
                      background: done ? "rgba(34,197,94,0.06)" : active ? "var(--coral-soft)" : "transparent",
                      display: "flex", gap: 12, alignItems: "flex-start",
                      transition: "border-color 350ms ease, background 350ms ease"
                    }}>
                      <span className="mono" style={{ fontSize: 11, paddingTop: 2, minWidth: 20, color: done ? "#22c55e" : "var(--coral)" }}>{s.n}_</span>
                      <div style={{ flex: 1 }}>
                        <span className="display" style={{ fontSize: 15, letterSpacing: "-0.01em", display: "block", marginBottom: 2 }}>{s.k}</span>
                        <span style={{ fontSize: 12, color: "var(--muted)" }}>{s.d}</span>
                      </div>
                      <span style={{
                        fontSize: 12, paddingTop: 3,
                        color: done ? "#22c55e" : "var(--coral)",
                        opacity: active ? 1 : 0,
                        transition: "opacity 300ms ease, color 300ms ease"
                      }}>{done ? "✓" : "●"}</span>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Output image — aparece no mesmo espaço */}
            <div style={{
              borderRadius: 12, overflow: "hidden",
              border: "1px solid var(--coral)",
              opacity: showOutput ? 1 : 0,
              maxHeight: showOutput ? 400 : 0,
              transform: showOutput ? "translateY(0) scale(1)" : "translateY(10px) scale(0.98)",
              transition: "opacity 500ms ease, max-height 500ms ease, transform 500ms cubic-bezier(0.34,1.1,0.64,1)"
            }}>
              <div style={{ padding: "10px 14px", background: "var(--paper)", display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "1px solid var(--rule)" }}>
                <span className="chip" style={{ borderColor: "#22c55e", color: "#22c55e" }}>
                  <span className="dot" style={{ background: "#22c55e" }} />Output · 1 token
                </span>
                <HumanVerifiedBadge id="HV-OUT-001" />
              </div>
              <img src={OUTPUT_IMG} alt="Output" style={{ width: "100%", aspectRatio: "4/3", objectFit: "cover", display: "block" }} />
            </div>

          </div>
        </Reveal>
      </div>

      <style>{`
        @media (max-width: 760px) { .upload-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </Section>
  );
}

window.UploadDemo = UploadDemo;
