// Home view — the "scene": ALT keycap as hero + live transcription + recent list.

const { useState: uS_h, useEffect: uE_h, useRef: uR_h } = React;

function HomeView({ density, variation }) {
  const [pressed, setPressed] = uS_h(false);
  const [liveText, setLiveText] = uS_h("");
  const [tick, setTick] = uS_h(0);
  const intervalRef = uR_h(null);
  const phrases = [
    "Hey team — quick update on the onboarding flow.",
    "The activation rate hinges on that first dictation feeling instant.",
    "If there's any perceived latency in the first 200ms, users drop off.",
    "We should ship the pre-warmed model path this sprint.",
  ];
  const [phraseIdx, setPhraseIdx] = uS_h(0);

  uE_h(() => {
    const onDown = (e) => {
      if (e.altKey || e.key === "Alt") setPressed(true);
    };
    const onUp = (e) => {
      if (e.key === "Alt" || !e.altKey) setPressed(false);
    };
    window.addEventListener("keydown", onDown);
    window.addEventListener("keyup", onUp);
    return () => {
      window.removeEventListener("keydown", onDown);
      window.removeEventListener("keyup", onUp);
    };
  }, []);

  uE_h(() => {
    if (!pressed) {
      setLiveText("");
      clearInterval(intervalRef.current);
      return;
    }
    const phrase = phrases[phraseIdx % phrases.length];
    let i = 0;
    setLiveText("");
    intervalRef.current = setInterval(() => {
      i += 1;
      setLiveText(phrase.slice(0, i));
      if (i >= phrase.length) {
        clearInterval(intervalRef.current);
      }
    }, 35);
    return () => clearInterval(intervalRef.current);
  }, [pressed, phraseIdx]);

  uE_h(() => {
    const id = setInterval(() => setTick((t) => t + 1), 90);
    return () => clearInterval(id);
  }, []);

  const handleClickKey = () => {
    setPressed((p) => {
      if (p) {
        setPhraseIdx((i) => i + 1);
      }
      return !p;
    });
  };

  const pad = density === "compact" ? 24 : density === "airy" ? 56 : 36;

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        height: "100%",
        overflowY: "auto",
        position: "relative",
      }}
    >
      {/* Canvas top-right — words transcribed stat */}
      <div style={{ position: "absolute", top: 18, right: 20, display: "flex", alignItems: "baseline", gap: 6, zIndex: 2 }}>
        <span style={{ fontSize: 15, fontWeight: 500, color: "var(--ink)", letterSpacing: "-0.01em" }}>184</span>
        <span style={{ fontSize: 11.5, color: "var(--ink-mute)", letterSpacing: "0.02em" }}>words transcribed</span>
      </div>
      {/* Top-left — time saved stat */}
      <div style={{ position: "absolute", top: 18, left: 20, display: "flex", alignItems: "baseline", gap: 6, zIndex: 2 }}>
        <span style={{ fontSize: 15, fontWeight: 500, color: "var(--ink)", letterSpacing: "-0.01em" }}>42 min</span>
        <span style={{ fontSize: 11.5, color: "var(--ink-mute)", letterSpacing: "0.02em" }}>saved this week</span>
      </div>
      {/* HERO */}
      <section
        style={{
          padding: `${pad}px ${pad + 8}px ${pad}px`,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          gap: density === "compact" ? 18 : 28,
          borderBottom: "1px solid var(--line-soft)",
        }}
      >
        <div style={{ textAlign: "center", maxWidth: 560, width: "100%" }}>
          <div
            style={{
              fontSize: 11.5,
              color: "var(--ink-mute)",
              letterSpacing: "0.08em",
              textTransform: "uppercase",
              fontWeight: 500,
              marginBottom: 10,
            }}
          >
            {pressed ? "Listening" : "Ready"}
          </div>
          <h1
            style={{
              margin: 0,
              fontSize: variation === "quiet" ? 22 : 26,
              fontWeight: 500,
              letterSpacing: "-0.02em",
              lineHeight: 1.35,
              color: "var(--ink)",
              display: "inline-flex",
              alignItems: "center",
              gap: 10,
              justifyContent: "center",
              whiteSpace: "nowrap",
            }}
          >
            {pressed ? (
              <>
                <span>Hold</span>
                <span style={{ color: "var(--ink-mute)", display: "inline-flex", alignItems: "center", gap: 6 }}>
                  <AltGlyphInline size={18} />Alt
                </span>
                <span>, keep talking.</span>
              </>
            ) : (
              <>
                <span>Hold</span>
                <KeycapInlineAlt />
                <span>and speak.</span>
              </>
            )}
          </h1>
          <p
            style={{
              margin: "8px 0 0",
              fontSize: 13.5,
              color: "var(--ink-mute)",
              lineHeight: 1.5,
            }}
          >
            Your words appear at the cursor wherever you are. Release to paste.
          </p>
        </div>

        {/* The Alt keycap stage */}
        <div
          style={{
            position: "relative",
            padding: "20px 40px 16px",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          {/* pulse ring */}
          {pressed && (
            <span
              style={{
                position: "absolute",
                width: 110,
                height: 110,
                borderRadius: 22,
                border: "1.5px solid rgba(2,2,2,.18)",
                animation: "pulseRing 1200ms ease-out infinite",
                pointerEvents: "none",
              }}
            />
          )}
          <div
            onMouseDown={handleClickKey}
            onMouseUp={() => {}}
            onClick={(e) => e.preventDefault()}
            style={{ cursor: "pointer", userSelect: "none" }}
          >
            <Keycap label={<AltGlyph size={56} />} width={88} height={88} pressed={pressed} />
          </div>
        </div>

        {/* Live transcription OR a quiet status */}
        <div
          style={{
            width: "min(640px, 100%)",
            minHeight: 64,
            padding: "14px 18px",
            borderRadius: 18,
            background: pressed ? "#fff" : "transparent",
            border: "none",
            transition: "all 180ms ease",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: 14,
          }}
        >
          {pressed ? (
            <>
              <WaveformMini tick={tick} />
              <div
                style={{
                  flex: 1,
                  fontSize: 15,
                  lineHeight: 1.45,
                  color: "var(--ink)",
                  minHeight: 22,
                }}
              >
                {liveText}
                <span
                  style={{
                    display: "inline-block",
                    width: 2,
                    height: 16,
                    background: "var(--ink)",
                    marginLeft: 2,
                    verticalAlign: -2,
                    animation: "caret 900ms steps(1) infinite",
                  }}
                />
              </div>
              <span
                style={{
                  fontSize: 11,
                  color: "var(--ink-mute)",
                  fontVariantNumeric: "tabular-nums",
                }}
              >
                0:0{Math.min(9, Math.floor(tick / 10))}
              </span>
            </>
          ) : (
            <span
              style={{
                fontSize: 13,
                color: "var(--ink-mute)",
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
              }}
            >
              <span
                style={{
                  width: 6,
                  height: 6,
                  borderRadius: 999,
                  background: "var(--ink-faint)",
                }}
              />
              Press and hold Alt anywhere — even when globefn is hidden.
            </span>
          )}
        </div>
      </section>

      {/* RECENT */}
      <section style={{ padding: `${pad - 8}px ${pad + 8}px ${pad}px` }}>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            marginBottom: 12,
          }}
        >
          <h2
            style={{
              margin: 0,
              fontSize: 13,
              fontWeight: 500,
              color: "var(--ink-mute)",
              letterSpacing: "0.04em",
              textTransform: "uppercase",
            }}
          >
            Recent dictations
          </h2>
          <div style={{ display: "flex", gap: 6 }}>
            <Pill compact>Today</Pill>
            <Pill compact>This week</Pill>
            <Pill compact>All</Pill>
          </div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          {TRANSCRIPTIONS.map((t) => (
            <TranscriptionRow key={t.id} item={t} variation={variation} />
          ))}
        </div>
      </section>
    </div>
  );
}

// Inline Alt keycap used in the H1 — a miniature flat keycap with the ⌥ glyph
function KeycapInlineAlt() {
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        width: 34,
        height: 30,
        borderRadius: 6,
        background: "#ffffff",
        border: "1px solid rgba(0,0,0,0.14)",
        boxShadow: "0 1.5px 0 rgba(0,0,0,0.08)",
        color: "var(--ink)",
      }}
    >
      <AltGlyphInline size={16} />
    </span>
  );
}

function WaveformMini({ tick }) {
  const bars = 5;
  return (
    <div style={{ display: "flex", gap: 2, alignItems: "center", height: 18 }}>
      {Array.from({ length: bars }).map((_, i) => {
        const h = 4 + Math.abs(Math.sin(tick * 0.3 + i * 0.9)) * 14;
        return (
          <span
            key={i}
            style={{
              width: 2.5,
              height: h,
              borderRadius: 2,
              background: "var(--ink)",
              transition: "height 90ms linear",
            }}
          />
        );
      })}
    </div>
  );
}

function TranscriptionRow({ item, variation }) {
  const [hover, setHover] = uS_h(false);
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        padding: "14px 14px",
        borderRadius: 18,
        background: hover ? "#fff" : "transparent",
        border: "none",
        display: "flex",
        alignItems: "flex-start",
        gap: 14,
        transition: "all 120ms ease",
        cursor: "default",
      }}
    >
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "flex-start",
          gap: 2,
          minWidth: 72,
          paddingTop: 1,
        }}
      >
        <span
          style={{
            fontSize: 11.5,
            color: "var(--ink-mute)",
            fontVariantNumeric: "tabular-nums",
          }}
        >
          {item.time}
        </span>
        <span style={{ fontSize: 10.5, color: "var(--ink-faint)" }}>
          {item.duration} · {item.words}w
        </span>
      </div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div
          style={{
            fontSize: 14,
            lineHeight: 1.5,
            color: "var(--ink)",
            overflow: "hidden",
            textOverflow: "ellipsis",
            display: "-webkit-box",
            WebkitLineClamp: 2,
            WebkitBoxOrient: "vertical",
          }}
        >
          {item.text}
        </div>
        <div
          style={{
            fontSize: 11,
            color: "var(--ink-mute)",
            marginTop: 4,
            display: "flex",
            alignItems: "center",
            gap: 6,
          }}
        >
          <span
            style={{
              width: 5,
              height: 5,
              borderRadius: 999,
              background: "var(--ink-faint)",
            }}
          />
          Pasted into {item.app}
        </div>
      </div>

      <div
        style={{
          display: "flex",
          gap: 2,
          opacity: hover ? 1 : 0,
          transition: "opacity 120ms ease",
        }}
      >
        <IconButton icon={<Ic.copy width="14" height="14" />} title="Copy" size={26} />
        <IconButton icon={<Ic.trash width="14" height="14" />} title="Delete" size={26} />
      </div>
    </div>
  );
}

window.HomeView = HomeView;
