// sonidos.jsx — Sonidos ambientales (MP3 reales + Web Audio para café)
// Cargado en SerenIA.html: <script type="text/babel" src="./sonidos.jsx">

const SONIDOS_CONFIG = [
  { id: 'lluvia',    label: 'Lluvia',     emoji: '🌧', color: '#5B8FC4', bg: '#E8F0F8', desc: 'Lluvia suave' },
  { id: 'bosque',    label: 'Bosque',     emoji: '🌲', color: '#5A8C5A', bg: '#E8F3E8', desc: 'Brisa entre hojas' },
  { id: 'fuego',     label: 'Fuego',      emoji: '🔥', color: '#C4703A', bg: '#F8EDDE', desc: 'Fogata' },
  { id: 'oceano',    label: 'Océano',     emoji: '🌊', color: '#3A7BC4', bg: '#DDE8F5', desc: 'Olas del mar' },
  { id: 'naturaleza',label: 'Naturaleza', emoji: '🌿', color: '#4A8A5A', bg: '#E3F0E8', desc: 'Sonidos naturales' },
  { id: 'viento',    label: 'Viento',     emoji: '🌬', color: '#6A8A9A', bg: '#E0E8EC', desc: 'Brisa tranquila' },
];

// Archivos MP3 para sonidos con audio real
const SONIDOS_FILES = {
  lluvia:    '/Audios/Sonido de lluvia.mp3',
  bosque:    '/Audios/bosque.mp3',
  fuego:     '/Audios/fogata.mp3',
  oceano:    '/Audios/ola.mp3',
  viento:    '/Audios/viento.mp3',
  naturaleza:'/Audios/naturalez.mp3',
};

// ── Motor de audio ────────────────────────────────────────────────────────────
const _sonidosNodes = {};

function sonidoStart(id, volume) {
  if (_sonidosNodes[id] || !SONIDOS_FILES[id]) return;
  const el = new Audio(SONIDOS_FILES[id]);
  el.loop = true;
  el.volume = volume;
  el.play().catch(() => {});
  _sonidosNodes[id] = { el };
}

function sonidoStop(id) {
  const n = _sonidosNodes[id];
  if (!n) return;
  n.el.pause();
  n.el.currentTime = 0;
  delete _sonidosNodes[id];
}

function sonidoVolumen(id, vol) {
  const n = _sonidosNodes[id];
  if (n) n.el.volume = vol;
}

function sonidoStopAll() {
  Object.keys(_sonidosNodes).forEach(sonidoStop);
}

// ── Componente React ──────────────────────────────────────────────────────────
function SonidosScreen({ p, onBack }) {
  const [playing, setPlaying]     = React.useState({});
  const [timerMin, setTimerMin]   = React.useState(null);
  const [timeLeft, setTimeLeft]   = React.useState(null);
  const [customMin, setCustomMin] = React.useState('');

  React.useEffect(() => () => sonidoStopAll(), []);

  React.useEffect(() => {
    if (timeLeft === null) return;
    if (timeLeft <= 0) {
      sonidoStopAll();
      setPlaying({});
      setTimeLeft(null);
      setTimerMin(null);
      return;
    }
    const t = setTimeout(() => setTimeLeft(s => s - 1), 1000);
    return () => clearTimeout(t);
  }, [timeLeft]);

  const toggle = (id) => {
    if (playing[id] !== undefined) {
      sonidoStop(id);
      setPlaying(prev => { const n = { ...prev }; delete n[id]; return n; });
    } else {
      sonidoStart(id, 0.5);
      setPlaying(prev => ({ ...prev, [id]: 0.5 }));
    }
  };

  const changeVol = (id, vol) => {
    sonidoVolumen(id, vol);
    setPlaying(prev => ({ ...prev, [id]: vol }));
  };

  const startTimer = (min) => {
    setTimerMin(min);
    setTimeLeft(min * 60);
  };

  const startCustomTimer = () => {
    const min = parseInt(customMin);
    if (!min || min < 1 || min > 480) return;
    setCustomMin('');
    startTimer(min);
  };

  const cancelTimer = () => { setTimerMin(null); setTimeLeft(null); };

  const fmt = (s) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
  const anyPlaying = Object.keys(playing).length > 0;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: p.bg }}>
      {/* Cabecera */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 18px 10px', borderBottom: `1px solid ${p.line}`, flexShrink: 0 }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', cursor: 'pointer',
          color: p.primaryDeep, fontSize: 15, fontWeight: 600, padding: '6px 0' }}>‹ Inicio</button>
        <div style={{ fontSize: 15, fontWeight: 600, color: p.ink }}>Sonidos</div>
        <div style={{ width: 60 }} />
      </div>

      <style>{`
        @keyframes sonidosBar {
          0%   { height: 4px; }
          25%  { height: 12px; }
          50%  { height: 26px; }
          100% { height: 4px; }
        }
        .sonidos-row {
          display: flex; flex-direction: row; align-items: center;
          height: 64px; padding: 0 16px;
          border-radius: 12px; cursor: pointer;
          transition: background .25s ease-in-out;
        }
        .sonidos-row:hover { background: #f0efec; }
        .sonidos-row.is-active { background: #f4f4f1; }
        .timer-preset-btn {
          flex: 1; padding: 9px 4px; border-radius: 12px;
          border: 1px solid; background: transparent;
          font-size: 12px; font-weight: 500; cursor: pointer;
          transition: background .15s;
        }
        .timer-preset-btn:hover { opacity: .8; }
      `}</style>

      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 14px 32px' }}>
        {/* Lista de sonidos */}
        <div style={{
          background: p.surface, borderRadius: 15, padding: '14px 8px 18px',
          boxShadow: `0 8px 26px ${p.ink}10, 0 0 0 1px ${p.line}`,
        }}>
          {SONIDOS_CONFIG.map(s => {
            const active = playing[s.id] !== undefined;
            const vol = playing[s.id] ?? 0.5;
            return (
              <div key={s.id} className={`sonidos-row${active ? ' is-active' : ''}`}>
                <div onClick={() => toggle(s.id)} style={{
                  display: 'flex', alignItems: 'center', flex: 1, height: '100%', minWidth: 0,
                }}>
                  <div style={{
                    width: 40, height: 40, borderRadius: 6, marginRight: 14,
                    background: active ? s.bg : '#e9e8e8',
                    color: s.color, fontSize: 22,
                    display: 'grid', placeItems: 'center', flexShrink: 0,
                    transition: 'background .25s',
                  }}>{s.emoji}</div>
                  <div style={{ color: '#0f0f0f', minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.2,
                      color: active ? s.color : '#0f0f0f',
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {s.label}
                    </div>
                    <div style={{ fontSize: 10, color: '#7a7a7a', marginTop: 2 }}>{s.desc}</div>
                  </div>
                </div>

                {active ? (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginLeft: 8 }}>
                    <input type="range" min={0.05} max={1} step={0.05} value={vol}
                      onChange={e => changeVol(s.id, parseFloat(e.target.value))}
                      style={{ width: 70, accentColor: s.color, cursor: 'pointer' }}
                      onClick={e => e.stopPropagation()} />
                    <div style={{ display: 'flex', alignItems: 'flex-end', height: 26, gap: 2, marginLeft: 2 }}>
                      {[0.2, 0.4, 0.6, 0.8].map((d, i) => (
                        <div key={i} style={{
                          width: 2, height: 4, background: 'limegreen', borderRadius: 5,
                          animation: `sonidosBar 1s ${d}s infinite`,
                        }} />
                      ))}
                    </div>
                  </div>
                ) : (
                  <div onClick={() => toggle(s.id)} style={{
                    height: '1.6em', width: '1.6em', marginLeft: 8,
                    clipPath: 'polygon(50% 50%, 100% 50%, 75% 6.6%)',
                    background: '#000', transform: 'rotate(-90deg)',
                  }} />
                )}
              </div>
            );
          })}
        </div>

        {/* Temporizador */}
        {anyPlaying && (
          <div style={{ background: p.surface, borderRadius: 15, padding: 18, marginTop: 16,
            boxShadow: `0 8px 26px ${p.ink}10, 0 0 0 1px ${p.line}` }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: p.ink, marginBottom: 14,
              display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span>Temporizador</span>
              {timeLeft !== null && (
                <span style={{ fontFamily: 'monospace', fontSize: 18, color: p.primaryDeep }}>
                  {fmt(timeLeft)}
                </span>
              )}
            </div>

            {timeLeft !== null ? (
              <div>
                <div style={{ height: 6, borderRadius: 3, background: p.line,
                  overflow: 'hidden', marginBottom: 14 }}>
                  <div style={{
                    height: '100%', borderRadius: 3, background: p.primaryDeep,
                    width: `${(timeLeft / (timerMin * 60)) * 100}%`,
                    transition: 'width 1s linear',
                  }} />
                </div>
                <button onClick={cancelTimer} style={{
                  width: '100%', padding: '10px', borderRadius: 12,
                  border: `1px solid ${p.line}`, background: 'transparent',
                  color: p.inkSoft, fontSize: 13, fontWeight: 600, cursor: 'pointer',
                }}>Cancelar</button>
              </div>
            ) : (
              <>
                {/* Presets */}
                <div style={{ display: 'flex', gap: 8, marginBottom: 10 }}>
                  {[15, 30, 45, 60].map(min => (
                    <button key={min} className="timer-preset-btn"
                      onClick={() => startTimer(min)}
                      style={{ borderColor: p.line, color: p.ink }}>
                      {min}m
                    </button>
                  ))}
                </div>
                {/* Personalizado */}
                <div style={{ display: 'flex', gap: 8 }}>
                  <input
                    type="number" min={1} max={480}
                    placeholder="min"
                    value={customMin}
                    onChange={e => setCustomMin(e.target.value)}
                    onKeyDown={e => e.key === 'Enter' && startCustomTimer()}
                    style={{
                      width: 72, padding: '9px 10px', borderRadius: 12,
                      border: `1px solid ${p.line}`, background: p.bg,
                      color: p.ink, fontSize: 13, outline: 'none',
                      textAlign: 'center',
                    }}
                  />
                  <button onClick={startCustomTimer}
                    disabled={!customMin || parseInt(customMin) < 1}
                    style={{
                      flex: 1, padding: '9px', borderRadius: 12,
                      border: `1px solid ${p.line}`, background: 'transparent',
                      color: customMin && parseInt(customMin) >= 1 ? p.primaryDeep : p.inkMute,
                      fontSize: 13, fontWeight: 600, cursor: 'pointer',
                    }}>
                    Personalizado
                  </button>
                </div>
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
