// Teleprompter Prompter Mode — 1280x800 fullscreen presentation

const Ic = ({ size = 16, stroke = 1.75, children }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth={stroke}
       strokeLinecap="round" strokeLinejoin="round">{children}</svg>
);
const IcPlay     = (p) => <Ic {...p}><polygon points="5 3 19 12 5 21 5 3" fill="currentColor" stroke="none"/></Ic>;
const IcPause    = (p) => <Ic {...p}><rect x="6" y="4" width="4" height="16" fill="currentColor" stroke="none"/><rect x="14" y="4" width="4" height="16" fill="currentColor" stroke="none"/></Ic>;
const IcRewind   = (p) => <Ic {...p}><polygon points="11 19 2 12 11 5 11 19" fill="currentColor" stroke="none"/><polygon points="22 19 13 12 22 5 22 19" fill="currentColor" stroke="none"/></Ic>;
const IcMic      = (p) => <Ic {...p}><rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0"/><line x1="12" y1="18" x2="12" y2="22"/></Ic>;
const IcChev     = (p) => <Ic {...p} stroke={2}><polyline points="6 9 12 15 18 9"/></Ic>;
const IcX        = (p) => <Ic {...p} stroke={2}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></Ic>;
const IcType     = (p) => <Ic {...p}><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></Ic>;
const IcDroplet  = (p) => <Ic {...p}><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></Ic>;
const IcBold     = (p) => <Ic {...p} stroke={2.25}><path d="M6 4h7a4 4 0 0 1 0 8H6z"/><path d="M6 12h8a4 4 0 0 1 0 8H6z"/></Ic>;
const IcRows     = (p) => <Ic {...p}><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></Ic>;

const SCRIPT = [
  "Buenas tardes a todos, gracias por acompañarnos en esta sesión.",
  "Hoy quiero presentaros los resultados del segundo trimestre y la dirección que vamos a tomar en los próximos meses.",
  "Hemos cerrado el trimestre con un crecimiento del 23% respecto al período anterior, impulsado principalmente por la adopción de nuestro nuevo módulo de copiloto en reuniones técnicas.",
  "El reto que identificamos hace seis meses era claro: los consultores IT autónomos pierden negocio cuando no saben responder con suficiente claridad a las preguntas técnicas de sus clientes en tiempo real.",
  "Nuestra solución parte de tres pilares fundamentales: escucha en tiempo real, detección automática de preguntas y sugerencia contextual basada en el conocimiento del consultor.",
  "En el roadmap de los próximos noventa días vamos a centrarnos en mejorar la latencia del modelo, ampliar el soporte multilingüe y lanzar la integración nativa con Microsoft Teams.",
];

const FONTS = ["Inter", "JetBrains Mono", "Georgia", "Helvetica"];
const COLORS = [
  { name: "Blanco", value: "#F5F5F4" },
  { name: "Ámbar",  value: "#F5C842" },
  { name: "Verde",  value: "#34D399" },
  { name: "Violeta",value: "#B19CFF" },
];
const WEIGHTS = [
  { name: "Normal", value: 400 },
  { name: "Medium", value: 500 },
  { name: "Semibold", value: 600 },
  { name: "Bold", value: 700 },
];
const LINEHEIGHTS = [1.4, 1.6, 1.8, 2.0];

const Slider = ({ value, min, max, step = 1, onChange, width = 96 }) => {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div className="ptp-slider" style={{ width }}>
      <div className="ptp-slider-track">
        <div className="ptp-slider-fill" style={{ width: `${pct}%` }} />
        <div className="ptp-slider-thumb" style={{ left: `${pct}%` }} />
      </div>
      <input type="range" min={min} max={max} step={step}
             value={value} onChange={(e) => onChange(parseFloat(e.target.value))}
             className="ptp-slider-input" />
    </div>
  );
};

const Dropdown = ({ icon, label, value, options, renderOption, onSelect }) => {
  const [open, setOpen] = React.useState(false);
  return (
    <div className="ptp-dd-wrap">
      <button className="ptp-ctrl-btn" onClick={() => setOpen((v) => !v)}>
        {icon}
        <span className="ptp-ctrl-label">{label}</span>
        <span className="ptp-ctrl-value">{value}</span>
        <IcChev size={11} />
      </button>
      {open && (
        <div className="ptp-dd-menu" onMouseLeave={() => setOpen(false)}>
          {options.map((opt, i) => (
            <button key={i} className="ptp-dd-item"
                    onClick={() => { onSelect(opt); setOpen(false); }}>
              {renderOption ? renderOption(opt) : <span>{opt}</span>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

const Prompter = () => {
  const [playing, setPlaying]   = React.useState(false);
  const [activeIdx, setActiveIdx] = React.useState(2);
  const [speed, setSpeed]       = React.useState(1.2);
  const [size, setSize]         = React.useState(48);
  const [opacity, setOpacity]   = React.useState(95);
  const [voice, setVoice]       = React.useState(true);
  const [font, setFont]         = React.useState("Inter");
  const [color, setColor]       = React.useState(COLORS[0]);
  const [weight, setWeight]     = React.useState(WEIGHTS[0]);
  const [lineHeight, setLineHeight] = React.useState(1.6);

  const [countdown, setCountdown] = React.useState(null);
  const [elapsed, setElapsed]     = React.useState(42);
  const [controlsVisible, setControlsVisible] = React.useState(true);

  // Auto-hide controls after 3s of no mouse movement
  const hideTimer = React.useRef(null);
  const handleMouseMove = () => {
    setControlsVisible(true);
    if (hideTimer.current) clearTimeout(hideTimer.current);
    hideTimer.current = setTimeout(() => setControlsVisible(false), 3000);
  };
  React.useEffect(() => {
    handleMouseMove();
    return () => hideTimer.current && clearTimeout(hideTimer.current);
  }, []);

  // Elapsed clock
  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => setElapsed((e) => e + 1), 1000);
    return () => clearInterval(id);
  }, [playing]);

  const startPlay = () => {
    setCountdown(3);
    let n = 3;
    const id = setInterval(() => {
      n -= 1;
      if (n === 0) {
        clearInterval(id);
        setCountdown(null);
        setPlaying(true);
      } else {
        setCountdown(n);
      }
    }, 800);
  };

  const togglePlay = () => {
    if (playing) { setPlaying(false); return; }
    startPlay();
  };
  const restart = () => { setActiveIdx(0); setElapsed(0); setPlaying(false); };

  const mm = String(Math.floor(elapsed / 60));
  const ss = String(elapsed % 60).padStart(2, "0");

  return (
    <div className="ptp-root" data-screen-label="07 Teleprompter Prompter"
         onMouseMove={handleMouseMove}
         style={{ "--tp-opacity": opacity / 100 }}>
      {/* Backdrop overlay (transparency) */}
      <div className="ptp-bg" style={{ opacity: opacity / 100 }} />

      {/* Clock */}
      <div className="ptp-clock">
        <span className="ptp-clock-dot" />
        <span>{mm}:{ss}</span>
      </div>

      {/* Script */}
      <div className="ptp-stage">
        <div className="ptp-script"
             style={{
               fontFamily: font === "Inter" ? "var(--font-ui)"
                         : font === "JetBrains Mono" ? "var(--font-mono)"
                         : `${font}, serif`,
               lineHeight,
             }}>
          {SCRIPT.map((line, i) => {
            const isActive = i === activeIdx;
            const isPast = i < activeIdx;
            return (
              <p key={i}
                 className={`ptp-line ${isActive ? "active" : ""} ${isPast ? "past" : ""}`}
                 style={{
                   fontSize: `${size}px`,
                   color: color.value,
                   fontWeight: weight.value,
                 }}
                 onClick={() => setActiveIdx(i)}>
                {line}
              </p>
            );
          })}
        </div>
      </div>

      {/* Countdown */}
      {countdown !== null && (
        <div className="ptp-countdown">
          <span key={countdown} className="ptp-countdown-num">{countdown}</span>
        </div>
      )}

      {/* Floating control bar */}
      <div className={`ptp-controls ${controlsVisible ? "visible" : ""}`}>
        <div className="ptp-ctrl-group">
          <button className="ptp-ctrl-icon" onClick={restart} title="Inicio">
            <IcRewind size={15} />
          </button>
          <button className={`ptp-ctrl-icon primary ${playing ? "playing" : ""}`}
                  onClick={togglePlay} title={playing ? "Pausa" : "Play"}>
            {playing ? <IcPause size={15} /> : <IcPlay size={15} />}
          </button>
          <button className={`ptp-ctrl-icon ${voice ? "active" : ""}`}
                  onClick={() => setVoice((v) => !v)} title="Voz">
            <IcMic size={15} />
            <span className={`ptp-mic-dot ${voice ? "on" : ""}`} />
          </button>
        </div>

        <span className="ptp-ctrl-sep" />

        <div className="ptp-ctrl-slider">
          <span className="ptp-ctrl-slbl">Velocidad</span>
          <Slider value={speed} min={0.5} max={2.5} step={0.1}
                  onChange={setSpeed} />
          <span className="ptp-ctrl-sval">{speed.toFixed(1)}×</span>
        </div>

        <div className="ptp-ctrl-slider">
          <span className="ptp-ctrl-slbl">Tamaño</span>
          <Slider value={size} min={24} max={80} step={2}
                  onChange={setSize} />
          <span className="ptp-ctrl-sval">{size}px</span>
        </div>

        <span className="ptp-ctrl-sep" />

        <Dropdown icon={<IcType size={13} />} label="Fuente" value={font}
                  options={FONTS} onSelect={setFont} />
        <Dropdown icon={<span className="ptp-color-dot" style={{ background: color.value }} />}
                  label="Color" value={color.name}
                  options={COLORS} onSelect={setColor}
                  renderOption={(o) => (
                    <>
                      <span className="ptp-color-dot" style={{ background: o.value }} />
                      <span>{o.name}</span>
                    </>
                  )} />
        <Dropdown icon={<IcBold size={13} />} label="Peso" value={weight.name}
                  options={WEIGHTS} onSelect={setWeight}
                  renderOption={(o) => <span style={{ fontWeight: o.value }}>{o.name}</span>} />
        <Dropdown icon={<IcRows size={13} />} label="Línea" value={lineHeight.toFixed(1)}
                  options={LINEHEIGHTS} onSelect={setLineHeight} />

        <span className="ptp-ctrl-sep" />

        <div className="ptp-ctrl-slider">
          <span className="ptp-ctrl-slbl">Opacidad</span>
          <Slider value={opacity} min={20} max={100} step={1}
                  onChange={setOpacity} />
          <span className="ptp-ctrl-sval">{opacity}%</span>
        </div>

        <span className="ptp-ctrl-sep" />

        <button className="ptp-ctrl-icon danger" title="Salir">
          <IcX size={14} />
        </button>
      </div>
    </div>
  );
};

window.TeleprompterPrompter = Prompter;
