/* global React, Common */
const { Eyebrow, SectionTitle, SectionLead, Keycap } = Common;
const { useEffect: useSpE, useState: useSpS, useRef: useSpR } = React;

// Speed demo: type race vs Dimmy
function SpeedSection() {
  const [run, setRun] = useSpS(0);
  const [typing, setTyping] = useSpS("");
  const [dimmy, setDimmy] = useSpS("");
  const [tTime, setTTime] = useSpS(0);
  const [dTime, setDTime] = useSpS(0);
  const [phase, setPhase] = useSpS("idle"); // idle | running | done

  const sentence = "Hey team, I think we should ship the new pricing page on Friday.";

  const start = () => {
    setTyping(""); setDimmy(""); setTTime(0); setDTime(0); setPhase("running");
    const startedAt = performance.now();

    // typing simulation: ~60 wpm = ~5 chars/sec → ~16 chars/sec for fast typist
    let ti = 0;
    const tId = setInterval(() => {
      ti++;
      setTyping(sentence.slice(0, ti));
      setTTime(performance.now() - startedAt);
      if (ti >= sentence.length) {
        clearInterval(tId);
      }
    }, 55);

    // dimmy simulation: 380ms thinking, then full paste
    setTimeout(() => {
      setDimmy(sentence);
      setDTime(performance.now() - startedAt);
    }, 380);

    setTimeout(() => setPhase("done"), 4500);
  };

  // auto-loop
  useSpE(() => {
    if (phase !== "idle") return;
    const id = setTimeout(start, 600);
    return () => clearTimeout(id);
  }, [phase]);

  useSpE(() => {
    if (phase === "done") {
      const id = setTimeout(() => setPhase("idle"), 2400);
      return () => clearTimeout(id);
    }
  }, [phase]);

  const fmt = (ms) => `${(ms / 1000).toFixed(2)}s`;

  return (
    <section id="speed" style={{ padding: "120px 32px", position: "relative" }}>
      <div className="container">
        <div style={{
          display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 64, alignItems: "center",
        }} className="speed-grid">
          <div>
            <Eyebrow num={3} color="#FBBF24">speed</Eyebrow>
            <div style={{ height: 16 }}/>
            <SectionTitle>
              Faster than<br/>
              <span style={{ color: "var(--fg-faint)", textDecoration: "line-through", textDecorationColor: "rgba(255,255,255,0.3)" }}>typing</span>{" "}
              you.
            </SectionTitle>
            <p className="reveal" style={{
              marginTop: 20, fontSize: 17, lineHeight: 1.55,
              color: "var(--fg-muted)",
              textWrap: "pretty",
            }}>
              You speak at <strong style={{ color: "var(--fg)" }}>~150 words per minute</strong>.
              You type at <strong style={{ color: "var(--fg)" }}>~40</strong>.
              Dimmy closes that gap with sub-second latency, so the bottleneck is your thinking, not your fingers.
            </p>
            <div className="reveal" style={{ marginTop: 28, display: "flex", flexDirection: "column", gap: 12 }}>
              {[
                ["~380ms", "median round-trip on M1, fully offline"],
                ["~120ms", "transcription with whisper-large-v3-turbo"],
                ["~60 fps", "pill animation on a 2018 ThinkPad"],
                ["~12 MB", "installer size · ~78 MB whisper model"],
              ].map(([k, v]) => (
                <div key={k} style={{
                  display: "flex", alignItems: "baseline", gap: 16,
                  padding: "10px 14px",
                  background: "var(--bg-elev)",
                  border: "1px solid var(--line)",
                  borderRadius: 10,
                }}>
                  <span style={{
                    fontFamily: "var(--font-mono)", fontSize: 16, fontWeight: 600,
                    color: "#FBBF24", minWidth: 90,
                  }}>{k}</span>
                  <span style={{ fontSize: 13, color: "var(--fg-muted)" }}>{v}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="reveal" style={{
            position: "relative",
            background: "linear-gradient(180deg, var(--bg-elev), transparent)",
            border: "1px solid var(--line)",
            borderRadius: 20,
            padding: 28,
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 16 }}>
              <Eyebrow color="#888">live race</Eyebrow>
              <span style={{ flex: 1 }}/>
              <button onClick={start} style={{
                fontFamily: "var(--font-mono)", fontSize: 11,
                color: "var(--fg-muted)", background: "transparent",
                border: "1px solid var(--line-strong)", borderRadius: 6,
                padding: "4px 8px", cursor: "pointer",
              }}>↻ replay</button>
            </div>

            {/* Typing lane */}
            <Lane
              label="typing"
              sub={`~${Math.round(typing.length / 5 / Math.max(0.1, tTime / 60000)) || 0} wpm`}
              color="#888"
              text={typing}
              ghost={sentence}
              time={tTime}
              done={typing === sentence}
              icon={<Keycap size="sm">K</Keycap>}
            />

            <div style={{ height: 12 }}/>

            {/* Dimmy lane */}
            <Lane
              label="dimmy"
              sub="~150 wpm equivalent"
              color="#38BDF8"
              text={dimmy}
              ghost={sentence}
              time={dTime}
              done={!!dimmy}
              icon={
                <span style={{
                  width: 22, height: 22, borderRadius: 99,
                  background: "linear-gradient(135deg, #34D399, #38BDF8, #6366F1)",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  fontSize: 11, color: "white", fontWeight: 700,
                }}>D</span>
              }
            />

            <div style={{
              marginTop: 20, padding: 14,
              background: "rgba(74,222,128,0.06)",
              border: "1px solid rgba(74,222,128,0.16)",
              borderRadius: 10,
              display: "flex", alignItems: "center", gap: 12,
            }}>
              <span style={{ fontSize: 18 }}>⚡</span>
              <span style={{ fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.4 }}>
                Dimmy finished in <strong style={{ color: "#4ADE80", fontFamily: "var(--font-mono)" }}>{fmt(dTime || 380)}</strong>.
                Typing is still going at <strong style={{ color: "var(--fg)", fontFamily: "var(--font-mono)" }}>{fmt(tTime)}</strong>.
              </span>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          .speed-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
        }
      `}</style>
    </section>
  );
}

function Lane({ label, sub, color, text, ghost, time, done, icon }) {
  return (
    <div>
      <div style={{
        display: "flex", alignItems: "center", gap: 10, marginBottom: 8,
      }}>
        {icon}
        <span style={{
          fontFamily: "var(--font-mono)", fontSize: 11, color,
          letterSpacing: "0.08em", textTransform: "uppercase",
        }}>{label}</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-faint)" }}>{sub}</span>
        <span style={{ flex: 1 }}/>
        <span style={{
          fontFamily: "var(--font-mono)", fontSize: 12, color: done ? color : "var(--fg-faint)",
          fontWeight: done ? 600 : 400,
        }}>{(time / 1000).toFixed(2)}s</span>
      </div>
      <div style={{
        position: "relative", padding: "14px 16px",
        background: "rgba(0,0,0,0.4)",
        border: `1px solid ${done ? color + "44" : "var(--line)"}`,
        borderRadius: 10,
        fontSize: 14, fontFamily: "var(--font-sans)",
        color: "var(--fg)",
        minHeight: 48, lineHeight: 1.4,
        transition: "border-color 300ms",
      }}>
        <span>{text}</span>
        {!done && text && <span style={{
          display: "inline-block", width: 2, height: "1em", background: color,
          verticalAlign: "-2px", marginLeft: 1, animation: "caret 0.8s steps(1) infinite",
        }}/>}
        {!text && (
          <span style={{ color: "var(--line-strong)", fontSize: 14 }}>{ghost}</span>
        )}
      </div>
      <div style={{
        height: 2, background: "var(--line)",
        borderRadius: 99, marginTop: 6, overflow: "hidden",
      }}>
        <div style={{
          height: "100%", width: `${Math.min(100, (text.length / ghost.length) * 100)}%`,
          background: color, transition: "width 100ms linear",
        }}/>
      </div>
    </div>
  );
}

window.SpeedSection = SpeedSection;
