// Onboarding Step 2 — Audio Configuration
// 800x600 centered window. Same dark system. Two device cards with vumeters.

const IconHeadphones = ({ size = 20 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"
       strokeLinejoin="round">
    <path d="M3 18v-6a9 9 0 0 1 18 0v6" />
    <path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3z" />
    <path d="M3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z" />
  </svg>
);
const IconMicSm = ({ size = 20 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"
       strokeLinejoin="round">
    <path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z" />
    <path d="M19 10v1a7 7 0 0 1-14 0v-1" />
    <line x1="12" y1="19" x2="12" y2="22" />
    <line x1="8" y1="22" x2="16" y2="22" />
  </svg>
);
const IconChev = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth="2" strokeLinecap="round"
       strokeLinejoin="round">
    <polyline points="6 9 12 15 18 9" />
  </svg>
);
const IconCheckSm = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"
       strokeLinejoin="round">
    <polyline points="20 6 9 17 4 12" />
  </svg>
);
const IconArrowL = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth="2" strokeLinecap="round"
       strokeLinejoin="round">
    <line x1="19" y1="12" x2="5" y2="12" />
    <polyline points="12 19 5 12 12 5" />
  </svg>
);
const IconArrowR = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth="2" strokeLinecap="round"
       strokeLinejoin="round">
    <line x1="5" y1="12" x2="19" y2="12" />
    <polyline points="12 5 19 12 12 19" />
  </svg>
);

// Animated VU meter — 24 bars, randomly modulated.
const VUMeter = ({ baseLevel = 0.55, color = "var(--accent-success)" }) => {
  const BARS = 24;
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 110);
    return () => clearInterval(id);
  }, []);
  // pseudo-random levels seeded by tick
  const levels = React.useMemo(() => {
    return Array.from({ length: BARS }).map((_, i) => {
      const phase = (tick * 0.4) + i * 0.45;
      const wobble = Math.sin(phase) * 0.18 + Math.cos(phase * 0.8 + i) * 0.12;
      const decay = Math.max(0, 1 - i / (BARS * 1.2));
      const v = Math.max(0.08, Math.min(1, baseLevel * (0.55 + decay) + wobble));
      return v;
    });
  }, [tick, baseLevel]);

  return (
    <div className="vu">
      {levels.map((lv, i) => {
        const peak = lv > 0.85;
        return (
          <span
            key={i}
            className="vu-bar"
            style={{
              height: `${Math.round(lv * 100)}%`,
              background: peak ? "var(--accent-warning)" : color,
              opacity: 0.55 + lv * 0.45,
            }}
          />
        );
      })}
    </div>
  );
};

const DeviceCard = ({
  iconKind, label, deviceName, deviceList,
  statusLabel, statusVariant = "success",
  testLabel, level
}) => {
  const [open, setOpen] = React.useState(false);
  const [selected, setSelected] = React.useState(deviceName);
  const [testing, setTesting] = React.useState(false);
  const Ic = iconKind === "headphones" ? IconHeadphones : IconMicSm;

  return (
    <div className="dev-card">
      <div className="dev-head">
        <div className="dev-icon">
          <Ic size={18} />
        </div>
        <div className="dev-label">{label}</div>
        <div className={`dev-status status-${statusVariant}`}>
          <IconCheckSm size={12} />
          <span>{statusLabel}</span>
        </div>
      </div>

      <div className="dev-row">
        <div className="dropdown" onClick={() => setOpen((v) => !v)}>
          <div className="dropdown-value">
            <span className="dd-text">{selected}</span>
          </div>
          <span className={`dropdown-chev ${open ? "open" : ""}`}>
            <IconChev size={14} />
          </span>
          {open && (
            <div className="dropdown-menu" onClick={(e) => e.stopPropagation()}>
              {deviceList.map((d) => (
                <div
                  key={d}
                  className={`dropdown-item ${d === selected ? "selected" : ""}`}
                  onClick={() => { setSelected(d); setOpen(false); }}
                >
                  {d}
                  {d === selected && <IconCheckSm size={12} />}
                </div>
              ))}
            </div>
          )}
        </div>
        <button
          className={`btn-secondary ${testing ? "testing" : ""}`}
          onClick={() => {
            setTesting(true);
            setTimeout(() => setTesting(false), 1600);
          }}
        >
          {testing ? "Probando…" : testLabel}
        </button>
      </div>

      <div className="vu-row">
        <VUMeter baseLevel={level} />
        <div className="vu-readout">
          <span className="vu-db">−18 dB</span>
        </div>
      </div>
    </div>
  );
};

const OnboardingAudio = () => {
  return (
    <div className="ob-stage">
      <div className="ob-window ob2-window" data-screen-label="03 Onboarding · Audio">
        <div className="ob-grain" aria-hidden="true" />

        <div className="ob2-content">
          <div className="ob2-header">
            <h1 className="ob2-title">Configura tus dispositivos de audio</h1>
            <p className="ob2-subtitle">Necesitamos escuchar al cliente y a ti.</p>
          </div>

          <div className="ob2-cards">
            <DeviceCard
              iconKind="headphones"
              label="Audio de la reunión (cliente)"
              deviceName="Altavoz por defecto — WASAPI loopback"
              deviceList={[
                "Altavoz por defecto — WASAPI loopback",
                "Realtek Audio — Stereo Mix",
                "Headphones (Sony WH-1000XM5) — loopback",
              ]}
              statusLabel="Detectando audio"
              statusVariant="success"
              testLabel="Probar audio"
              level={0.62}
            />

            <DeviceCard
              iconKind="mic"
              label="Tu micrófono"
              deviceName="Realtek Audio — Micrófono integrado"
              deviceList={[
                "Realtek Audio — Micrófono integrado",
                "Sony WH-1000XM5 — Hands-Free",
                "USB Audio — Blue Yeti",
              ]}
              statusLabel="Listo"
              statusVariant="success"
              testLabel="Probar micrófono"
              level={0.45}
            />
          </div>
        </div>

        <div className="ob2-footer">
          <button className="btn-ghost">
            <IconArrowL size={14} />
            <span>Atrás</span>
          </button>

          <div className="ob-step ob2-step-inline">
            <span className="ob-step-dots">
              <span className="ob-dot" />
              <span className="ob-dot active" />
              <span className="ob-dot" />
            </span>
            <span className="ob-step-text">2 de 3</span>
          </div>

          <button className="btn-primary">
            <span>Siguiente</span>
            <IconArrowR size={14} />
          </button>
        </div>
      </div>
    </div>
  );
};

window.OnboardingAudio = OnboardingAudio;
