/* global React, Common */
const { Eyebrow, SectionTitle, SectionLead } = Common;
const { useRef: useViR, useState: useViS, useEffect: useViE } = React;

// State color tokens. Match the real app's pill states.
const STATE_COLOR = {
  idle:         "#34D399",  // green
  recording:    "#EF4444",  // red
  transcribing: "#38BDF8",  // blue
  done:         "#34D399",  // green flash
};

// =============================================================
// Tray menu data (shared mac/win)
// =============================================================
const STYLES = [
  { id: "off",          label: "Off",          color: "#94A3B8" },
  { id: "correct",      label: "Correct",      color: "#34D399" },
  { id: "elaborate",    label: "Elaborate",    color: "#86EFAC" },
  { id: "summarize",    label: "Summarize",    color: "#FACC15" },
  { id: "professional", label: "Professional", color: "#F472B6" },
];
const LANGS = [
  { id: "none",  flag: null,   label: "No translation", strike: true },
  { id: "en",    flag: "🇬🇧", label: "English" },
  { id: "it",    flag: "🇮🇹", label: "Italiano", pinned: true },
  { id: "fr",    flag: "🇫🇷", label: "Français" },
  { id: "de",    flag: "🇩🇪", label: "Deutsch" },
];

const SVG_STROKE = { fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };

// =============================================================
// Windows: volume bar under the taskbar icon.
// Recording = filled progress representing live mic level.
// Transcribing = indeterminate sweep.
// Idle/done = small static accent line.
// =============================================================
function WinVolumeBar({ state, level }) {
  if (state === "recording") {
    return (
      <div style={{
        marginTop: 4,
        width: 32, height: 3, borderRadius: 99,
        background: "rgba(255,255,255,0.14)",
        overflow: "hidden",
      }}>
        <div style={{
          height: "100%",
          width: `${Math.max(6, level * 100)}%`,
          background: "#EF4444",
          borderRadius: 99,
          boxShadow: "0 0 6px rgba(239,68,68,0.55)",
          transition: "width 70ms linear",
        }}/>
      </div>
    );
  }
  if (state === "transcribing") {
    return (
      <div style={{
        position: "relative", marginTop: 4,
        width: 32, height: 3, borderRadius: 99,
        background: "rgba(255,255,255,0.10)",
        overflow: "hidden",
      }}>
        <div style={{
          position: "absolute", top: 0, height: "100%", width: "45%",
          background: "linear-gradient(90deg, transparent, #38BDF8, transparent)",
          animation: "win-progress 1.1s linear infinite",
          borderRadius: 99,
        }}/>
      </div>
    );
  }
  const c = STATE_COLOR[state] || STATE_COLOR.idle;
  return (
    <div style={{
      marginTop: 4, height: 3, borderRadius: 99,
      width: state === "done" ? 22 : 14,
      background: c,
      boxShadow: `0 0 6px ${c}88`,
      transition: "width 300ms cubic-bezier(0.2,0.8,0.2,1), background 300ms",
    }}/>
  );
}

function WinTaskbarIcon({ state, level, onClick, active }) {
  const dotColor = STATE_COLOR[state];
  return (
    <button onClick={onClick} aria-label="Dimmy" style={{
      appearance: "none", border: 0, padding: 0, background: "transparent",
      display: "flex", flexDirection: "column", alignItems: "center",
      cursor: "pointer", color: "inherit",
    }}>
      <span style={{
        position: "relative",
        width: 36, height: 36, borderRadius: 8,
        background: active ? "rgba(255,255,255,0.10)" : "transparent",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        transition: "background 200ms",
      }}>
        <img src="assets/icon_1024.png" alt="" width={26} height={26} style={{ display: "block" }}/>
        <span style={{
          position: "absolute", top: 2, right: 2,
          width: 9, height: 9, borderRadius: 99,
          background: dotColor,
          boxShadow: `0 0 8px ${dotColor}, 0 0 0 2px #1f1f1f`,
          animation: state === "recording" ? "win-pulse 1.4s ease-in-out infinite" : "none",
          transition: "background 240ms",
        }}/>
      </span>
      <WinVolumeBar state={state} level={level}/>
    </button>
  );
}

// =============================================================
// Windows: tray menu (Win11 Fluent style)
// =============================================================
function WinTrayMenu({ activeStyle, onPickStyle, activeLang, onPickLang }) {
  return (
    <div style={{
      width: 244,
      borderRadius: 8,
      background: "rgba(32,32,32,0.94)",
      border: "1px solid rgba(255,255,255,0.10)",
      boxShadow: "0 24px 48px rgba(0,0,0,0.55), 0 8px 16px rgba(0,0,0,0.4)",
      backdropFilter: "blur(20px) saturate(1.2)",
      WebkitBackdropFilter: "blur(20px) saturate(1.2)",
      color: "rgba(255,255,255,0.92)",
      fontFamily: '"Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif',
      fontSize: 13,
      padding: "6px 0",
      userSelect: "none",
    }}>
      <Group label="Tasks">
        <MenuItem icon={<IconToggle/>} label="Toggle pill"/>
        <MenuItem icon={<IconCog/>} label="Open Settings…"/>
        <MenuItem icon={<IconPower/>} label="Quit Dimmy"/>
      </Group>
      <Divider/>
      <Group label="Style">
        {STYLES.map((s) => (
          <MenuItem key={s.id} icon={<Dot color={s.color}/>} label={s.label}
            active={activeStyle === s.id} onClick={() => onPickStyle && onPickStyle(s.id)}/>
        ))}
      </Group>
      <Divider/>
      <Group label="Translate to">
        {LANGS.map((l) => (
          <MenuItem key={l.id}
            icon={l.flag ? <span style={{ fontSize: 15, lineHeight: 1 }}>{l.flag}</span> : <IconNoTranslate/>}
            label={l.label} strike={l.strike} active={activeLang === l.id}
            right={l.pinned ? <IconPin/> : null}
            onClick={() => onPickLang && onPickLang(l.id)}/>
        ))}
      </Group>
      <Divider/>
      <div style={{ padding: "2px 0" }}>
        <MenuItem icon={<IconDev/>} label="Dimmy (Dev)"/>
        <MenuItem icon={<IconUnpin/>} label="Unpin from taskbar"/>
        <MenuItem icon={<IconClose/>} label="Close window"/>
      </div>
    </div>
  );
}

// =============================================================
// Mac menubar tray icon. Idle shows the monochrome glyph; during
// recording the glyph is replaced by the status dot (pulsing).
// Transcribing keeps the dot blue. Done is a green flash, then idle.
// =============================================================
function MacMenuBarIcon({ state, onClick, active }) {
  const dotColor = STATE_COLOR[state];
  const showDotInsteadOfIcon = state === "recording" || state === "transcribing" || state === "done";
  return (
    <button onClick={onClick} aria-label="Dimmy" style={{
      appearance: "none", border: 0, padding: 0, background: "transparent",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      width: 28, height: 22, borderRadius: 5,
      background: active ? "rgba(255,255,255,0.18)" : "transparent",
      transition: "background 160ms",
      cursor: "pointer", color: "rgba(255,255,255,0.92)",
      position: "relative",
    }}>
      {/* Idle / default glyph: small monochrome Dimmy "speech-wave" icon */}
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
        style={{
          opacity: showDotInsteadOfIcon ? 0 : 1,
          transform: showDotInsteadOfIcon ? "scale(0.6)" : "scale(1)",
          transition: "opacity 220ms, transform 220ms",
        }}>
        <path d="M4 6a3 3 0 0 1 3-3h7a4 4 0 0 1 4 4v6a4 4 0 0 1-4 4h-2l-3 3v-3H7a3 3 0 0 1-3-3V6z"
          stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>
        <path d="M9 9v3M12 8v5M15 10v1" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
      </svg>
      {/* Status dot, replaces the glyph during recording/transcribing/done */}
      <span style={{
        position: "absolute",
        width: 10, height: 10, borderRadius: 99,
        background: dotColor,
        boxShadow: `0 0 8px ${dotColor}`,
        opacity: showDotInsteadOfIcon ? 1 : 0,
        transform: showDotInsteadOfIcon ? "scale(1)" : "scale(0.4)",
        animation: state === "recording" ? "win-pulse 1.4s ease-in-out infinite" : "none",
        transition: "opacity 220ms, transform 220ms, background 200ms",
      }}/>
    </button>
  );
}

// =============================================================
// Mac tray menu (NSMenu / Big Sur+ vibrancy, rounded corners)
// =============================================================
function MacTrayMenu({ activeStyle, onPickStyle, activeLang, onPickLang }) {
  return (
    <div style={{
      width: 248,
      borderRadius: 10,
      background: "rgba(40,40,44,0.78)",
      border: "1px solid rgba(255,255,255,0.10)",
      boxShadow: "0 24px 60px rgba(0,0,0,0.45), 0 6px 12px rgba(0,0,0,0.3)",
      backdropFilter: "blur(36px) saturate(1.6)",
      WebkitBackdropFilter: "blur(36px) saturate(1.6)",
      color: "rgba(255,255,255,0.95)",
      fontFamily: '-apple-system, "SF Pro Text", "SF Pro Display", system-ui, sans-serif',
      fontSize: 13,
      padding: "5px 5px",
      userSelect: "none",
    }}>
      <MacGroup label="Tasks">
        <MacItem icon={<IconToggle/>} label="Toggle pill"/>
        <MacItem icon={<IconCog/>} label="Open Settings…"/>
        <MacItem icon={<IconPower/>} label="Quit Dimmy"/>
      </MacGroup>
      <MacDivider/>
      <MacGroup label="Style">
        {STYLES.map((s) => (
          <MacItem key={s.id} icon={<Dot color={s.color}/>} label={s.label}
            active={activeStyle === s.id} onClick={() => onPickStyle && onPickStyle(s.id)}/>
        ))}
      </MacGroup>
      <MacDivider/>
      <MacGroup label="Translate to">
        {LANGS.map((l) => (
          <MacItem key={l.id}
            icon={l.flag ? <span style={{ fontSize: 15, lineHeight: 1 }}>{l.flag}</span> : <IconNoTranslate/>}
            label={l.label} strike={l.strike} active={activeLang === l.id}
            right={l.pinned ? <IconPin/> : null}
            onClick={() => onPickLang && onPickLang(l.id)}/>
        ))}
      </MacGroup>
      <MacDivider/>
      <div>
        <MacItem icon={<IconDev/>} label="Dimmy (Dev)"/>
        <MacItem icon={<IconClose/>} label="Hide menubar icon"/>
      </div>
    </div>
  );
}

// =============================================================
// Shared menu primitives (Win and Mac flavors share row API)
// =============================================================
function Group({ label, children }) {
  return (
    <div>
      <div style={{
        padding: "6px 14px 2px", fontSize: 11,
        color: "rgba(255,255,255,0.5)", letterSpacing: "0.04em",
      }}>{label}</div>
      <div>{children}</div>
    </div>
  );
}
function Divider() {
  return <div style={{ height: 1, background: "rgba(255,255,255,0.08)", margin: "4px 8px" }}/>;
}
function MenuItem({ icon, label, active, strike, right, onClick }) {
  const [hover, setHover] = useViS(false);
  return (
    <div onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: "7px 12px", cursor: onClick ? "pointer" : "default",
        background: hover ? "rgba(255,255,255,0.06)" : (active ? "rgba(56,189,248,0.10)" : "transparent"),
        color: active ? "#7DD3FC" : "rgba(255,255,255,0.92)",
        transition: "background 120ms",
      }}>
      <span style={{ width: 18, display: "inline-flex", justifyContent: "center" }}>{icon}</span>
      <span style={{
        flex: 1,
        textDecoration: strike ? "line-through" : "none",
        opacity: strike ? 0.55 : 1,
        whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
      }}>{label}</span>
      {right}
    </div>
  );
}

function MacGroup({ label, children }) {
  return (
    <div>
      <div style={{
        padding: "5px 10px 1px", fontSize: 10,
        color: "rgba(255,255,255,0.45)", letterSpacing: "0.02em",
        textTransform: "uppercase",
      }}>{label}</div>
      <div>{children}</div>
    </div>
  );
}
function MacDivider() {
  return <div style={{ height: 1, background: "rgba(255,255,255,0.10)", margin: "4px 6px" }}/>;
}
function MacItem({ icon, label, active, strike, right, onClick }) {
  const [hover, setHover] = useViS(false);
  return (
    <div onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: "5px 10px", borderRadius: 5,
        cursor: onClick ? "pointer" : "default",
        background: hover ? "#0a84ff" : (active ? "rgba(10,132,255,0.22)" : "transparent"),
        color: hover ? "white" : (active ? "#7DD3FC" : "rgba(255,255,255,0.95)"),
        transition: "background 90ms, color 90ms",
      }}>
      <span style={{ width: 18, display: "inline-flex", justifyContent: "center" }}>{icon}</span>
      <span style={{
        flex: 1,
        textDecoration: strike ? "line-through" : "none",
        opacity: strike ? 0.55 : 1,
        whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
      }}>{label}</span>
      {right}
    </div>
  );
}

function Dot({ color }) {
  return <span style={{
    width: 9, height: 9, borderRadius: 99, background: color,
    boxShadow: `0 0 6px ${color}66`,
  }}/>;
}

// Inline SVG icons. Line style, à la Segoe Fluent / SF Symbols.
function IconToggle() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><rect x="2" y="7" width="20" height="10" rx="5"/><circle cx="16" cy="12" r="3" fill="currentColor"/></svg>; }
function IconCog() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M5 19l2-2M17 7l2-2"/></svg>; }
function IconPower() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><path d="M12 3v9M5.5 7.5a9 9 0 1 0 13 0"/></svg>; }
function IconNoTranslate() { return <svg width="15" height="15" viewBox="0 0 24 24" {...SVG_STROKE}><rect x="3" y="3" width="18" height="18" rx="3"/><path d="M5 5l14 14"/></svg>; }
function IconPin() { return <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M16 3a1 1 0 0 0-1 1v4.586L9.707 13.88A1 1 0 0 0 9 14.586V19l-3.707 3.707a1 1 0 0 0 1.414 1.414L10.414 20H15v-4.414L20.293 10.293A1 1 0 0 0 21 9.586V5a1 1 0 0 0-1-1zM17 5h2v3.586L13.586 14H11v-2.586L17 5z"/></svg>; }
function IconDev() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><path d="M16 18l6-6-6-6M8 6l-6 6 6 6"/></svg>; }
function IconUnpin() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><path d="M3 3l18 18"/><path d="M14 4v5l4 4M4 14h5l4 4"/></svg>; }
function IconClose() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><path d="M6 6l12 12M18 6L6 18"/></svg>; }

// =============================================================
// WINDOWS desktop mockup
// =============================================================
function WinDesktopMockup({ phase, level, menuOpen, setMenuOpen, activeStyle, setActiveStyle, activeLang, setActiveLang, stateLabel }) {
  return (
    <div className="dimmy-desktop-mockup" style={{
      position: "relative",
      maxWidth: 1080, marginInline: "auto",
      borderRadius: 18, overflow: "hidden",
      border: "1px solid var(--line-strong)",
      boxShadow: "0 50px 120px -30px rgba(56,189,248,0.28), 0 30px 60px -15px rgba(0,0,0,0.5)",
      background: "linear-gradient(135deg, #1e293b 0%, #0f172a 50%, #1e1b4b 100%)",
      minHeight: 460,
    }}>
      <div style={{
        position: "absolute", inset: 0,
        background:
          "radial-gradient(900px 700px at 20% 10%, rgba(56,189,248,0.18), transparent 55%), " +
          "radial-gradient(700px 600px at 90% 90%, rgba(167,139,250,0.16), transparent 55%)",
        pointerEvents: "none",
      }}/>

      <StateCaption phase={phase} stateLabel={stateLabel} anchor="center"/>

      {/* Win11-style taskbar, left-aligned. Status pill (top-center), Dimmy
          icon (leftmost in the dock) and the dropdown menu now all sit on
          the same side. */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: 0,
        height: 48, background: "rgba(32,32,32,0.78)",
        borderTop: "1px solid rgba(255,255,255,0.08)",
        backdropFilter: "blur(20px) saturate(1.4)",
        WebkitBackdropFilter: "blur(20px) saturate(1.4)",
        display: "flex", alignItems: "center", justifyContent: "flex-start",
        gap: 14, padding: "0 16px", zIndex: 2,
      }}>
        <Stub><WinLogo/></Stub>
        {/* Dimmy first in the cluster, with its dropdown anchored to it. */}
        <div style={{ position: "relative" }}>
          <WinTaskbarIcon state={phase} level={level}
            active={menuOpen} onClick={() => setMenuOpen((v) => !v)}/>
          <div style={{
            position: "absolute", left: -6, bottom: "calc(100% + 16px)",
            zIndex: 3,
            transform: menuOpen ? "translateY(0) scale(1)" : "translateY(8px) scale(0.97)",
            opacity: menuOpen ? 1 : 0,
            transformOrigin: "bottom left",
            transition: "transform 260ms cubic-bezier(0.2,0.8,0.2,1), opacity 200ms",
            pointerEvents: menuOpen ? "auto" : "none",
          }}>
            <WinTrayMenu
              activeStyle={activeStyle} onPickStyle={setActiveStyle}
              activeLang={activeLang} onPickLang={setActiveLang}/>
          </div>
        </div>
        <Stub><IconSearch/></Stub>
        <Stub><IconCamera/></Stub>
        <Stub><IconChrome/></Stub>
        <Stub><IconExplorer/></Stub>
        <Stub><IconStore/></Stub>
        <span style={{ flex: 1 }}/>
        <div style={{
          fontFamily: '"Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif',
          fontSize: 11, color: "rgba(255,255,255,0.85)",
          textAlign: "right", lineHeight: 1.1,
        }}>
          <div>20:21</div>
          <div style={{ opacity: 0.7 }}>01/05/2026</div>
        </div>
      </div>
    </div>
  );
}

// =============================================================
// MAC desktop mockup
// =============================================================
function MacDesktopMockup({ phase, menuOpen, setMenuOpen, activeStyle, setActiveStyle, activeLang, setActiveLang, stateLabel }) {
  return (
    <div className="dimmy-desktop-mockup" style={{
      position: "relative",
      maxWidth: 1080, marginInline: "auto",
      borderRadius: 18, overflow: "hidden",
      border: "1px solid var(--line-strong)",
      boxShadow: "0 50px 120px -30px rgba(56,189,248,0.28), 0 30px 60px -15px rgba(0,0,0,0.5)",
      background: "linear-gradient(135deg, #2c1810 0%, #4a1942 50%, #1a3260 100%)",
      minHeight: 460,
    }}>
      <div style={{
        position: "absolute", inset: 0,
        background:
          "radial-gradient(900px 700px at 80% 10%, rgba(255,180,120,0.22), transparent 55%), " +
          "radial-gradient(700px 600px at 10% 90%, rgba(167,139,250,0.18), transparent 55%)",
        pointerEvents: "none",
      }}/>

      {/* macOS menubar (top) */}
      <div style={{
        position: "absolute", top: 0, left: 0, right: 0,
        height: 26, zIndex: 4,
        background: "rgba(0,0,0,0.28)",
        backdropFilter: "blur(24px) saturate(1.6)",
        WebkitBackdropFilter: "blur(24px) saturate(1.6)",
        borderBottom: "1px solid rgba(255,255,255,0.06)",
        display: "flex", alignItems: "center", gap: 14, padding: "0 12px",
        fontFamily: '-apple-system, "SF Pro Text", "SF Pro Display", system-ui, sans-serif',
        fontSize: 13,
        color: "rgba(255,255,255,0.95)",
      }}>
        {/* Apple menu */}
        <span style={{ width: 14, height: 14, display: "inline-flex" }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M11.06 8.46c-.02-1.95 1.6-2.88 1.67-2.93-.91-1.34-2.34-1.52-2.84-1.54-1.21-.12-2.36.71-2.97.71-.62 0-1.57-.7-2.58-.68-1.33.02-2.55.77-3.23 1.96-1.38 2.39-.35 5.92 1 7.86.66.95 1.44 2.02 2.46 1.98 1-.04 1.37-.64 2.58-.64 1.2 0 1.55.64 2.58.62 1.07-.02 1.74-.96 2.39-1.92.75-1.1 1.06-2.18 1.08-2.24-.02-.01-2.07-.79-2.09-3.16zm-1.94-5.8c.55-.66.92-1.59.82-2.51-.79.03-1.75.53-2.32 1.19-.51.58-.96 1.51-.84 2.42.88.07 1.78-.45 2.34-1.1z"/></svg>
        </span>
        <strong style={{ fontWeight: 600 }}>Dimmy</strong>
        <span style={{ opacity: 0.78 }}>File</span>
        <span style={{ opacity: 0.78 }}>Edit</span>
        <span style={{ opacity: 0.78 }}>View</span>
        <span style={{ opacity: 0.78 }}>Window</span>
        <span style={{ opacity: 0.78 }}>Help</span>
        <span style={{ flex: 1 }}/>
        {/* Right cluster: status icons + clock */}
        <span style={{ opacity: 0.85, display: "inline-flex", gap: 12, alignItems: "center" }}>
          <IconBatteryMac/>
          <IconWifiMac/>
          <IconSpotlight/>
          <IconControlCenter/>
          {/* the live Dimmy menubar icon */}
          <MacMenuBarIcon state={phase} active={menuOpen} onClick={() => setMenuOpen((v) => !v)}/>
          <span style={{
            fontFeatureSettings: '"tnum"', whiteSpace: "nowrap",
            fontSize: 12.5,
          }}>Fri 1 May 20:21</span>
        </span>
      </div>

      <StateCaption phase={phase} stateLabel={stateLabel} top={40} anchor="center"/>

      {/* Tray menu, drops down from menubar, anchored under the Dimmy icon */}
      <div style={{
        position: "absolute", right: 124, top: 32, zIndex: 5,
        transform: menuOpen ? "translateY(0) scale(1)" : "translateY(-6px) scale(0.97)",
        opacity: menuOpen ? 1 : 0,
        transformOrigin: "top right",
        transition: "transform 220ms cubic-bezier(0.2,0.8,0.2,1), opacity 180ms",
        pointerEvents: menuOpen ? "auto" : "none",
      }}>
        <MacTrayMenu
          activeStyle={activeStyle} onPickStyle={setActiveStyle}
          activeLang={activeLang} onPickLang={setActiveLang}/>
      </div>

      {/* mac dock with realistic-ish app icons. clickable but inert. */}
      <MacDock/>
    </div>
  );
}

// =============================================================
// MacDock: classic centered bottom strip with iconic app glyphs.
// Pure SVG, no external assets, no real action on click (cursor: pointer
// + brief press feedback only). Hover lifts the icon Mac-style.
// =============================================================
const MAC_DOCK_APPS = [
  { name: "Finder", bg: "linear-gradient(180deg, #6FB1DB, #1E5A99)",
    glyph: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M3 5 H11 V20 H6 Q3 20 3 17 Z" fill="#1E3A5F"/>
        <path d="M11 5 H18 Q21 5 21 8 V17 Q21 20 18 20 H11 Z" fill="#A4D1F0"/>
        <ellipse cx="8" cy="11" rx="0.9" ry="1.6" fill="#fff"/>
        <ellipse cx="14" cy="11" rx="0.9" ry="1.6" fill="#1E3A5F"/>
        <path d="M7.5 15 Q12 17.5 16.5 15" stroke="#1E3A5F" strokeWidth="1" fill="none" strokeLinecap="round"/>
      </svg>
    ),
  },
  { name: "Launchpad", bg: "rgba(50,50,52,0.92)",
    glyph: (
      <svg width="20" height="20" viewBox="0 0 20 20" aria-hidden="true">
        {[0,1,2].map((y) => [0,1,2].map((x) => (
          <rect key={`${x}-${y}`} x={2 + x*6} y={2 + y*6} width={4} height={4} rx={1} fill="rgba(255,255,255,0.88)"/>
        )))}
      </svg>
    ),
  },
  { name: "Safari", bg: "radial-gradient(circle at 30% 30%, #fff, #38B6FF 40%, #006CCE 100%)",
    glyph: (
      <svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true">
        <circle cx="12" cy="12" r="10" fill="none" stroke="#fff" strokeWidth="0.6" opacity="0.55"/>
        <path d="M12 5 L13.5 12 L12 19 L10.5 12 Z" fill="#EF4444"/>
        <path d="M5 12 L12 10.5 L19 12 L12 13.5 Z" fill="#fff"/>
        <circle cx="12" cy="12" r="1" fill="#fff"/>
      </svg>
    ),
  },
  { name: "Messages", bg: "linear-gradient(180deg, #5DEC83, #14B14B)",
    glyph: (
      <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
        <path d="M5 5 H19 Q21 5 21 7 V14 Q21 16 19 16 H10 L7 19 V16 H5 Q3 16 3 14 V7 Q3 5 5 5 Z" fill="#fff"/>
      </svg>
    ),
  },
  { name: "Mail", bg: "linear-gradient(180deg, #5BC0FE, #007AFF)",
    glyph: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <rect x="3" y="6" width="18" height="13" rx="2" fill="#fff"/>
        <path d="M3.5 7.5 L12 14 L20.5 7.5" stroke="#007AFF" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    ),
  },
  { name: "Notes", bg: "linear-gradient(180deg, #FFF275, #FFC83A)",
    glyph: (
      <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
        <rect x="4" y="3" width="16" height="18" rx="1.5" fill="#fffdf0"/>
        <rect x="4" y="3" width="16" height="3" fill="#FF8B47"/>
        <line x1="6.5" y1="9.5" x2="17.5" y2="9.5" stroke="#D4A12A" strokeWidth="0.8" strokeLinecap="round"/>
        <line x1="6.5" y1="12.5" x2="17.5" y2="12.5" stroke="#D4A12A" strokeWidth="0.8" strokeLinecap="round"/>
        <line x1="6.5" y1="15.5" x2="14" y2="15.5" stroke="#D4A12A" strokeWidth="0.8" strokeLinecap="round"/>
      </svg>
    ),
  },
  { name: "Music", bg: "linear-gradient(135deg, #FB85B4, #F32368)",
    glyph: (
      <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
        <path d="M9 17 V7 L18 5 V15" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        <circle cx="7" cy="17" r="2.2" fill="#fff"/>
        <circle cx="16" cy="15" r="2.2" fill="#fff"/>
      </svg>
    ),
  },
  { name: "Photos", bg: "rgba(255,255,255,0.96)",
    glyph: (
      <svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true">
        {[
          ["#FB7185", 12, 4.5],
          ["#FBBF24", 18.2, 8],
          ["#4ADE80", 18.2, 15],
          ["#38BDF8", 12, 18.5],
          ["#A78BFA", 5.8, 15],
          ["#F472B6", 5.8, 8],
        ].map(([c, x, y], i) => <circle key={i} cx={x} cy={y} r="3.4" fill={c} opacity="0.92"/>)}
      </svg>
    ),
  },
  { name: "Calendar", bg: "#fff",
    glyph: (
      <svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true">
        <rect x="2" y="2" width="20" height="6" fill="#FFEFEF" rx="0"/>
        <text x="12" y="7" textAnchor="middle" fontFamily="-apple-system, system-ui, sans-serif" fontWeight="700" fontSize="4.5" fill="#FF3B30" letterSpacing="0.4">SAT</text>
        <text x="12" y="20" textAnchor="middle" fontFamily="-apple-system, system-ui, sans-serif" fontWeight="500" fontSize="13" fill="#1F1F22">17</text>
      </svg>
    ),
  },
];

function MacDock() {
  const [hover, setHover] = useViS(null);
  const [pressed, setPressed] = useViS(null);
  return (
    <div style={{
      position: "absolute", left: "50%", bottom: 12, transform: "translateX(-50%)",
      display: "flex", gap: 6, padding: "6px 10px",
      borderRadius: 18,
      background: "rgba(255,255,255,0.14)",
      backdropFilter: "blur(24px) saturate(1.6)",
      WebkitBackdropFilter: "blur(24px) saturate(1.6)",
      border: "1px solid rgba(255,255,255,0.18)",
      boxShadow: "0 10px 30px rgba(0,0,0,0.3), inset 0 1px 0 rgba(255,255,255,0.12)",
      zIndex: 2,
      alignItems: "flex-end",
    }}>
      {MAC_DOCK_APPS.map((app, i) => {
        const isHover = hover === i;
        const isPressed = pressed === i;
        return (
          <span key={app.name} title={app.name}
            onMouseEnter={() => setHover(i)}
            onMouseLeave={() => { setHover(null); setPressed(null); }}
            onMouseDown={() => setPressed(i)}
            onMouseUp={() => setPressed(null)}
            style={{
              width: 32, height: 32, borderRadius: 8,
              background: app.bg,
              boxShadow: "inset 0 1px 0 rgba(255,255,255,0.28), 0 4px 10px rgba(0,0,0,0.35)",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              cursor: "pointer", userSelect: "none",
              transform: isPressed ? "translateY(-2px) scale(0.92)" : isHover ? "translateY(-8px) scale(1.18)" : "translateY(0) scale(1)",
              transition: "transform 220ms cubic-bezier(0.34,1.4,0.64,1)",
              transformOrigin: "bottom center",
            }}>
            {app.glyph}
          </span>
        );
      })}
    </div>
  );
}

function StateCaption({ phase, stateLabel, top = 18, anchor = "left" }) {
  // anchor:
  //   "left"   → top-left corner (Windows mockup, away from the dropdown
  //              that drops above the bottom-left taskbar Dimmy icon).
  //   "center" → horizontal center (Mac mockup, so the pill stays clear of
  //              the dropdown that descends from the menubar Dimmy icon).
  //   "right"  → tucked under the menubar Dimmy icon (legacy).
  let horiz;
  if (anchor === "center") horiz = { left: "50%", transform: "translateX(-50%)" };
  else if (anchor === "right") horiz = { right: 16 };
  else horiz = { left: 22 };
  return (
    <div style={{
      position: "absolute", top, ...horiz, zIndex: 6,
      display: "inline-flex", alignItems: "center", gap: 10,
      padding: "6px 12px", borderRadius: 99,
      background: "rgba(0,0,0,0.55)",
      border: "1px solid rgba(255,255,255,0.10)",
      backdropFilter: "blur(10px)",
      WebkitBackdropFilter: "blur(10px)",
      color: "rgba(255,255,255,0.92)",
      fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em",
      boxShadow: phase === "recording" ? `0 0 0 1px ${STATE_COLOR.recording}55, 0 8px 24px ${STATE_COLOR.recording}33` : "none",
      transition: "box-shadow 240ms",
    }}>
      <span style={{
        width: 7, height: 7, borderRadius: 99,
        background: STATE_COLOR[phase],
        boxShadow: `0 0 8px ${STATE_COLOR[phase]}`,
        animation: phase === "recording" ? "win-pulse 1.4s ease-in-out infinite" : "none",
        transition: "background 240ms",
      }}/>
      <span style={{ textTransform: "uppercase" }}>{stateLabel}</span>
    </div>
  );
}

function Stub({ children }) {
  return (
    <span style={{
      width: 36, height: 36, borderRadius: 8,
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      color: "rgba(255,255,255,0.78)",
    }}>{children}</span>
  );
}
function WinLogo() { 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 IconSearch() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/></svg>; }
function IconCamera() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><rect x="3" y="6" width="14" height="12" rx="2"/><path d="M17 10l4-2v8l-4-2"/></svg>; }
function IconChrome() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><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 IconExplorer() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><path d="M3 7l9-4 9 4-9 4-9-4z"/><path d="M3 12l9 4 9-4M3 17l9 4 9-4"/></svg>; }
function IconStore() { return <svg width="14" height="14" viewBox="0 0 24 24" {...SVG_STROKE}><path d="M3 3l3 7h12l3-7"/><rect x="3" y="10" width="18" height="11" rx="1"/></svg>; }
function IconWifiMac() { return <svg width="13" height="13" viewBox="0 0 24 24" {...SVG_STROKE}><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 IconBatteryMac() { return <svg width="20" height="13" viewBox="0 0 28 13" {...SVG_STROKE}><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 IconSpotlight() { return <svg width="13" height="13" viewBox="0 0 24 24" {...SVG_STROKE}><circle cx="11" cy="11" r="6.5"/><path d="M20 20l-4.4-4.4"/></svg>; }
function IconControlCenter() { return <svg width="13" height="13" viewBox="0 0 24 24" {...SVG_STROKE}><rect x="3" y="3" width="8" height="8" rx="2"/><rect x="13" y="3" width="8" height="8" rx="2"/><rect x="3" y="13" width="8" height="8" rx="2"/><rect x="13" y="13" width="8" height="8" rx="2"/></svg>; }

// =============================================================
// Section
// =============================================================
function VideoSection() {
  // Default = macOS (the Windows taskbar lives in InvisibleSection too, but
  // the toggle stays so users can compare both platforms here).
  const [platform, setPlatform] = useViS("mac"); // mac | win
  const [phase, setPhase] = useViS("idle");      // idle | recording | transcribing | done
  const [level, setLevel] = useViS(0.3);
  const [activeStyle, setActiveStyle] = useViS("correct");
  const [activeLang, setActiveLang] = useViS("it");
  const [menuOpen, setMenuOpen] = useViS(true);
  const sectionRef = useViR(null);
  const inViewRef = useViR(true);

  useViE(() => {
    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();
  }, []);

  // Auto-cycle: idle → recording → transcribing → done → idle
  useViE(() => {
    let timers = [];
    let levelInterval;
    const wait = (ms) => new Promise((r) => timers.push(setTimeout(r, ms)));
    let cancelled = false;

    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);
        // Hold the recording state long enough for the static rainbow ring
        // to register visually. 3s felt like a flash, 4.5s feels deliberate.
        await wait(4500);
        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);
    };
  }, []);

  const stateLabel = { idle: "ready", recording: "recording", transcribing: "transcribing", done: "done" }[phase];

  return (
    <section ref={sectionRef} style={{ padding: "120px 32px", position: "relative", overflow: "hidden" }}>
      <div className="container">
        <div className="reveal" style={{ textAlign: "center", marginBottom: 40 }}>
          <Eyebrow num={2} color="#FB923C">live demo</Eyebrow>
          <div style={{ height: 16 }}/>
          <SectionTitle align="center" maxWidth={780}>
            Press, speak, release.<br/>
            <span className="grad-text">That's the whole UX.</span>
          </SectionTitle>
          <SectionLead align="center" maxWidth={580}>
            One icon, one status dot, a right-click menu. That's all the UI you ever need to see. Watch it cycle live.
          </SectionLead>
        </div>

        {/* Platform toggle */}
        <div className="reveal" style={{ display: "flex", justifyContent: "center", marginBottom: 24 }}>
          <div style={{
            display: "inline-flex", padding: 4,
            background: "var(--bg-elev)", border: "1px solid var(--line)",
            borderRadius: 10, gap: 4,
          }}>
            {[["mac", "macOS"], ["win", "Windows"]].map(([id, label]) => (
              <button key={id} onClick={() => setPlatform(id)} style={{
                padding: "8px 16px", borderRadius: 7,
                background: platform === id ? "var(--line)" : "transparent",
                border: 0, color: platform === id ? "var(--fg)" : "var(--fg-muted)",
                fontSize: 13, fontFamily: "var(--font-sans)",
                fontWeight: platform === id ? 600 : 500,
                cursor: "pointer", transition: "all 200ms",
              }}>{label}</button>
            ))}
          </div>
        </div>

        {platform === "mac" ? (
          <MacDesktopMockup
            phase={phase}
            menuOpen={menuOpen} setMenuOpen={setMenuOpen}
            activeStyle={activeStyle} setActiveStyle={setActiveStyle}
            activeLang={activeLang} setActiveLang={setActiveLang}
            stateLabel={stateLabel}/>
        ) : (
          <WinDesktopMockup
            phase={phase} level={level}
            menuOpen={menuOpen} setMenuOpen={setMenuOpen}
            activeStyle={activeStyle} setActiveStyle={setActiveStyle}
            activeLang={activeLang} setActiveLang={setActiveLang}
            stateLabel={stateLabel}/>
        )}

        <div className="reveal" style={{
          marginTop: 24, textAlign: "center",
          fontFamily: "var(--font-mono)", fontSize: 12,
          color: "var(--fg-faint)",
          display: "inline-flex", flexWrap: "wrap", justifyContent: "center", gap: "6px 16px",
          width: "100%",
        }}>
          <span>real ui · pure react · no video</span>
          <span style={{ opacity: 0.4 }}>·</span>
          <span>auto-cycling: idle → rec → transcribe → done</span>
          <span style={{ opacity: 0.4 }}>·</span>
          <span>click the icon to toggle the menu</span>
        </div>
      </div>

      <style>{`
        @keyframes win-pulse {
          0%, 100% { transform: scale(1); opacity: 1; }
          50% { transform: scale(1.18); opacity: 0.75; }
        }
        @keyframes win-progress {
          0% { left: -45%; }
          100% { left: 100%; }
        }
        @media (max-width: 720px) {
          .dimmy-desktop-mockup { min-height: 360px !important; }
        }
      `}</style>
    </section>
  );
}

// Re-exports. Let other sections (Tray, Invisible) reuse the live components.
window.DimmyTray = {
  WinTrayMenu, MacTrayMenu,
  WinTaskbarIcon, WinVolumeBar,
  MacMenuBarIcon,
  WinDesktopMockup, MacDesktopMockup,
  STATE_COLOR, STYLES, LANGS,
};
window.VideoSection = VideoSection;
