/* global React */

function TypingDots() {
  return (
    <div style={{ padding: "10px 14px", background: "var(--cream)", border: "1px solid var(--rule)", borderRadius: "12px 12px 12px 2px", alignSelf: "flex-start", display: "flex", gap: 5, alignItems: "center" }}>
      {[0, 1, 2].map(i => (
        <span key={i} style={{
          width: 6, height: 6, borderRadius: "50%", background: "var(--muted)",
          display: "block",
          animation: `portal-dot 1.2s ease-in-out ${i * 0.2}s infinite`
        }} />
      ))}
    </div>
  );
}

function Portal() {
  const chatRef = React.useRef(null);
  const [step, setStep] = React.useState(0);

  React.useEffect(() => {
    const el = chatRef.current;
    if (!el) return;
    const timers = [];
    const obs = new IntersectionObserver(([entry]) => {
      if (!entry.isIntersecting) return;
      obs.disconnect();
      timers.push(setTimeout(() => setStep(1), 600));   // client msg
      timers.push(setTimeout(() => setStep(2), 1900));  // typing dots
      timers.push(setTimeout(() => setStep(3), 3400));  // bolder reply
      timers.push(setTimeout(() => setStep(4), 4600));  // desert image
      timers.push(setTimeout(() => setStep(5), 5000));  // status update
    }, { threshold: 0.4 });
    obs.observe(el);
    return () => { obs.disconnect(); timers.forEach(clearTimeout); };
  }, []);

  const anim = (visible, fromRight = false) => ({
    transition: "opacity 450ms ease, transform 450ms ease",
    opacity: visible ? 1 : 0,
    transform: visible ? "translateY(0)" : `translateY(${fromRight ? "-" : ""}8px)`,
    pointerEvents: visible ? "auto" : "none",
  });

  const statusItems = [
    { l: "Briefing validado",  done: true,           active: false },
    { l: "Curadoria IA [V01]", done: true,            active: false },
    { l: "Refinamento [V02]",  done: step >= 5,       active: step >= 1 && step < 5 },
    { l: "Entrega final",      done: false,           active: step >= 5 },
  ];

  return (
    <Section id="connected" tone="cream">
      <SectionHead
        num="09 / Plataforma"
        tag={<BeTag name="Connected" size="lg" />}
        title="Onde <em>tudo</em> vive."
        sub="Distância zero entre ideia e asset final. Briefing, revisões, downloads, tokens, todos no mesmo portal. Powered by Boldy."
      />

      <Reveal>
        <div className="card" style={{ padding: 0, overflow: "hidden", background: "var(--paper)" }}>

          {/* ── Barra de título ── */}
          <div style={{ display: "flex", justifyContent: "space-between", padding: "14px 20px", borderBottom: "1px solid var(--rule)", background: "var(--cream)" }}>
            <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
              <span style={{ width: 9, height: 9, borderRadius: "50%", background: "#D4D2C8" }} />
              <span style={{ width: 9, height: 9, borderRadius: "50%", background: "#D4D2C8" }} />
              <span style={{ width: 9, height: 9, borderRadius: "50%", background: "var(--coral)" }} />
              <span className="mono mono-ink" style={{ marginLeft: 12 }}>Be Connected · primavera_26</span>
            </div>
            <PoweredByBoldy />
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "200px 1fr 280px", minHeight: 480 }} className="portal-grid">

            {/* ── Sidebar ── */}
            <aside style={{ borderRight: "1px solid var(--rule)", padding: 20 }}>
              <span className="mono">Workspace</span>
              <ul style={{ listStyle: "none", padding: 0, margin: "12px 0", fontSize: 13.5, display: "flex", flexDirection: "column", gap: 4 }}>
                <li style={{ padding: "8px 10px", background: "var(--coral)", color: "#FFF", borderRadius: 6 }}>→ Projetos ativos</li>
                <li style={{ padding: "8px 10px", color: "var(--muted)" }}>Biblioteca</li>
                <li style={{ padding: "8px 10px", color: "var(--muted)" }}>Tokens · histórico</li>
                <li style={{ padding: "8px 10px", color: "var(--muted)" }}>Be Informed</li>
              </ul>
              <div style={{ borderTop: "1px solid var(--rule)", paddingTop: 14, marginTop: 16 }}>
                <span className="mono">Tokens · Abr</span>
                <div className="display" style={{ fontSize: 32, letterSpacing: "-0.03em", lineHeight: 1, marginTop: 4 }}>
                  38<span className="mono" style={{ color: "var(--muted)" }}>/50</span>
                </div>
                <div style={{ height: 4, background: "var(--rule)", marginTop: 10, borderRadius: 999 }}>
                  <div style={{ width: "76%", height: "100%", background: "var(--coral)", borderRadius: 999 }} />
                </div>
              </div>
            </aside>

            {/* ── Chat ── */}
            <main ref={chatRef} style={{ padding: 24, display: "flex", flexDirection: "column", gap: 14, overflow: "hidden" }}>
              <span className="mono mono-ink">Canal · #042 Primavera_26</span>

              {/* M. Lopes — V01 */}
              <div style={{ padding: "10px 14px", background: "var(--cream)", border: "1px solid var(--rule)", borderRadius: "12px 12px 12px 2px", alignSelf: "flex-start", maxWidth: "70%", fontSize: 13.5 }}>
                <span className="mono" style={{ display: "block", marginBottom: 4 }}>M. Lopes · 14:02</span>
                V01 da campanha. Iluminação ok?
              </div>

              {/* V01 image — sempre visível */}
              <div style={{ borderRadius: 8, overflow: "hidden", alignSelf: "flex-start", width: "calc(50% - 5px)" }}>
                <img
                  src={(window.BOLDER_MEDIA_URL || '') + 'images/TABLET_1.png'}
                  alt="Bolder Platform V01"
                  style={{ width: "100%", aspectRatio: "4/3", objectFit: "cover", display: "block" }}
                />
              </div>

              {/* Cliente — entra ao step 1 */}
              <div style={{ ...anim(step >= 1, true), padding: "10px 14px", background: "var(--coral)", color: "#FFF", borderRadius: "12px 12px 2px 12px", alignSelf: "flex-end", maxWidth: "70%", fontSize: 13.5 }}>
                <span className="mono" style={{ display: "block", marginBottom: 4, color: "rgba(255,255,255,0.7)" }}>Cliente · 14:08</span>
                Adoro. Testar no cenário do deserto?
              </div>

              {/* Typing dots — step 2 e 3 */}
              <div style={anim(step >= 2 && step < 4)}>
                <TypingDots />
              </div>

              {/* M. Lopes reply — step 3 */}
              <div style={{ ...anim(step >= 3), padding: "10px 14px", background: "var(--cream)", border: "1px solid var(--rule)", borderRadius: "12px 12px 12px 2px", alignSelf: "flex-start", maxWidth: "70%", fontSize: 13.5 }}>
                <span className="mono" style={{ display: "block", marginBottom: 4 }}>M. Lopes · 14:09</span>
                A gerar variante deserto, já a chegar...
              </div>

              {/* V02 desert — step 4 */}
              <div style={{ ...anim(step >= 4), position: "relative", alignSelf: "flex-start", width: "calc(50% - 5px)", borderRadius: 8, overflow: "hidden" }}>
                <img
                  src={(window.BOLDER_MEDIA_URL || '') + 'images/TABLET_2.png'}
                  alt="Bolder Platform V02 — Desert"
                  style={{ width: "100%", aspectRatio: "4/3", objectFit: "cover", display: "block" }}
                />
                <div style={{ position: "absolute", inset: 0, borderRadius: 8, border: "1.5px dashed var(--coral)" }} />
              </div>
            </main>

            {/* ── Status ── */}
            <aside style={{ borderLeft: "1px solid var(--rule)", padding: 20, background: "var(--cream)" }}>
              <span className="mono mono-ink">Status</span>
              <ol style={{ listStyle: "none", padding: 0, margin: "14px 0", display: "flex", flexDirection: "column", gap: 12, fontSize: 13 }}>
                {statusItems.map((s, i) => (
                  <li key={i} style={{
                    display: "flex", gap: 10, alignItems: "center",
                    opacity: s.done || s.active ? 1 : 0.35,
                    transition: "opacity 400ms ease",
                  }}>
                    <span style={{
                      width: 18, height: 18, borderRadius: "50%", flexShrink: 0,
                      background: s.done ? "var(--coral)" : "transparent",
                      border: s.active ? "1.5px solid var(--coral)" : s.done ? "none" : "1px solid var(--rule-strong)",
                      color: "#FFF", display: "grid", placeItems: "center", fontSize: 10,
                      transition: "background 400ms ease, border 400ms ease",
                    }}>
                      {s.done ? "✓" : ""}
                    </span>
                    {s.l}
                  </li>
                ))}
              </ol>
              <div style={{ paddingTop: 16, borderTop: "1px solid var(--rule)" }}>
                <HumanVerifiedBadge id="HV-2026-0042" />
              </div>
            </aside>

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

      <style>{`
        @keyframes portal-dot {
          0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }
          30%            { opacity: 1;    transform: translateY(-3px); }
        }
        @media (max-width: 900px) {
          .portal-grid { grid-template-columns: 1fr !important; }
          .portal-grid > aside { border: none !important; border-bottom: 1px solid var(--rule) !important; }
        }
      `}</style>
    </Section>
  );
}

window.Portal = Portal;
