// زمام — مُصدِّر الفيديو: يسجّل الصورة والصوت من الصفحة ويُنزّلها ملفاً
// يعتمد على animations.jsx (useTimeline) + فيديو-صوت.jsx (ZAudio)

// جسر داخل المسرح: ينشر التحكم بالساعة إلى النافذة
function ZStageControl() {
  const { setTime, setPlaying, duration } = useTimeline();
  React.useEffect(() => {
    window.__zStage = { setTime, setPlaying, duration };
  }, [setTime, setPlaying, duration]);
  return null;
}

function pickMime() {
  const cands = ['video/mp4;codecs=avc1', 'video/mp4', 'video/webm;codecs=vp9', 'video/webm;codecs=vp8', 'video/webm'];
  for (const m of cands) { if (window.MediaRecorder && MediaRecorder.isTypeSupported(m)) return m; }
  return 'video/webm';
}

function ZExportButton() {
  const [state, setState] = React.useState('idle'); // idle | recording | saving | error
  const [pct, setPct] = React.useState(0);

  const run = async () => {
    if (state === 'recording' || state === 'saving') return;
    const stage = window.__zStage;
    if (!stage) { setState('error'); return; }
    const dur = stage.duration || 128;

    // تحقق من دعم التقاط الشاشة (غير مدعوم غالباً على الجوال)
    if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
      setState('error');
      return;
    }

    let stream;
    try {
      stream = await navigator.mediaDevices.getDisplayMedia({
        video: { frameRate: 30 },
        audio: true,
        preferCurrentTab: true,
      });
    } catch (e) {
      setState('idle'); // المستخدم ألغى الاختيار
      return;
    }

    // فعّل الصوت من بدايته
    try { ZAudio.enable(); } catch (e) {}

    const mime = pickMime();
    const chunks = [];
    let rec;
    try {
      rec = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 8000000 });
    } catch (e) {
      rec = new MediaRecorder(stream);
    }
    rec.ondataavailable = (ev) => { if (ev.data && ev.data.size) chunks.push(ev.data); };
    rec.onstop = () => {
      const blob = new Blob(chunks, { type: mime.indexOf('mp4') >= 0 ? 'video/mp4' : 'video/webm' });
      const ext = mime.indexOf('mp4') >= 0 ? 'mp4' : 'webm';
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url; a.download = 'زمام-الفيديو-التشويقي.' + ext;
      document.body.appendChild(a); a.click(); a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 4000);
      stream.getTracks().forEach((t) => t.stop());
      setState('idle'); setPct(0);
    };

    // لو أوقف المستخدم المشاركة يدوياً
    stream.getVideoTracks()[0].addEventListener('ended', () => {
      if (rec.state !== 'inactive') rec.stop();
    });

    // ابدأ من الصفر
    stage.setPlaying(false);
    stage.setTime(0);
    setState('recording'); setPct(0);
    await new Promise((r) => setTimeout(r, 400));

    rec.start();
    stage.setTime(0);
    stage.setPlaying(true);

    const t0 = performance.now();
    const tick = () => {
      const el = (performance.now() - t0) / 1000;
      setPct(Math.min(100, Math.round((el / dur) * 100)));
      if (el >= dur + 0.6) {
        stage.setPlaying(false);
        try { ZAudio.disable(); } catch (e) {}
        setState('saving');
        if (rec.state !== 'inactive') rec.stop();
        return;
      }
      requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  };

  const label =
    state === 'recording' ? '⏺ يسجّل… ' + pct + '٪' :
    state === 'saving' ? '💾 يحفظ…' :
    state === 'error' ? '✕ غير مدعوم — سجّل الشاشة' :
    '⬇︎ صدّر الفيديو';

  const bg = state === 'recording' ? 'rgba(176,71,61,0.9)' : state === 'error' ? 'rgba(120,40,34,0.9)' : 'rgba(199,154,58,0.92)';

  return (
    <button onClick={run} title="يسجّل المقطع بالصوت ويُنزّله ملفاً (يعمل على الكمبيوتر)" style={{ position: 'fixed', top: 14, left: 150, zIndex: 60, background: bg, color: state === 'recording' || state === 'error' ? '#fff' : '#1a1206', border: 'none', borderRadius: 24, padding: '10px 18px', fontFamily: "'IBM Plex Sans Arabic', sans-serif", fontSize: 15, fontWeight: 700, cursor: 'pointer', direction: 'rtl', boxShadow: '0 4px 16px rgba(0,0,0,0.3)' }}>
      {label}
    </button>
  );
}

Object.assign(window, { ZStageControl, ZExportButton });
