// V3 — animated scenes, theme + i18n aware.

function useInView(ref, threshold = 0.35) {
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { threshold });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [ref, threshold]);
  return inView;
}

function useTimeline(playing, durationMs) {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    if (!playing) return;
    let raf, start = performance.now();
    const loop = (now) => {
      const e = Math.min(1, (now - start) / durationMs);
      setT(e);
      if (e < 1) raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [playing, durationMs]);
  return t;
}

function PlayingWaveform({ bars = 28, height = 30, progress }) {
  const T = useTheme();
  const pattern = [0.35,0.6,0.9,0.5,0.75,0.4,1,0.65,0.85,0.5,0.3,0.7,0.9,0.55,0.8,0.4,0.65,0.95,0.55,0.7,0.35,0.8,0.6,0.45,0.7,0.9,0.5,0.6];
  const active = Math.floor(progress * bars);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 3, height }}>
      {Array.from({ length: bars }).map((_, i) => {
        const h = pattern[i % pattern.length] * height;
        const played = i < active;
        return (
          <div key={i} style={{
            width: 3, height: h, borderRadius: 2,
            background: played ? T.corallo : T.viola,
            opacity: played ? 1 : 0.4,
            transition: 'opacity .2s, background .2s',
          }} />
        );
      })}
    </div>
  );
}

function VoiceScene({ vertical }) {
  const T = useTheme();
  const t_ = useT();
  const L = t_.moments.m2.labels;
  const { isMobile } = useViewport();
  const ref = React.useRef(null);
  const inView = useInView(ref);
  const [cycle, setCycle] = React.useState(0);
  const t = useTimeline(inView, 7000);

  React.useEffect(() => {
    if (t >= 1 && inView) {
      const id = setTimeout(() => setCycle((c) => c + 1), 2500);
      return () => clearTimeout(id);
    }
  }, [t, inView]);
  // eslint-disable-next-line
  React.useEffect(() => {}, [cycle]);

  const audio = Math.min(1, t / 0.35);
  const textPhase = Math.max(0, Math.min(1, (t - 0.35) / 0.40));
  const chipsPhase = Math.max(0, Math.min(1, (t - 0.75) / 0.15));
  const agendaPhase = Math.max(0, Math.min(1, (t - 0.90) / 0.10));

  const fullText = vertical.voice.transcript;
  const typed = fullText.slice(0, Math.floor(fullText.length * textPhase));
  const parsed = vertical.voice.parsed;

  return (
    <div ref={ref} style={{
      background: T.ink2, border: `1px solid ${T.line}`,
      borderRadius: 16, padding: isMobile ? 18 : 24,
      display: 'grid',
      gridTemplateColumns: isMobile ? '1fr' : '1fr 1px 1fr',
      gap: isMobile ? 20 : 28,
    }}>
      <div>
        <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.5, color: T.corallo, marginBottom: 14 }}>
          {L.audio}
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 14,
          padding: '14px 16px', borderRadius: 12,
          background: T.violaSoft, border: `1px solid ${T.violaBorder}`,
        }}>
          <div style={{ width: 36, height: 36, borderRadius: 18, background: T.corallo, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <svg width="13" height="14" viewBox="0 0 12 14" fill="#fff"><path d="M3 1l7 6-7 6z"/></svg>
          </div>
          <div style={{ flex: 1 }}><PlayingWaveform progress={audio} /></div>
          <div style={{ fontSize: 11, color: T.muted, fontVariantNumeric: 'tabular-nums', fontFamily: T.mono }}>
            {(audio * 47).toFixed(0).padStart(2, '0')}s
          </div>
        </div>
        <div style={{ marginTop: 18 }}>
          <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.5, color: T.faint, marginBottom: 10 }}>
            {L.transcript}
          </div>
          <div style={{ fontSize: 14, lineHeight: 1.55, color: T.text, minHeight: 84 }}>
            "{typed}
            {textPhase < 1 && <span style={{ display: 'inline-block', width: 2, height: 14, background: T.corallo, marginLeft: 2, verticalAlign: 'middle', animation: 'hello-blink 1s infinite' }} />}
            {textPhase >= 1 && '"'}
          </div>
        </div>
      </div>

      {!isMobile && <div style={{ background: T.line }} />}

      <div>
        <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.5, color: T.corallo, marginBottom: 14 }}>
          {L.intent}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, opacity: chipsPhase, transform: `translateY(${(1 - chipsPhase) * 8}px)` }}>
          <ParsedRow kLabel={L.parsed.cliente} v={parsed.who} />
          <ParsedRow kLabel={L.parsed.azione} v={parsed.action} accent={['urgenza','anticipa','urgente','emergenza','sposta serie'].includes(parsed.action)} />
          {parsed.from && <ParsedRow kLabel={L.parsed.da} v={parsed.from} strike />}
          <ParsedRow kLabel={L.parsed.a} v={parsed.to} accent />
        </div>
        <div style={{
          marginTop: 22, padding: '12px 14px', borderRadius: 10,
          background: 'rgba(244,63,94,0.08)', border: `1px solid rgba(244,63,94,0.25)`,
          opacity: agendaPhase, transform: `translateY(${(1 - agendaPhase) * 6}px)`,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <div style={{ width: 20, height: 20, borderRadius: 10, background: T.corallo, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <svg width="10" height="8" viewBox="0 0 10 8" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 4l3 3 5-6"/></svg>
          </div>
          <div style={{ fontSize: 12, color: T.text, lineHeight: 1.4 }}>
            <strong>{L.confirm.strong.replace('{staff}', vertical.staffName)}</strong><br/>
            <span style={{ color: T.muted }}>{L.confirm.weak}</span>
          </div>
        </div>
      </div>
      <style>{`@keyframes hello-blink{0%,50%{opacity:1}51%,100%{opacity:0}}`}</style>
    </div>
  );
}

function ParsedRow({ kLabel, v, accent, strike }) {
  const T = useTheme();
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, fontFamily: T.font }}>
      <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1, color: T.faint, width: 72, textTransform: 'uppercase' }}>
        {kLabel}
      </div>
      <div style={{ fontSize: 14, fontWeight: 500, color: accent ? T.corallo : T.text, textDecoration: strike ? 'line-through' : 'none', opacity: strike ? 0.5 : 1 }}>
        {v}
      </div>
    </div>
  );
}

function ReminderScene({ vertical }) {
  const T = useTheme();
  const t_ = useT();
  const L = t_.moments.m3.labels;
  const ref = React.useRef(null);
  const inView = useInView(ref);
  const [cycle, setCycle] = React.useState(0);
  const t = useTimeline(inView, 6500);
  React.useEffect(() => {
    if (t >= 1 && inView) {
      const id = setTimeout(() => setCycle((c) => c + 1), 2500);
      return () => clearTimeout(id);
    }
  }, [t, inView]);
  // eslint-disable-next-line
  React.useEffect(() => {}, [cycle]);

  const aiP = Math.max(0, Math.min(1, t / 0.25));
  const deliveredP = Math.max(0, Math.min(1, (t - 0.25) / 0.25));
  const typingP = Math.max(0, Math.min(1, (t - 0.5) / 0.20));
  const replyP = Math.max(0, Math.min(1, (t - 0.7) / 0.15));
  const confirmP = Math.max(0, Math.min(1, (t - 0.85) / 0.15));
  const showTyping = typingP > 0 && replyP < 0.2;

  return (
    <div ref={ref} style={{
      background: T.ink2, border: `1px solid ${T.line}`,
      borderRadius: 16, padding: 20, maxWidth: 440, width: '100%',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingBottom: 12, borderBottom: `1px solid ${T.line}`, marginBottom: 16 }}>
        <div style={{ width: 32, height: 32, borderRadius: 16, background: 'rgba(37,211,102,0.2)', border: '1px solid rgba(37,211,102,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="#25D366"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: T.text }}>
            {vertical.voice.parsed.who.replace(/\s*\(.*/, '')}
          </div>
          <div style={{ fontSize: 10, color: T.muted, fontFamily: T.mono, letterSpacing: 0.5 }}>
            {L.header}
          </div>
        </div>
        <div style={{ fontSize: 10, padding: '3px 7px', background: 'rgba(37,211,102,0.12)', border: '1px solid rgba(37,211,102,0.3)', borderRadius: 5, color: '#25D366', fontFamily: T.mono, letterSpacing: 1 }}>WA</div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minHeight: 260 }}>
        <div style={{ alignSelf: 'flex-start', maxWidth: '82%', opacity: aiP, transform: `translateY(${(1 - aiP) * 6}px)` }}>
          <div style={{
            background: T.ink3, border: `1px solid ${T.line}`,
            padding: '10px 14px', borderRadius: '14px 14px 14px 2px',
            fontSize: 13, lineHeight: 1.45, color: T.text,
          }}>
            {vertical.reminder.msg}
          </div>
          <div style={{ fontSize: 9, color: T.faint, marginTop: 4, display: 'flex', alignItems: 'center', gap: 4, fontFamily: T.mono, letterSpacing: 0.5 }}>
            14:00
            <span style={{ opacity: deliveredP, color: deliveredP > 0.9 ? '#3b82f6' : T.faint }}>✓✓</span>
            <span style={{ opacity: deliveredP }}>· {L.delivered}</span>
          </div>
        </div>
        {showTyping && (
          <div style={{ alignSelf: 'flex-end', padding: '8px 14px', background: 'rgba(139,92,246,0.15)', borderRadius: '14px 14px 2px 14px', display: 'flex', gap: 4 }}>
            {[0, 1, 2].map((i) => (
              <span key={i} style={{
                width: 6, height: 6, borderRadius: 3, background: T.muted,
                animation: `hello-typing 1.2s infinite`, animationDelay: `${i * 0.15}s`,
              }} />
            ))}
          </div>
        )}
        {replyP > 0 && (
          <div style={{ alignSelf: 'flex-end', maxWidth: '70%', opacity: replyP, transform: `translateY(${(1 - replyP) * 6}px)` }}>
            <div style={{
              background: T.violaSoft, border: `1px solid ${T.violaBorder}`,
              padding: '10px 14px', borderRadius: '14px 14px 2px 14px', fontSize: 13, color: T.text,
            }}>{vertical.reminder.reply}</div>
            <div style={{ fontSize: 9, color: T.faint, marginTop: 4, textAlign: 'right', fontFamily: T.mono, letterSpacing: 0.5 }}>14:02</div>
          </div>
        )}
        {confirmP > 0 && (
          <div style={{
            alignSelf: 'center', marginTop: 8, opacity: confirmP,
            padding: '6px 12px', borderRadius: 999,
            background: 'rgba(244,63,94,0.12)', border: '1px solid rgba(244,63,94,0.3)',
            fontSize: 11, color: T.corallo, fontFamily: T.mono, letterSpacing: 1, textAlign: 'center',
          }}>
            {L.confirmed}
          </div>
        )}
      </div>
      <style>{`@keyframes hello-typing{0%,60%,100%{opacity:.35;transform:translateY(0)}30%{opacity:1;transform:translateY(-2px)}}`}</style>
    </div>
  );
}

Object.assign(window, { VoiceScene, ReminderScene });
