// ─── Docker Page ─────────────────────────────────────────────────────────────
const { useState: uDKS, useEffect: uDKE, useRef: uDKR } = React;

function DockerPage() {
  const [containers, setContainers] = uDKS([]);
  const [filter, setFilter]         = uDKS('all');
  const [selectedId, setSelectedId] = uDKS(null);
  const [composeModal, setComposeModal] = uDKS(false);
  const [composeContent, setComposeContent] = uDKS('');
  const [composeName, setComposeName] = uDKS('');
  const [actionLog, setActionLog]   = uDKS([]);
  const [toast, setToast]           = uDKS(null);
  const [loading, setLoading]       = uDKS(false);

  const log = (msg, color = '#00c8ff') => {
    const ts = new Date().toLocaleTimeString('de-DE');
    setActionLog(prev => [{ ts, msg, color, id: Date.now() }, ...prev.slice(0, 19)]);
  };
  const showToast = (msg, color = '#00ff88') => { setToast({ msg, color }); setTimeout(() => setToast(null), 2500); };

  const fetchContainers = () =>
    apiClient('/api/docker/containers').then(d => { if (d) setContainers(d); }).catch(() => {});

  uDKE(() => {
    fetchContainers();
    const id = setInterval(fetchContainers, 10000);
    return () => clearInterval(id);
  }, []);

  const doAction = async (id, action) => {
    const c = containers.find(x => x.id === id);
    if (!c) return;
    try {
      if (action === 'start' || action === 'stop' || action === 'restart') {
        await apiClient(`/api/docker/containers/${id}/${action}`, { method: 'POST' });
        const colors = { start: '#00ff88', stop: '#ff2244', restart: '#ffd700' };
        const icons  = { start: '▶', stop: '■', restart: '↺' };
        log(`${icons[action]} ${action.charAt(0).toUpperCase()+action.slice(1)}ed ${c.name}`, colors[action]);
        showToast(`${c.name} ${action}ed`, colors[action]);
        setTimeout(fetchContainers, 1500);
      } else if (action === 'backup') {
        const r = await apiClient(`/api/docker/containers/${c.name}/backup`, { method: 'POST' });
        log(`💾 Backup started for ${c.name} (run: ${r?.run_id?.slice(0,8)})`, '#00c8ff');
        showToast(`Backup started for ${c.name}`);
      } else if (action === 'update') {
        const r = await apiClient(`/api/docker/containers/${c.name}/update`, { method: 'POST' });
        log(`⬆ Update started for ${c.name} (run: ${r?.run_id?.slice(0,8)})`, '#00c8ff');
        showToast(`Update started for ${c.name}`);
      }
    } catch (err) {
      log(`✖ ${action} failed for ${c.name}: ${err.message}`, '#ff2244');
      showToast(`${action} failed`, '#ff2244');
    }
  };

  const openCompose = async (c) => {
    setSelectedId(c.id);
    setComposeName(c.name);
    try {
      const data = await apiClient(`/api/docker/compose/${c.name}`);
      setComposeContent(data?.content || '');
    } catch { setComposeContent('# Could not load compose file'); }
    setComposeModal(true);
  };

  const saveCompose = async () => {
    try {
      await apiClient(`/api/docker/compose/${composeName}`, {
        method: 'PUT',
        body: JSON.stringify({ content: composeContent }),
      });
      setComposeModal(false);
      showToast('docker-compose.yaml saved');
      log(`Saved compose for ${composeName}`, '#00ff88');
    } catch (err) {
      showToast(`Save failed: ${err.message}`, '#ff2244');
    }
  };

  const filtered = filter === 'all' ? containers : containers.filter(c => c.status === filter);
  const stats = {
    running: containers.filter(c => c.status === 'running').length,
    stopped: containers.filter(c => c.status === 'stopped').length,
    paused:  containers.filter(c => c.status === 'paused').length,
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gridTemplateRows: 'auto 1fr', gap: 8, padding: 10, height: '100%', boxSizing: 'border-box', overflow: 'hidden' }}>

      {/* Top Stats */}
      <div style={{ gridColumn: '1 / 3', display: 'flex', gap: 8, alignItems: 'center' }}>
        {[
          ['TOTAL', containers.length, '#00c8ff'],
          ['RUNNING', stats.running, '#00ff88'],
          ['STOPPED', stats.stopped, '#ff2244'],
          ['PAUSED', stats.paused, '#ffd700'],
        ].map(([l, v, c]) => (
          <div key={l} onClick={() => setFilter(l.toLowerCase() === 'total' ? 'all' : l.toLowerCase())}
            style={{ flex: 1, background: filter === (l.toLowerCase() === 'total' ? 'all' : l.toLowerCase()) ? `${c}15` : 'rgba(0,15,35,0.8)', border: `1px solid ${filter === (l.toLowerCase() === 'total' ? 'all' : l.toLowerCase()) ? c : c + '30'}`, padding: '8px 14px', cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center', transition: 'all 0.2s' }}>
            <span style={{ fontSize: 14, letterSpacing: '0.15em', color: `${c}80`, fontFamily: "'Share Tech Mono',monospace" }}>{l}</span>
            <span style={{ fontSize: 24, fontWeight: 700, color: c, fontFamily: "'Share Tech Mono',monospace", textShadow: `0 0 8px ${c}` }}>{v}</span>
          </div>
        ))}
      </div>

      {/* Container List */}
      <Panel title="CONTAINER REGISTRY" style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        <div style={{ flex: 1, overflow: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>{['NAME', 'IMAGE', 'STATUS', 'CPU %', 'MEM MB', 'PORTS', 'UPTIME', 'ACTIONS'].map(h => (
                <th key={h} style={{ fontSize: 14, letterSpacing: '0.15em', color: 'rgba(0,200,255,0.5)', textTransform: 'uppercase', padding: '6px 10px', borderBottom: '1px solid rgba(0,200,255,0.12)', textAlign: 'left', fontWeight: 400, fontFamily: "'Share Tech Mono',monospace", whiteSpace: 'nowrap' }}>{h}</th>
              ))}</tr>
            </thead>
            <tbody>
              {filtered.map(c => (
                <tr key={c.id} onClick={() => setSelectedId(c.id === selectedId ? null : c.id)}
                  style={{ cursor: 'pointer', background: selectedId === c.id ? 'rgba(0,200,255,0.06)' : 'transparent', transition: 'background 0.15s' }}>
                  <td style={{ padding: '8px 10px', fontFamily: "'Share Tech Mono',monospace", fontSize: 14, color: '#e0f4ff', borderBottom: '1px solid rgba(0,200,255,0.05)', whiteSpace: 'nowrap', fontWeight: 600 }}>{c.name}</td>
                  <td style={{ padding: '8px 10px', fontFamily: "'Share Tech Mono',monospace", fontSize: 14, color: 'rgba(180,220,255,0.5)', borderBottom: '1px solid rgba(0,200,255,0.05)', maxWidth: 180 }}>
                    <span style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.image}</span>
                  </td>
                  <td style={{ padding: '8px 10px', borderBottom: '1px solid rgba(0,200,255,0.05)' }}><StatusBadge status={c.status} /></td>
                  <td style={{ padding: '8px 10px', fontFamily: "'Share Tech Mono',monospace", fontSize: 14, color: c.cpu_pct > 1 ? '#ffd700' : '#00ff88', borderBottom: '1px solid rgba(0,200,255,0.05)' }}>{(c.cpu_pct||0).toFixed(1)}</td>
                  <td style={{ padding: '8px 10px', fontFamily: "'Share Tech Mono',monospace", fontSize: 14, color: '#00c8ff', borderBottom: '1px solid rgba(0,200,255,0.05)' }}>{(c.mem_mb||0).toFixed(0)}</td>
                  <td style={{ padding: '8px 10px', fontFamily: "'Share Tech Mono',monospace", fontSize: 14, color: 'rgba(180,220,255,0.45)', borderBottom: '1px solid rgba(0,200,255,0.05)', whiteSpace: 'nowrap' }}>{(c.ports||[]).join(', ') || '—'}</td>
                  <td style={{ padding: '8px 10px', fontFamily: "'Share Tech Mono',monospace", fontSize: 14, color: 'rgba(0,200,255,0.5)', borderBottom: '1px solid rgba(0,200,255,0.05)', whiteSpace: 'nowrap' }}>{c.uptime}</td>
                  <td style={{ padding: '8px 10px', borderBottom: '1px solid rgba(0,200,255,0.05)', whiteSpace: 'nowrap' }}>
                    <div style={{ display: 'flex', gap: 4 }}>
                      {c.status !== 'running' && <SCPButton small color="#00ff88" onClick={e => { e.stopPropagation(); doAction(c.id, 'start'); }}>▶</SCPButton>}
                      {c.status === 'running'  && <SCPButton small color="#ff2244" onClick={e => { e.stopPropagation(); doAction(c.id, 'stop'); }}>■</SCPButton>}
                      <SCPButton small color="#ffd700" onClick={e => { e.stopPropagation(); doAction(c.id, 'restart'); }}>↺</SCPButton>
                      <SCPButton small color="#00c8ff" onClick={e => { e.stopPropagation(); doAction(c.id, 'backup'); }}>BAK</SCPButton>
                      <SCPButton small color="#00c8ff" onClick={e => { e.stopPropagation(); doAction(c.id, 'update'); }}>UPD</SCPButton>
                      <SCPButton small color="#888" onClick={e => { e.stopPropagation(); openCompose(c); }}>YAML</SCPButton>
                    </div>
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr><td colSpan={8} style={{ padding: '20px 12px', textAlign: 'center', fontSize: 14, color: 'rgba(0,200,255,0.25)', fontFamily: "'Share Tech Mono',monospace" }}>LOADING...</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </Panel>

      {/* Action Log */}
      <Panel title="ACTION LOG" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ flex: 1, overflow: 'auto', padding: '6px 0' }}>
          {actionLog.length === 0 && (
            <div style={{ padding: '20px 12px', textAlign: 'center', fontSize: 14, color: 'rgba(0,200,255,0.25)', fontFamily: "'Share Tech Mono',monospace" }}>NO ACTIONS YET</div>
          )}
          {actionLog.map(e => (
            <div key={e.id} style={{ display: 'flex', gap: 8, padding: '5px 12px', borderBottom: '1px solid rgba(0,200,255,0.05)' }}>
              <span style={{ fontSize: 14, color: 'rgba(0,200,255,0.3)', fontFamily: "'Share Tech Mono',monospace", flexShrink: 0 }}>{e.ts}</span>
              <span style={{ fontSize: 14, color: e.color, fontFamily: "'Share Tech Mono',monospace" }}>{e.msg}</span>
            </div>
          ))}
        </div>
      </Panel>

      {/* Compose Editor Modal */}
      <Modal open={composeModal} onClose={() => setComposeModal(false)} title="DOCKER-COMPOSE EDITOR" width={700}>
        <div style={{ marginBottom: 8, fontSize: 14, color: 'rgba(0,200,255,0.4)', fontFamily: "'Share Tech Mono',monospace" }}>
          /home/ingo/docker/{composeName}/docker-compose.yaml
        </div>
        <CodeEditor value={composeContent} onChange={setComposeContent} rows={22} />
        <div style={{ display: 'flex', gap: 8, marginTop: 12, justifyContent: 'flex-end' }}>
          <SCPButton color="#888" onClick={() => setComposeModal(false)}>CANCEL</SCPButton>
          <SCPButton color="#00ff88" onClick={saveCompose}>SAVE</SCPButton>
        </div>
      </Modal>

      {toast && (
        <div style={{ position: 'fixed', bottom: 24, right: 24, background: 'rgba(0,15,35,0.95)', border: `1px solid ${toast.color}50`, padding: '10px 20px', zIndex: 9999, fontFamily: "'Share Tech Mono',monospace", fontSize: 14, color: toast.color, boxShadow: `0 0 20px ${toast.color}20` }}>
          {toast.msg}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { DockerPage });
