// FOOTPASS Messenger v2 · call screens (voice out/in/active, video w/ real webcam)
const { useState: useStateK, useEffect: useEffectK, useRef: useRefK } = React;

function fmtDur(s) {
  return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
}

// Round control button with label
function CallBtn({ icon, label, on, danger, onClick, disabled }) {
  return (
    <div className="callbtn-wrap">
      <button
        className={`callbtn ${on ? 'on' : ''} ${danger ? 'danger' : ''}`}
        onClick={onClick}
        disabled={disabled}
        aria-label={label}
      >{icon}</button>
      <span className="callbtn-label">{label}</span>
    </div>
  );
}

// ── VOICE CALL · outgoing ringing → connected (or starts active) ──
function VoiceCall({ lang, peer, startActive = false, onEnd, onVideo }) {
  const p = peer || FP_PEERS.lucas;
  const t = (k) => fpT(lang, k);
  const [phase, setPhase] = useStateK(startActive ? 'active' : 'calling'); // calling → ringing → active
  const [secs, setSecs] = useStateK(0);
  const [muted, setMuted] = useStateK(false);
  const [speaker, setSpeaker] = useStateK(false);

  useEffectK(() => {
    if (phase === 'calling') {
      const id = setTimeout(() => setPhase('ringing'), 1300);
      return () => clearTimeout(id);
    }
    if (phase === 'ringing') {
      const id = setTimeout(() => setPhase('active'), 2800);
      return () => clearTimeout(id);
    }
  }, [phase]);

  useEffectK(() => {
    if (phase !== 'active') return;
    const id = setInterval(() => setSecs(s => s + 1), 1000);
    return () => clearInterval(id);
  }, [phase]);

  const active = phase === 'active';
  const sub = phase === 'calling' ? t('connecting') : phase === 'ringing' ? t('ringing') : fmtDur(secs);

  return (
    <div className="callscreen" data-screen-label="Appel vocal">
      <div className="call-bg"></div>
      <FPStatusBar light />
      <div className="call-center">
        <div className={`call-avatar-wrap ${!active ? 'pulsing' : ''}`}>
          <span className="call-ring r1"></span>
          <span className="call-ring r2"></span>
          <FPAvatar size={108} initials={p.initials} src={p.photo} />
        </div>
        <div className="call-name">{window.fpUpperLast(p.name)}</div>
        <div className={`call-sub ${active ? 'timer' : ''}`}>{sub}</div>
      </div>
      <div className="call-controls">
        <CallBtn icon={<FPIcon.MicOff c="#fff" s={22} />} label={t('mute')} on={muted} onClick={() => setMuted(m => !m)} disabled={!active} />
        <CallBtn icon={<FPIcon.SpeakerOn c="#fff" s={22} />} label={t('speaker')} on={speaker} onClick={() => setSpeaker(s => !s)} disabled={!active} />
        <CallBtn icon={<FPIcon.VideoFill c="#fff" s={24} />} label={t('video')} onClick={() => onVideo && onVideo(secs)} disabled={!active} />
        <CallBtn icon={<FPIcon.PhoneDown c="#fff" s={28} />} label={t('endCall')} danger onClick={() => onEnd(active ? secs : null)} />
      </div>
    </div>
  );
}

// ── INCOMING CALL · accept / decline ──
function IncomingCall({ lang, peer, video = false, onAccept, onDecline }) {
  const p = peer || FP_PEERS.lucas;
  const t = (k) => fpT(lang, k);
  return (
    <div className="callscreen incoming" data-screen-label="Appel entrant">
      <div className="call-bg"></div>
      <FPStatusBar light />
      <div className="call-center">
        <div className="call-avatar-wrap pulsing">
          <span className="call-ring r1"></span>
          <span className="call-ring r2"></span>
          <FPAvatar size={108} initials={p.initials} src={p.photo} />
        </div>
        <div className="call-name">{window.fpUpperLast(p.name)}</div>
        <div className="call-sub">{video ? t('incomingVideo') : t('incomingCall')}</div>
      </div>
      <div className="call-controls incoming-controls">
        <div className="callbtn-wrap">
          <button className="callbtn danger big" onClick={onDecline} aria-label={t('decline')}>
            <FPIcon.PhoneDown c="#fff" s={30} />
          </button>
          <span className="callbtn-label">{t('decline')}</span>
        </div>
        <div className="callbtn-wrap">
          <button className="callbtn accept big" onClick={onAccept} aria-label={t('accept')}>
            {video ? <FPIcon.VideoFill c="#fff" s={26} /> : <FPIcon.PhoneFill c="#fff" s={26} />}
          </button>
          <span className="callbtn-label">{t('accept')}</span>
        </div>
      </div>
    </div>
  );
}

// ── VIDEO CALL · remote simulated, self = real webcam ──
function VideoCall({ lang, peer, onEnd, startSecs = 0 }) {
  const p = peer || FP_PEERS.lucas;
  const t = (k) => fpT(lang, k);
  const [phase, setPhase] = useStateK('connecting');
  const [secs, setSecs] = useStateK(startSecs);
  const [muted, setMuted] = useStateK(false);
  const [camOff, setCamOff] = useStateK(false);
  const [mirror, setMirror] = useStateK(true);
  const [camState, setCamState] = useStateK('loading'); // loading | on | denied
  const [pip, setPip] = useStateK({ x: 0, y: 0 });
  const videoRef = useRefK(null);
  const streamRef = useRefK(null);
  const dragRef = useRefK(null);

  useEffectK(() => {
    const id = setTimeout(() => setPhase('active'), 2200);
    return () => clearTimeout(id);
  }, []);

  useEffectK(() => {
    if (phase !== 'active') return;
    const id = setInterval(() => setSecs(s => s + 1), 1000);
    return () => clearInterval(id);
  }, [phase]);

  // Real webcam for self feed
  useEffectK(() => {
    let cancelled = false;
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' }, audio: false })
        .then((stream) => {
          if (cancelled) { stream.getTracks().forEach(tr => tr.stop()); return; }
          streamRef.current = stream;
          if (videoRef.current) videoRef.current.srcObject = stream;
          setCamState('on');
        })
        .catch(() => { if (!cancelled) setCamState('denied'); });
    } else {
      setCamState('denied');
    }
    return () => {
      cancelled = true;
      if (streamRef.current) streamRef.current.getTracks().forEach(tr => tr.stop());
    };
  }, []);

  useEffectK(() => {
    if (streamRef.current) streamRef.current.getVideoTracks().forEach(tr => { tr.enabled = !camOff; });
  }, [camOff]);

  // Draggable PIP
  const onPipDown = (e) => {
    dragRef.current = { sx: e.clientX, sy: e.clientY, ox: pip.x, oy: pip.y };
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onPipMove = (e) => {
    const d = dragRef.current;
    if (!d) return;
    setPip({
      x: Math.max(-250, Math.min(0, d.ox + (e.clientX - d.sx))),
      y: Math.max(-480, Math.min(0, d.oy + (e.clientY - d.sy))),
    });
  };
  const onPipUp = () => { dragRef.current = null; };

  return (
    <div className="callscreen video" data-screen-label="Appel vidéo">
      {/* Remote feed · simulated */}
      <div className="vid-remote">
        <div className="vid-remote-anim"></div>
        <div className="vid-remote-center">
          <FPAvatar size={88} initials={p.initials} src={p.photo} />
          <div className="vid-remote-name">{window.fpUpperLast(p.name)}</div>
        </div>
      </div>

      <FPStatusBar light />

      {/* Top chip: secure + timer */}
      <div className="vid-top">
        <div className="vid-chip"><span>{phase === 'connecting' ? t('connecting') : fmtDur(secs)}</span></div>
      </div>

      {/* Self PIP · real webcam */}
      <div
        className="vid-pip"
        style={{ transform: `translate(${pip.x}px, ${pip.y}px)` }}
        onPointerDown={onPipDown} onPointerMove={onPipMove} onPointerUp={onPipUp}
      >
        <video
          ref={videoRef} autoPlay playsInline muted
          className={`vid-self ${mirror ? 'mirror' : ''} ${camOff || camState !== 'on' ? 'hidden' : ''}`}
        ></video>
        {(camOff || camState !== 'on') && (
          <div className="vid-self-off">
            <FPAvatar size={36} initials="AD" />
            {camState === 'denied' && !camOff && <span className="vid-self-note">{t('camDenied')}</span>}
          </div>
        )}
      </div>

      <div className="call-controls vid-controls">
        <CallBtn icon={<FPIcon.MicOff c="#fff" s={22} />} label={t('mute')} on={muted} onClick={() => setMuted(m => !m)} />
        <CallBtn icon={<FPIcon.CamOff c="#fff" s={24} />} label={t('cameraOff')} on={camOff} onClick={() => setCamOff(c => !c)} />
        <CallBtn icon={<FPIcon.CamFlip c="#fff" s={22} />} label={t('flip')} onClick={() => setMirror(m => !m)} />
        <CallBtn icon={<FPIcon.PhoneDown c="#fff" s={28} />} label={t('endCall')} danger onClick={() => onEnd(phase === 'active' ? secs : null)} />
      </div>
    </div>
  );
}

Object.assign(window, { VoiceCall, IncomingCall, VideoCall, fmtDur });
