/* global React */
// Cloud Phone Automations — boutons simples, pas de blocs
const { useState, useEffect, useCallback } = React;

function countdown(isoStr) {
  if (!isoStr) return null;
  const diff = new Date(isoStr + 'Z') - Date.now();
  if (diff <= 0) return "maintenant";
  const h = Math.floor(diff / 3600000);
  const m = Math.floor((diff % 3600000) / 60000);
  const s = Math.floor((diff % 60000) / 1000);
  if (h > 0) return `${h}h ${m}m`;
  if (m > 0) return `${m}m ${s}s`;
  return `${s}s`;
}

function CloudAutomations() {
  const [phones, setPhones] = useState([]);
  const [workflows, setWorkflows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [launching, setLaunching] = useState({});
  const [tick, setTick] = useState(0);

  // Tick toutes les secondes pour le countdown
  useEffect(() => {
    const t = setInterval(() => setTick(x => x + 1), 1000);
    return () => clearInterval(t);
  }, []);

  const load = useCallback(async () => {
    try {
      const [pRes, wRes] = await Promise.all([
        fetch('/api/morelogin/phones'),
        fetch('/api/cloud-workflow/list')
      ]);
      const pData = await pRes.json();
      const wData = await wRes.json();
      setPhones(pData.phones || []);
      setWorkflows(wData.workflows || []);
    } catch(e) { console.error(e); }
    setLoading(false);
  }, []);

  useEffect(() => { load(); }, [load]);

  // Refresh workflows toutes les 30s
  useEffect(() => {
    const t = setInterval(load, 30000);
    return () => clearInterval(t);
  }, [load]);

  async function launch(phone) {
    setLaunching(l => ({ ...l, [phone.id]: true }));
    try {
      const r = await fetch('/api/cloud-workflow/start', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phoneId: String(phone.id), phoneName: phone.name })
      });
      const d = await r.json();
      if (d.ok) {
        await load();
      } else {
        alert('Erreur : ' + (d.error || 'inconnue'));
      }
    } catch(e) { alert(e.message); }
    setLaunching(l => ({ ...l, [phone.id]: false }));
  }

  // Index workflows par phone_id (dernier en date)
  const wfByPhone = {};
  for (const wf of workflows) {
    if (!wfByPhone[wf.phone_id] || wf.id > wfByPhone[wf.phone_id].id) {
      wfByPhone[wf.phone_id] = wf;
    }
  }

  const st = {
    page: { padding: 24, maxWidth: 900, margin: '0 auto' },
    title: { fontSize: 22, fontWeight: 700, color: 'var(--text)', marginBottom: 6 },
    sub: { fontSize: 13, color: 'var(--muted)', marginBottom: 24 },
    grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 },
    card: { background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 12, padding: 16 },
    phoneName: { fontWeight: 600, fontSize: 14, color: 'var(--text)', marginBottom: 4 },
    phoneId: { fontSize: 11, color: 'var(--muted)', marginBottom: 12 },
    btn: { width: '100%', padding: '10px 0', borderRadius: 8, border: 'none', background: '#238636', color: '#fff', fontWeight: 700, fontSize: 14, cursor: 'pointer' },
    btnDisabled: { background: 'var(--surface-3)', color: 'var(--muted)', cursor: 'not-allowed' },
    status: { marginTop: 10, fontSize: 12, display: 'flex', flexDirection: 'column', gap: 4 },
    step: (done) => ({ display: 'flex', alignItems: 'center', gap: 6, color: done ? '#3fb950' : 'var(--muted)' }),
    badge: (done) => ({ width: 16, height: 16, borderRadius: '50%', background: done ? '#238636' : 'var(--border-2)', display: 'inline-block', flexShrink: 0 }),
    empty: { textAlign: 'center', color: 'var(--muted)', padding: '60px 0', fontSize: 14 },
  };

  if (loading) return (
    <div style={{ ...st.page, textAlign: 'center', paddingTop: 60, color: 'var(--muted)' }}>
      Chargement…
    </div>
  );

  return (
    <div style={st.page}>
      <div style={st.title}>⚡ Automations Cloud Phone</div>
      <div style={st.sub}>
        Clique sur <strong>▶ Lancer</strong> pour démarrer le workflow sur un phone :<br />
        <span style={{ color: '#3fb950' }}>①</span> Insertion compte IG (immédiat) &nbsp;→&nbsp;
        <span style={{ color: '#d29922' }}>②</span> Jour 1 - 1er Réel (+2h auto)
      </div>

      {phones.length === 0 ? (
        <div style={st.empty}>Aucun cloud phone trouvé sur MoreLogin.</div>
      ) : (
        <div style={st.grid}>
          {phones.map(phone => {
            const wf = wfByPhone[String(phone.id)];
            const isRunning = wf && !wf.step2_done;
            const isLaunching = !!launching[phone.id];
            const step2At = wf && wf.step2_run_at;
            const timeLeft = step2At ? countdown(step2At) : null;

            return (
              <div key={phone.id} style={st.card}>
                <div style={st.phoneName}>{phone.name || 'Phone #' + phone.id}</div>
                <div style={st.phoneId}>ID: {phone.id}</div>

                <button
                  style={{ ...st.btn, ...(isRunning || isLaunching ? st.btnDisabled : {}) }}
                  disabled={isRunning || isLaunching}
                  onClick={() => launch(phone)}
                >
                  {isLaunching ? '⏳ Lancement…' : isRunning ? '🔄 En cours…' : '▶ Lancer'}
                </button>

                {wf && (
                  <div style={st.status}>
                    <div style={st.step(wf.step1_done)}>
                      <span style={st.badge(wf.step1_done)} />
                      Insertion IG {wf.step1_done ? '✓' : '…'}
                    </div>
                    <div style={st.step(wf.step2_done)}>
                      <span style={st.badge(wf.step2_done)} />
                      Jour 1 {wf.step2_done ? '✓ lancé' : timeLeft ? `dans ${timeLeft}` : '…'}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

window.CloudAutomations = CloudAutomations;
