/* global React */
const { useState, useEffect, useRef, useMemo } = React;

/**
 * Hablai Pill — overlay flotante que aparece al presionar el hotkey
 *
 * Estados:
 *  - "idle"      → dot de 12px (latido sutil naranja), siempre visible
 *  - "listening" → expandida ~240px, waveform reactivo, timer
 *  - "polishing" → spinner + microcopy "puliendo…"
 *  - "done"      → checkmark + word count + "copiado"
 *
 * Modo offline: muestra un candadito + label "local" en la pill
 */
function HablaiPill({ state = "idle", offline = false, onStateChange, demo = false }) {
  const [elapsed, setElapsed] = useState(0);
  const [wordCount, setWordCount] = useState(0);

  // timer para listening
  useEffect(() => {
    if (state !== "listening") { setElapsed(0); return; }
    const t0 = Date.now();
    const id = setInterval(() => setElapsed(Math.floor((Date.now() - t0) / 100) / 10), 100);
    return () => clearInterval(id);
  }, [state]);

  // auto-advance en demo
  useEffect(() => {
    if (!demo) return;
    if (state === "listening") {
      const t = setTimeout(() => onStateChange?.("polishing"), 3200);
      return () => clearTimeout(t);
    }
    if (state === "polishing") {
      const t = setTimeout(() => { setWordCount(42); onStateChange?.("done"); }, 1600);
      return () => clearTimeout(t);
    }
    if (state === "done") {
      const t = setTimeout(() => onStateChange?.("idle"), 2400);
      return () => clearTimeout(t);
    }
  }, [state, demo, onStateChange]);

  return (
    <div className={`hablai-pill hablai-pill--${state}`} data-offline={offline}>
      {state === "idle" && <IdleDot />}
      {state === "listening" && <ListeningContent elapsed={elapsed} offline={offline} />}
      {state === "polishing" && <PolishingContent offline={offline} />}
      {state === "done" && <DoneContent wordCount={wordCount} />}
    </div>
  );
}

/* ── Idle ─────────────────────────────────── */
function IdleDot() {
  return (
    <div className="pill-idle">
      <span className="pill-idle-dot" />
    </div>
  );
}

/* ── Listening ────────────────────────────── */
function ListeningContent({ elapsed, offline }) {
  return (
    <>
      <div className="pill-indicator">
        <span className="pill-indicator-dot" />
      </div>
      <Waveform bars={22} />
      <div className="pill-meta">
        <span className="pill-timer">{elapsed.toFixed(1)}s</span>
        {offline && <span className="pill-badge"><LockIcon /> local</span>}
      </div>
    </>
  );
}

function Waveform({ bars = 22 }) {
  // seeds estáticos para evitar re-render jitter
  const seeds = useMemo(() => Array.from({ length: bars }, (_, i) => ({
    delay: (i * 0.06) % 0.8,
    duration: 0.6 + (i * 0.037) % 0.5,
    amplitude: 0.3 + ((i * 13) % 100) / 140,
  })), [bars]);
  return (
    <div className="pill-waveform">
      {seeds.map((s, i) => (
        <span
          key={i}
          className="pill-wf-bar"
          style={{
            animationDelay: `${s.delay}s`,
            animationDuration: `${s.duration}s`,
            '--amp': s.amplitude,
          }}
        />
      ))}
    </div>
  );
}

/* ── Polishing ────────────────────────────── */
function PolishingContent({ offline }) {
  return (
    <>
      <div className="pill-spinner">
        <svg viewBox="0 0 16 16" width="14" height="14">
          <circle cx="8" cy="8" r="6" fill="none" stroke="currentColor" strokeOpacity="0.2" strokeWidth="2" />
          <path d="M8 2 A6 6 0 0 1 14 8" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
        </svg>
      </div>
      <span className="pill-label">
        <ShimmerText>{offline ? "puliendo localmente" : "puliendo…"}</ShimmerText>
      </span>
    </>
  );
}

function ShimmerText({ children }) {
  return <span className="pill-shimmer">{children}</span>;
}

/* ── Done ─────────────────────────────────── */
function DoneContent({ wordCount }) {
  return (
    <>
      <div className="pill-check">
        <svg viewBox="0 0 16 16" width="14" height="14">
          <path d="M3 8.5 L6.5 12 L13 4.5" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>
      <span className="pill-label">
        <strong>{wordCount}</strong> palabras<span className="pill-dot-sep">·</span><span className="pill-muted">pegado</span>
      </span>
    </>
  );
}

/* ── Icons ────────────────────────────────── */
function LockIcon() {
  return (
    <svg viewBox="0 0 12 12" width="10" height="10" fill="none" stroke="currentColor" strokeWidth="1.4">
      <rect x="2" y="5.5" width="8" height="5" rx="1.2" />
      <path d="M4 5.5 V3.8 a2 2 0 0 1 4 0 V5.5" strokeLinecap="round" />
    </svg>
  );
}

window.HablaiPill = HablaiPill;
