// ─── Scripts Page ────────────────────────────────────────────────────────────
const { useState: uSCS, useEffect: uSCE, useRef: uSCR } = React;

function ScriptsPage() {
  const [scripts, setScripts] = uSCS([]);
  const [selected, setSelected]   = uSCS(null);
  const [editorOpen, setEditorOpen] = uSCS(false);
  const [editContent, setEditContent] = uSCS('');
  const [editName, setEditName]   = uSCS('');
  const [editDesc, setEditDesc]   = uSCS('');
  const [isNew, setIsNew]         = uSCS(false);
  const [runOutput, setRunOutput] = uSCS(null);
  const [running, setRunning]     = uSCS(null);
  const [filter, setFilter]       = uSCS('all');
  const [toast, setToast]         = uSCS(null);

  const showToast = (msg, color = '#00ff88') => { setToast({ msg, color }); setTimeout(() => setToast(null), 2500); };

  const fetchScripts = () =>
    apiClient('/api/scripts').then(d => { if (d) setScripts(d); }).catch(() => {});

  uSCE(() => { fetchScripts(); }, []);

  const openEdit = async (script) => {
    try {
      const data = await apiClient(`/api/scripts/${script.name}`);
      setSelected(script.name);
      setEditContent(data.content || '');
      setEditName(data.name);
      setEditDesc(data.desc || '');
      setIsNew(false);
      setEditorOpen(true);
    } catch (err) { showToast(`Load failed: ${err.message}`, '#ff2244'); }
  };

  const openNew = () => {
    setSelected(null); setEditContent('#!/bin/bash\n\n'); setEditName('new-script.sh');
    setEditDesc(''); setIsNew(true); setEditorOpen(true);
  };

  const saveScript = async () => {
    try {
      const method = isNew ? 'POST' : 'PUT';
      await apiClient(`/api/scripts/${editName}`, {
        method,
        body: JSON.stringify({ content: editContent, desc: editDesc }),
      });
      showToast(`${isNew ? 'Created' : 'Saved'} ${editName}`);
      setEditorOpen(false);
      fetchScripts();
    } catch (err) { showToast(`Save failed: ${err.message}`, '#ff2244'); }
  };

  const deleteScriptFn = async (name) => {
    try {
      await apiClient(`/api/scripts/${name}`, { method: 'DELETE' });
      showToast(`Deleted ${name}`, '#ff2244');
      fetchScripts();
    } catch (err) { showToast(`Delete failed: ${err.message}`, '#ff2244'); }
  };

  const runScript = async (name) => {
    setRunning(name);
    setRunOutput({ name, lines: [`[${new Date().toLocaleTimeString('de-DE')}] Starting ${name}...`], done: false });
    try {
      const { run_id } = await apiClient(`/api/scripts/${name}/run`, { method: 'POST' });
      // Poll until done
      const poll = setInterval(async () => {
        try {
          const result = await apiClient(`/api/scripts/runs/${run_id}`);
          const lines = result.output ? result.output.split('\n').filter(Boolean) : [];
          setRunOutput({ name, lines, done: result.status !== 'running' });
          if (result.status !== 'running') {
            clearInterval(poll);
            setRunning(null);
            showToast(`${name} ${result.status === 'success' ? 'completed' : 'failed'}`,
              result.status === 'success' ? '#00ff88' : '#ff2244');
            fetchScripts();
          }
        } catch { clearInterval(poll); setRunning(null); }
      }, 1500);
    } catch (err) {
      setRunning(null);
      setRunOutput(prev => ({ ...prev, lines: [...(prev?.lines||[]), `ERROR: ${err.message}`], done: true }));
    }
  };

  const filtered = filter === 'all' ? scripts : scripts.filter(s => s.type === filter || (filter === 'sh' && s.name.endsWith('.sh')) || (filter === 'py' && s.name.endsWith('.py')));
  const statusColor = { success: '#00ff88', error: '#ff2244', running: '#ffd700' };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 8, padding: 10, height: '100%', boxSizing: 'border-box', overflow: 'hidden' }}>
      <Panel title="SCRIPT LIBRARY" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}
        headerRight={
          <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            {['all', 'sh', 'py'].map(f => (
              <button key={f} onClick={() => setFilter(f)}
                style={{ background: filter === f ? 'rgba(0,200,255,0.15)' : 'transparent', border: '1px solid rgba(0,200,255,0.3)', color: filter === f ? '#00c8ff' : 'rgba(0,200,255,0.4)', fontSize: 14, padding: '2px 8px', cursor: 'pointer', fontFamily: "'Share Tech Mono',monospace", letterSpacing: '0.1em' }}>
                {f === 'all' ? 'ALL' : `*.${f}`}
              </button>
            ))}
            <SCPButton small color="#00ff88" onClick={openNew}>+ NEW</SCPButton>
          </div>
        }>
        <div style={{ flex: 1, overflow: 'auto' }}>
          {filtered.length === 0 && (
            <div style={{ padding: '20px 14px', textAlign: 'center', fontSize: 14, color: 'rgba(0,200,255,0.25)', fontFamily: "'Share Tech Mono',monospace" }}>NO SCRIPTS FOUND</div>
          )}
          {filtered.map(s => (
            <div key={s.name} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderBottom: '1px solid rgba(0,200,255,0.07)', transition: 'background 0.15s' }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(0,200,255,0.04)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <div style={{ width: 28, height: 28, border: `1px solid ${s.name.endsWith('.py') ? '#ffd70040' : '#00c8ff40'}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <span style={{ fontSize: 14, color: s.name.endsWith('.py') ? '#ffd700' : '#00c8ff', fontFamily: "'Share Tech Mono',monospace" }}>{s.name.endsWith('.py') ? 'PY' : 'SH'}</span>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, color: '#e0f4ff', fontFamily: "'Share Tech Mono',monospace", fontWeight: 600 }}>{s.name}</div>
                <div style={{ fontSize: 14, color: 'rgba(180,220,255,0.45)', fontFamily: "'Share Tech Mono',monospace", marginTop: 2 }}>{s.desc || '—'}</div>
                <div style={{ display: 'flex', gap: 12, marginTop: 4, fontSize: 14, fontFamily: "'Share Tech Mono',monospace" }}>
                  <span style={{ color: 'rgba(0,200,255,0.35)' }}>LAST RUN: <span style={{ color: 'rgba(0,200,255,0.6)' }}>{s.last_run || '—'}</span></span>
                  {s.last_status && <span style={{ color: statusColor[s.last_status] || '#00c8ff' }}>● {s.last_status.toUpperCase()}</span>}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 5, flexShrink: 0 }}>
                <SCPButton small color="#00ff88" onClick={() => runScript(s.name)} disabled={running === s.name}>
                  {running === s.name ? '…' : '▶ RUN'}
                </SCPButton>
                <SCPButton small color="#00c8ff" onClick={() => openEdit(s)}>EDIT</SCPButton>
                <SCPButton small color="#ff2244" onClick={() => deleteScriptFn(s.name)}>DEL</SCPButton>
              </div>
            </div>
          ))}
        </div>
      </Panel>

      {/* Output Console */}
      <Panel title="EXECUTION CONSOLE" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ flex: 1, background: 'rgba(0,5,12,0.9)', fontFamily: "'Share Tech Mono',monospace", fontSize: 14, overflow: 'auto', padding: 12 }}>
          {!runOutput ? (
            <div style={{ color: 'rgba(0,200,255,0.2)', paddingTop: 20, textAlign: 'center', fontSize: 14 }}>
              SELECT A SCRIPT AND PRESS ▶ RUN
              <div style={{ marginTop: 8, fontSize: 14, color: 'rgba(0,200,255,0.1)' }}>CONSOLE READY_</div>
            </div>
          ) : (
            <>
              <div style={{ color: 'rgba(0,200,255,0.4)', marginBottom: 8, fontSize: 14 }}>── {runOutput.name} ──────────────</div>
              {runOutput.lines.map((l, i) => (
                <div key={i} style={{ color: l.includes('error') || l.includes('ERROR') ? '#ff2244' : 'rgba(0,255,200,0.8)', marginBottom: 2, lineHeight: 1.5 }}>{l}</div>
              ))}
              {!runOutput.done && <span style={{ color: '#00c8ff' }} className="blink">█</span>}
            </>
          )}
        </div>
        {runOutput?.done && (
          <div style={{ padding: '8px 12px', borderTop: '1px solid rgba(0,200,255,0.1)' }}>
            <SCPButton small color="#888" onClick={() => setRunOutput(null)}>CLEAR</SCPButton>
          </div>
        )}
      </Panel>

      {/* Editor Modal */}
      <Modal open={editorOpen} onClose={() => setEditorOpen(false)} title={isNew ? 'NEW SCRIPT' : `EDIT: ${editName}`} width={720}>
        <InputField label="FILENAME" value={editName} onChange={setEditName} placeholder="my-script.sh" />
        <InputField label="DESCRIPTION" value={editDesc} onChange={setEditDesc} placeholder="What does this script do?" />
        <div style={{ marginBottom: 6 }}><SectionLabel>CONTENT</SectionLabel></div>
        <CodeEditor value={editContent} onChange={setEditContent} rows={20} />
        <div style={{ display: 'flex', gap: 8, marginTop: 12, justifyContent: 'flex-end' }}>
          <SCPButton color="#888" onClick={() => setEditorOpen(false)}>CANCEL</SCPButton>
          <SCPButton color="#00ff88" onClick={saveScript}>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, { ScriptsPage });
