/* global React */
// ============================================================
// Farm — Dashboard VPS Instagram (LDPlayer orchestrator)
// ============================================================
const { useState, useEffect, useCallback } = React;

const STEPS = ['login','pfp','bio','story','warmup','reels'];
const STEP_COLORS = {
  login:  '#7c5cff', pfp: '#22d3ee', bio: '#00e08a',
  story:  '#f5b942', warmup: '#fb923c', reels: '#ff7eb6',
};
const STATUS_COLORS = {
  pending: 'var(--text-2)', running: '#22d3ee',
  failed:  '#ef4444', done: '#00e08a',
};

async function farmFetch(path, opts = {}) {
  const r = await fetch('/api/farm' + path, {
    ...opts,
    headers: { 'Content-Type': 'application/json', ...(opts.headers || {}) },
  });
  if (!r.ok) throw new Error(await r.text());
  return r.json();
}

// ---- Stat card ----
function StatCard({ label, value, color }) {
  return React.createElement('div', {
    style: {
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 12, padding: '16px 20px', minWidth: 110, textAlign: 'center',
    }
  },
    React.createElement('div', { style: { fontSize: 28, fontWeight: 700, color: color || 'var(--accent)' } }, value),
    React.createElement('div', { style: { fontSize: 12, color: 'var(--text-2)', marginTop: 4 } }, label)
  );
}

// ---- Step badge ----
function StepBadge({ step }) {
  return React.createElement('span', {
    style: {
      background: (STEP_COLORS[step] || '#888') + '22',
      color: STEP_COLORS[step] || '#888',
      border: `1px solid ${STEP_COLORS[step] || '#888'}44`,
      borderRadius: 6, padding: '2px 8px', fontSize: 11, fontWeight: 600,
    }
  }, step);
}

// ---- Status dot ----
function StatusDot({ status }) {
  const color = STATUS_COLORS[status] || 'var(--text-2)';
  return React.createElement('span', {
    style: {
      display: 'inline-block', width: 8, height: 8,
      borderRadius: '50%', background: color,
      boxShadow: status === 'running' ? `0 0 6px ${color}` : 'none',
      marginRight: 6,
    }
  });
}

// ---- Accounts table ----
function AccountsTable({ accounts, onSelect }) {
  return React.createElement('div', { style: { overflowX: 'auto' } },
    React.createElement('table', {
      style: { width: '100%', borderCollapse: 'collapse', fontSize: 13 }
    },
      React.createElement('thead', null,
        React.createElement('tr', { style: { color: 'var(--text-2)', textAlign: 'left' } },
          ['ID','Username','Step','Status','Phase','Next action','Errors'].map(h =>
            React.createElement('th', {
              key: h,
              style: { padding: '8px 12px', borderBottom: '1px solid var(--border)', fontWeight: 600 }
            }, h)
          )
        )
      ),
      React.createElement('tbody', null,
        accounts.map(a =>
          React.createElement('tr', {
            key: a.id,
            onClick: () => onSelect(a),
            style: {
              cursor: 'pointer', transition: 'background .15s',
              borderBottom: '1px solid var(--border)',
            },
            onMouseEnter: e => e.currentTarget.style.background = 'var(--surface-2)',
            onMouseLeave: e => e.currentTarget.style.background = '',
          },
            React.createElement('td', { style: { padding: '8px 12px', color: 'var(--text-2)' } }, a.id),
            React.createElement('td', { style: { padding: '8px 12px', fontWeight: 500 } }, a.username || '—'),
            React.createElement('td', { style: { padding: '8px 12px' } }, React.createElement(StepBadge, { step: a.step })),
            React.createElement('td', { style: { padding: '8px 12px' } },
              React.createElement(StatusDot, { status: a.status }), a.status),
            React.createElement('td', { style: { padding: '8px 12px', color: 'var(--text-2)' } },
              a.step === 'reels' ? `P${a.reels_phase} · ${a.reels_today}/day` : '—'),
            React.createElement('td', { style: { padding: '8px 12px', color: 'var(--text-2)', fontSize: 12 } },
              a.next_action_at ? new Date(a.next_action_at).toLocaleString('fr-FR', { dateStyle:'short', timeStyle:'short' }) : '—'),
            React.createElement('td', { style: { padding: '8px 12px', color: a.error_count > 0 ? '#ef4444' : 'var(--text-2)' } },
              a.error_count || 0)
          )
        )
      )
    )
  );
}

// ---- Account detail modal ----
function AccountModal({ account, onClose }) {
  const [logs, setLogs] = useState([]);

  useEffect(() => {
    farmFetch(`/accounts/${account.id}/logs`).then(setLogs).catch(() => {});
  }, [account.id]);

  return React.createElement('div', {
    style: {
      position: 'fixed', inset: 0, background: '#000a', zIndex: 1000,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    },
    onClick: onClose,
  },
    React.createElement('div', {
      style: {
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 16, padding: 28, width: '90%', maxWidth: 560,
        maxHeight: '80vh', overflowY: 'auto',
      },
      onClick: e => e.stopPropagation(),
    },
      React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', marginBottom: 20 } },
        React.createElement('div', { style: { fontWeight: 700, fontSize: 16 } },
          account.username || `Account #${account.id}`),
        React.createElement('button', {
          onClick: onClose,
          style: { background: 'none', border: 'none', color: 'var(--text-2)', fontSize: 20, cursor: 'pointer' }
        }, '×')
      ),
      React.createElement('div', { style: { display: 'flex', gap: 10, marginBottom: 20, flexWrap: 'wrap' } },
        React.createElement(StepBadge, { step: account.step }),
        React.createElement('span', { style: { color: STATUS_COLORS[account.status], fontSize: 13 } }, account.status),
        account.step === 'reels' && React.createElement('span', {
          style: { color: 'var(--text-2)', fontSize: 12 }
        }, `Phase ${account.reels_phase} · ${account.reels_today} reels today`)
      ),
      account.last_error && React.createElement('div', {
        style: { background: '#ef444422', border: '1px solid #ef444455', borderRadius: 8,
                 padding: '8px 12px', marginBottom: 16, fontSize: 12, color: '#ef4444' }
      }, '⚠ ', account.last_error),
      React.createElement('div', { style: { fontWeight: 600, marginBottom: 10, fontSize: 13 } }, 'Logs récents'),
      logs.length === 0
        ? React.createElement('div', { style: { color: 'var(--text-2)', fontSize: 12 } }, 'Aucun log')
        : logs.map((l, i) =>
            React.createElement('div', {
              key: i,
              style: {
                display: 'flex', gap: 10, alignItems: 'flex-start',
                padding: '6px 0', borderBottom: '1px solid var(--border)', fontSize: 12,
              }
            },
              React.createElement('span', { style: { color: 'var(--text-2)', minWidth: 130 } },
                new Date(l.at).toLocaleString('fr-FR', { dateStyle:'short', timeStyle:'short' })),
              React.createElement(StepBadge, { step: l.step }),
              React.createElement('span', {
                style: { color: l.status === 'error' ? '#ef4444' : l.status === 'completed' ? '#00e08a' : 'var(--text-2)' }
              }, l.status),
              l.message && React.createElement('span', { style: { color: 'var(--text-2)' } }, l.message)
            )
          )
    )
  );
}

// ---- Main Farm page ----
function FarmPage() {
  const [stats, setStats]       = useState(null);
  const [accounts, setAccounts] = useState([]);
  const [total, setTotal]       = useState(0);
  const [page, setPage]         = useState(1);
  const [stepFilter, setStep]   = useState('');
  const [selected, setSelected] = useState(null);
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState(null);
  const [configOpen, setConfig] = useState(false);
  const [farmApiUrl, setFarmApiUrl]     = useState('');
  const [farmApiSecret, setFarmApiSecret] = useState('');

  const load = useCallback(async () => {
    setLoading(true); setError(null);
    try {
      const [s, a] = await Promise.all([
        farmFetch('/stats'),
        farmFetch(`/accounts?page=${page}&limit=50${stepFilter ? '&step='+stepFilter : ''}`),
      ]);
      setStats(s);
      setAccounts(a.accounts);
      setTotal(a.total);
    } catch(e) {
      setError(e.message);
    } finally { setLoading(false); }
  }, [page, stepFilter]);

  useEffect(() => { load(); }, [load]);
  useEffect(() => { const t = setInterval(load, 30000); return () => clearInterval(t); }, [load]);

  const saveConfig = async () => {
    await fetch('/api/farm-config', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ farm_api_url: farmApiUrl, farm_api_secret: farmApiSecret }),
    });
    setConfig(false);
    load();
  };

  return React.createElement('div', { style: { padding: '24px 28px', maxWidth: 1200, margin: '0 auto' } },
    // Header
    React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 } },
      React.createElement('div', null,
        React.createElement('h2', { style: { margin: 0, fontWeight: 700 } }, '🖥 VPS Farm'),
        React.createElement('div', { style: { color: 'var(--text-2)', fontSize: 13, marginTop: 4 } },
          'LDPlayer orchestrator — Hetzner AX52')
      ),
      React.createElement('div', { style: { display: 'flex', gap: 10 } },
        React.createElement('button', {
          onClick: load,
          style: {
            background: 'var(--surface-2)', border: '1px solid var(--border)',
            borderRadius: 8, padding: '8px 16px', color: 'var(--text)', cursor: 'pointer', fontSize: 13,
          }
        }, loading ? '⟳ Chargement…' : '↻ Actualiser'),
        React.createElement('button', {
          onClick: () => setConfig(true),
          style: {
            background: 'var(--accent)', border: 'none',
            borderRadius: 8, padding: '8px 16px', color: '#000', cursor: 'pointer', fontSize: 13, fontWeight: 600,
          }
        }, '⚙ Config VPS')
      )
    ),

    // Error
    error && React.createElement('div', {
      style: { background: '#ef444422', border: '1px solid #ef4444', borderRadius: 10,
               padding: '12px 16px', marginBottom: 20, color: '#ef4444', fontSize: 13 }
    }, '⚠ ', error),

    // Stats
    stats && React.createElement('div', {
      style: { display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 28 }
    },
      React.createElement(StatCard, { label: 'Running', value: stats.running, color: '#22d3ee' }),
      ...STEPS.map(s => React.createElement(StatCard, { key: s, label: s, value: stats[s] || 0, color: STEP_COLORS[s] })),
      React.createElement(StatCard, { label: 'Failed', value: stats.failed || 0, color: '#ef4444' }),
    ),

    // Filters
    React.createElement('div', { style: { display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' } },
      ['', ...STEPS].map(s =>
        React.createElement('button', {
          key: s || 'all',
          onClick: () => { setStep(s); setPage(1); },
          style: {
            background: stepFilter === s ? (STEP_COLORS[s] || 'var(--accent)') : 'var(--surface-2)',
            color: stepFilter === s ? '#000' : 'var(--text)',
            border: '1px solid var(--border)', borderRadius: 8,
            padding: '6px 14px', fontSize: 12, cursor: 'pointer', fontWeight: stepFilter === s ? 700 : 400,
          }
        }, s || 'Tous')
      )
    ),

    // Table
    React.createElement('div', {
      style: { background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }
    },
      React.createElement(AccountsTable, { accounts, onSelect: setSelected }),
      React.createElement('div', {
        style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                 padding: '12px 16px', borderTop: '1px solid var(--border)', fontSize: 13, color: 'var(--text-2)' }
      },
        React.createElement('span', null, `${total} comptes au total`),
        React.createElement('div', { style: { display: 'flex', gap: 8 } },
          React.createElement('button', {
            disabled: page <= 1,
            onClick: () => setPage(p => p - 1),
            style: { background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 6,
                     padding: '4px 12px', cursor: page <= 1 ? 'default' : 'pointer', opacity: page <= 1 ? .4 : 1 }
          }, '←'),
          React.createElement('span', null, `Page ${page}`),
          React.createElement('button', {
            disabled: page * 50 >= total,
            onClick: () => setPage(p => p + 1),
            style: { background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 6,
                     padding: '4px 12px', cursor: page*50>=total ? 'default' : 'pointer', opacity: page*50>=total ? .4 : 1 }
          }, '→')
        )
      )
    ),

    // Account modal
    selected && React.createElement(AccountModal, { account: selected, onClose: () => setSelected(null) }),

    // Config modal
    configOpen && React.createElement('div', {
      style: { position: 'fixed', inset: 0, background: '#000a', zIndex: 1000,
               display: 'flex', alignItems: 'center', justifyContent: 'center' },
      onClick: () => setConfig(false),
    },
      React.createElement('div', {
        style: { background: 'var(--surface)', border: '1px solid var(--border)',
                 borderRadius: 16, padding: 28, width: '90%', maxWidth: 440 },
        onClick: e => e.stopPropagation(),
      },
        React.createElement('h3', { style: { margin: '0 0 20px' } }, '⚙ Config VPS Farm'),
        React.createElement('label', { style: { display: 'block', marginBottom: 6, fontSize: 13 } }, 'URL API VPS (ex: http://1.2.3.4:8080)'),
        React.createElement('input', {
          value: farmApiUrl, onChange: e => setFarmApiUrl(e.target.value),
          placeholder: 'http://YOUR_VPS_IP:8080',
          style: { width: '100%', background: 'var(--surface-2)', border: '1px solid var(--border)',
                   borderRadius: 8, padding: '10px 14px', color: 'var(--text)', marginBottom: 14,
                   boxSizing: 'border-box', fontSize: 13 }
        }),
        React.createElement('label', { style: { display: 'block', marginBottom: 6, fontSize: 13 } }, 'Secret (FARM_SECRET)'),
        React.createElement('input', {
          type: 'password', value: farmApiSecret, onChange: e => setFarmApiSecret(e.target.value),
          placeholder: 'votre clé secrète',
          style: { width: '100%', background: 'var(--surface-2)', border: '1px solid var(--border)',
                   borderRadius: 8, padding: '10px 14px', color: 'var(--text)', marginBottom: 20,
                   boxSizing: 'border-box', fontSize: 13 }
        }),
        React.createElement('div', { style: { display: 'flex', gap: 10, justifyContent: 'flex-end' } },
          React.createElement('button', {
            onClick: () => setConfig(false),
            style: { background: 'var(--surface-2)', border: '1px solid var(--border)',
                     borderRadius: 8, padding: '10px 20px', cursor: 'pointer', fontSize: 13 }
          }, 'Annuler'),
          React.createElement('button', {
            onClick: saveConfig,
            style: { background: 'var(--accent)', border: 'none', borderRadius: 8,
                     padding: '10px 20px', color: '#000', cursor: 'pointer', fontSize: 13, fontWeight: 700 }
          }, 'Sauvegarder')
        )
      )
    )
  );
}
