/* global React, Common, DimmyTray */
const { Eyebrow, SectionTitle, SectionLead } = Common;
const { useState: useInS, useEffect: useInE, useRef: useInR } = React;

// Hide the pill: side-by-side comparison. Windows tray strip (icon + dot + VU)
// vs macOS menu bar (icon REPLACED by status dot during recording).
function InvisibleSection() {
  const [phase, setPhase] = useInS("idle");      // idle | recording | transcribing | done
  const [level, setLevel] = useInS(0.3);
  const [paused, setPaused] = useInS(false);

  const sectionRef = useInR(null);
  const inViewRef = useInR(true);

  useInE(() => {
    const el = sectionRef.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      inViewRef.current = !!(e && e.isIntersecting);
    }, { threshold: 0.25 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  useInE(() => {
    if (paused) return;
    let timers = [];
    let levelInterval;
    let cancelled = false;
    const wait = (ms) => new Promise((r) => timers.push(setTimeout(r, ms)));

    const cycle = async () => {
      while (!cancelled) {
        if (!inViewRef.current) { await wait(800); continue; }
        await wait(900);
        if (cancelled) return;
        setPhase("recording");
        let target = 0.5;
        levelInterval = setInterval(() => {
          target = Math.max(0.15, Math.min(0.95, target + (Math.random() - 0.5) * 0.4));
          setLevel((l) => l + (target - l) * 0.35);
        }, 80);
        await wait(3000);
        clearInterval(levelInterval);
        setLevel(0);
        if (cancelled) return;
        setPhase("transcribing");
        await wait(1500);
        if (cancelled) return;
        setPhase("done");
        await wait(700);
        if (cancelled) return;
        setPhase("idle");
      }
    };
    cycle();
    return () => {
      cancelled = true;
      timers.forEach(clearTimeout);
      if (levelInterval) clearInterval(levelInterval);
    };
  }, [paused]);

  const states = ["idle", "recording", "transcribing", "done"];
  const stateMeta = {
    idle:         { label: "Idle",         desc: "ready · nothing on screen",            color: "#34D399" },
    recording:    { label: "Recording",    desc: "Win bar tracks volume · Mac icon is the dot", color: "#EF4444" },
    transcribing: { label: "Transcribing", desc: "Win sweeps blue · Mac dot stays blue", color: "#38BDF8" },
    done:         { label: "Done",         desc: "green flash · text was inserted",      color: "#34D399" },
  };
  const meta = stateMeta[phase];

  const Tray = (typeof DimmyTray !== "undefined" ? DimmyTray : window.DimmyTray) || {};
  const { WinTaskbarIcon, MacMenuBarIcon } = Tray;

  return (
    <section ref={sectionRef} style={{ padding: "120px 32px", position: "relative", overflow: "hidden" }}>
      <div style={{
        position: "absolute", inset: 0, pointerEvents: "none",
        background: "radial-gradient(ellipse at 50% 50%, rgba(167,139,250,0.08), transparent 60%)",
      }}/>

      <div className="container" style={{ position: "relative" }}>
        <div className="reveal" style={{ textAlign: "center", marginBottom: 48 }}>
          <Eyebrow num={6} color="#A78BFA">no pill, no problem</Eyebrow>
          <div style={{ height: 16 }}/>
          <SectionTitle align="center" maxWidth={820}>
            Hide the pill.<br/>
            <span className="grad-text">The tray icon takes over.</span>
          </SectionTitle>
          <SectionLead align="center" maxWidth={640}>
            You're presenting on a Zoom call. You're recording a Loom. Or you just don't want a colored pill floating at the edge of your screen all day. Toggle it off. The tray icon does everything the pill did, quietly.
          </SectionLead>
        </div>

        {/* Stage */}
        <div className="reveal" style={{
          maxWidth: 1080, marginInline: "auto",
          padding: "56px 32px",
          background: "linear-gradient(180deg, var(--bg-elev), var(--bg))",
          border: "1px solid var(--line-strong)",
          borderRadius: 18,
          position: "relative",
          overflow: "hidden",
        }}>
          <div style={{
            position: "absolute", inset: 0,
            backgroundImage:
              "repeating-linear-gradient(45deg, rgba(255,255,255,0.015) 0 1px, transparent 1px 14px)," +
              "radial-gradient(ellipse at 80% 0%, rgba(56,189,248,0.06), transparent 50%)",
            pointerEvents: "none",
          }}/>

          <div style={{
            position: "relative",
            display: "grid", gridTemplateColumns: "1fr 1fr", gap: 48, alignItems: "center",
          }} className="invisible-grid">
            {/* LEFT: Windows taskbar (pinned apps zone, Dimmy lives here) */}
            <div>
              <Caption text="Windows · taskbar"/>
              <div style={{
                display: "inline-flex", alignItems: "center", gap: 6,
                background: "rgba(32,32,32,0.86)",
                border: "1px solid rgba(255,255,255,0.08)",
                borderRadius: 8,
                padding: "6px 12px",
                boxShadow: "0 20px 40px -10px rgba(0,0,0,0.5)",
                color: "rgba(255,255,255,0.78)",
                fontFamily: '"Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif',
                backdropFilter: "blur(20px) saturate(1.4)",
                WebkitBackdropFilter: "blur(20px) saturate(1.4)",
              }}>
                {/* Pinned-app stubs around the live Dimmy taskbar icon */}
                <PinnedStub><GlyphWinLogo/></PinnedStub>
                <PinnedStub><GlyphSearch/></PinnedStub>
                <PinnedStub><GlyphChrome/></PinnedStub>
                {/* The live Dimmy taskbar icon, same zone as the other pinned apps */}
                {WinTaskbarIcon && (
                  <div>
                    <WinTaskbarIcon state={phase} level={level}/>
                  </div>
                )}
                <PinnedStub><GlyphExplorer/></PinnedStub>
                <PinnedStub><GlyphStore/></PinnedStub>
              </div>
            </div>

            {/* RIGHT: macOS menu bar strip */}
            <div>
              <Caption text="macOS · menu bar"/>
              <div style={{
                display: "inline-flex", alignItems: "center", gap: 14,
                background: "rgba(0,0,0,0.36)",
                backdropFilter: "blur(24px) saturate(1.6)",
                WebkitBackdropFilter: "blur(24px) saturate(1.6)",
                border: "1px solid rgba(255,255,255,0.08)",
                borderRadius: 8,
                padding: "6px 14px",
                color: "rgba(255,255,255,0.92)",
                fontFamily: '-apple-system, "SF Pro Text", "SF Pro Display", system-ui, sans-serif',
                fontSize: 13,
                boxShadow: "0 20px 40px -10px rgba(0,0,0,0.5)",
              }}>
                {/* Decorative menubar glyphs */}
                <span style={{ opacity: 0.85, display: "inline-flex" }}><GlyphBatteryMac/></span>
                <span style={{ opacity: 0.85, display: "inline-flex" }}><GlyphWifiMac/></span>
                <span style={{ opacity: 0.85, display: "inline-flex" }}><GlyphSpotlightMac/></span>
                {/* The live Dimmy menu bar icon (becomes the dot during rec) */}
                {MacMenuBarIcon && <MacMenuBarIcon state={phase}/>}
                <span style={{
                  fontFeatureSettings: '"tnum"', whiteSpace: "nowrap",
                  fontSize: 12.5,
                }}>Fri 1 May 14:32</span>
              </div>
            </div>
          </div>

          {/* State chips */}
          <div style={{
            position: "relative", marginTop: 48,
            display: "flex", justifyContent: "center", gap: 8, flexWrap: "wrap",
          }}>
            {states.map((s) => {
              const m = stateMeta[s];
              const a = phase === s;
              return (
                <button key={s}
                  onClick={() => { setPaused(true); setPhase(s); if (s !== "recording") setLevel(0); }}
                  onDoubleClick={() => setPaused(false)}
                  title="double-click to resume auto-cycle"
                  style={{
                    display: "inline-flex", alignItems: "center", gap: 8,
                    padding: "8px 14px", borderRadius: 99,
                    background: a ? `${m.color}1F` : "var(--bg-elev)",
                    border: `1px solid ${a ? m.color + "66" : "var(--line)"}`,
                    color: a ? m.color : "var(--fg-muted)",
                    fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: a ? 600 : 500,
                    letterSpacing: "0.04em", textTransform: "lowercase",
                    cursor: "pointer",
                    transition: "all 200ms cubic-bezier(0.2,0.8,0.2,1)",
                  }}>
                  <span style={{
                    width: 7, height: 7, borderRadius: 99, background: m.color,
                    boxShadow: a ? `0 0 8px ${m.color}` : "none",
                  }}/>
                  {m.label}
                </button>
              );
            })}
          </div>

          <div style={{
            marginTop: 16, textAlign: "center",
            fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-faint)", position: "relative",
          }}>
            {paused ? "click chips to compare · double-click to resume · " : "auto-cycling · "}
            <span style={{ color: meta.color }}>{meta.desc}</span>
          </div>
        </div>

        {/* Three benefits */}
        <div className="reveal" style={{
          marginTop: 56,
          display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 1,
          background: "var(--line)",
          border: "1px solid var(--line)",
          borderRadius: 14, overflow: "hidden",
          maxWidth: 980, marginInline: "auto",
        }} className="invisible-benefits">
          {[
            { t: "Screenshare-safe", s: "Nothing floats over your slides. Recording is invisible to viewers, but the tray tells you it's on." },
            { t: "Fullscreen-friendly", s: "Games, video editors, presentations. Apps that hate floating overlays still get dictation." },
            { t: "Distraction-free", s: "Some users just don't want a pill in their peripheral vision. The tray icon is enough." },
          ].map((f, i) => (
            <div key={i} style={{ padding: "26px 24px", background: "var(--bg)" }}>
              <div style={{ fontWeight: 600, fontSize: 15, color: "var(--fg)", marginBottom: 8 }}>{f.t}</div>
              <div style={{ fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.5, textWrap: "pretty" }}>{f.s}</div>
            </div>
          ))}
        </div>
      </div>

      <style>{`
        @media (max-width: 720px) {
          .invisible-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
          .invisible-benefits { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

function Caption({ text }) {
  return (
    <div style={{
      fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.12em",
      color: "var(--fg-faint)", textTransform: "uppercase", marginBottom: 14,
      textAlign: "center",
    }}>{text}</div>
  );
}
function SmallStub({ children }) {
  return (
    <span style={{
      width: 24, height: 24, borderRadius: 5,
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      color: "rgba(255,255,255,0.55)",
    }}>{children}</span>
  );
}
function PinnedStub({ children }) {
  // Same footprint as WinTaskbarIcon (without the volume bar) so the row reads as one taskbar
  return (
    <span style={{
      width: 36, height: 36, borderRadius: 8,
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      color: "rgba(255,255,255,0.78)",
      transition: "background 200ms",
    }}>{children}</span>
  );
}
const STK = { fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
function GlyphWinLogo() { return <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M0 3.5L9.75 2.2v9.45H0V3.5zm10.95-1.45L24 0v11.65H10.95V2.05zM0 12.85h9.75V22.3L0 21V12.85zm10.95 0H24V24l-13.05-1.7v-9.45z"/></svg>; }
function GlyphSearch() { return <svg width="14" height="14" viewBox="0 0 24 24" {...STK}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/></svg>; }
function GlyphChrome() { return <svg width="14" height="14" viewBox="0 0 24 24" {...STK}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3.2"/><path d="M12 3v6M3.6 7.5l5.2 3M20.4 7.5l-5.2 3"/></svg>; }
function GlyphExplorer() { return <svg width="14" height="14" viewBox="0 0 24 24" {...STK}><path d="M3 7l9-4 9 4-9 4-9-4z"/><path d="M3 12l9 4 9-4M3 17l9 4 9-4"/></svg>; }
function GlyphStore() { return <svg width="14" height="14" viewBox="0 0 24 24" {...STK}><path d="M3 3l3 7h12l3-7"/><rect x="3" y="10" width="18" height="11" rx="1"/></svg>; }
function GlyphBatteryMac() { return <svg width="18" height="11" viewBox="0 0 28 13" {...STK}><rect x="1" y="2" width="22" height="9" rx="2"/><rect x="3" y="4" width="14" height="5" fill="currentColor" rx="0.5" stroke="none"/><rect x="24" y="5" width="2" height="3" fill="currentColor" rx="0.5" stroke="none"/></svg>; }
function GlyphWifiMac() { return <svg width="13" height="13" viewBox="0 0 24 24" {...STK}><path d="M2 8.5C5 6 8.5 4.5 12 4.5s7 1.5 10 4M5 12.5c2-1.7 4.5-2.5 7-2.5s5 .8 7 2.5M8 16.5c1.2-1 2.5-1.5 4-1.5s2.8.5 4 1.5"/><circle cx="12" cy="20" r="1.2" fill="currentColor"/></svg>; }
function GlyphSpotlightMac() { return <svg width="13" height="13" viewBox="0 0 24 24" {...STK}><circle cx="11" cy="11" r="6.5"/><path d="M20 20l-4.4-4.4"/></svg>; }

window.InvisibleSection = InvisibleSection;
