// ─── Settings Page ───────────────────────────────────────────────────────────
const { useState: uSTS, useEffect: uSTE } = React;

function SettingsPage() {
  const [activeTab, setActiveTab] = uSTS('dashboard');
  const [toast, setToast] = uSTS(null);
  const [settings, setSettings] = uSTS(null);
  const [newPath, setNewPath] = uSTS('');
  const [editSvcIdx, setEditSvcIdx] = uSTS(null);
  const [newSvc, setNewSvc] = uSTS({ name: '', compose: '', backup: '', update: '' });

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

  uSTE(() => {
    apiClient('/api/settings').then(d => { if (d) setSettings(d); }).catch(() => {});
  }, []);

  const upd = (patch) => setSettings(prev => ({ ...prev, ...patch }));

  const save = async () => {
    try {
      await apiClient('/api/settings', { method: 'PUT', body: JSON.stringify(settings) });
      showToast('Settings saved');
    } catch (err) { showToast(`Save failed: ${err.message}`, '#ff2244'); }
  };

  const testNtfy = async () => {
    try {
      const r = await apiClient('/api/settings/ntfy/test', { method: 'POST' });
      showToast(r?.ok ? 'Test notification sent!' : 'NTFY test failed', r?.ok ? '#00ff88' : '#ff2244');
    } catch (err) { showToast(`Error: ${err.message}`, '#ff2244'); }
  };

  const tabs = [
    { id: 'dashboard', label: 'DASHBOARD' },
    { id: 'docker',    label: 'DOCKER'    },
    { id: 'scripts',   label: 'SCRIPTS'   },
    { id: 'cron',      label: 'CRON'      },
    { id: 'ntfy',      label: 'NTFY'      },
  ];

  if (!settings) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', color: 'rgba(0,200,255,0.3)', fontFamily: "'Share Tech Mono',monospace" }}>LOADING...</div>
  );

  const storagePaths = settings.storage_paths || [];
  const ntfy = { server: settings.ntfy_server, topic: settings.ntfy_topic, events: settings.ntfy_events || {} };

  return (
    <div style={{ display: 'flex', gap: 0, padding: 10, height: '100%', boxSizing: 'border-box', overflow: 'hidden' }}>
      {/* Sidebar tabs */}
      <div style={{ width: 160, flexShrink: 0, background: 'rgba(0,10,25,0.7)', border: '1px solid rgba(0,200,255,0.15)', marginRight: 8 }}>
        <div style={{ padding: '12px 14px', fontSize: 14, letterSpacing: '0.15em', color: 'rgba(0,200,255,0.45)', fontFamily: "'Share Tech Mono',monospace", borderBottom: '1px solid rgba(0,200,255,0.1)' }}>CONFIGURATION</div>
        {tabs.map(t => (
          <div key={t.id} onClick={() => setActiveTab(t.id)}
            style={{ padding: '13px 16px', cursor: 'pointer', fontSize: 14, letterSpacing: '0.1em', fontFamily: "'Share Tech Mono',monospace", color: activeTab === t.id ? '#00c8ff' : 'rgba(180,220,255,0.5)', background: activeTab === t.id ? 'rgba(0,200,255,0.1)' : 'transparent', borderLeft: activeTab === t.id ? '2px solid #00c8ff' : '2px solid transparent', transition: 'all 0.15s' }}>
            {t.label}
          </div>
        ))}
      </div>

      {/* Content */}
      <Panel style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }} title={`SETTINGS — ${tabs.find(t=>t.id===activeTab)?.label}`}
        headerRight={<SCPButton small color="#00ff88" onClick={save}>SAVE CHANGES</SCPButton>}>
        <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>

          {/* ── Dashboard ── */}
          {activeTab === 'dashboard' && (
            <div>
              <SectionHeader>STORAGE MONITORING PATHS</SectionHeader>
              <div style={{ marginBottom: 12 }}>
                {storagePaths.map((p, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                    <span style={{ flex: 1, fontFamily: "'Share Tech Mono',monospace", fontSize: 14, color: '#00c8ff', background: 'rgba(0,200,255,0.06)', border: '1px solid rgba(0,200,255,0.15)', padding: '6px 10px' }}>{p}</span>
                    <SCPButton small color="#ff2244" onClick={() => upd({ storage_paths: storagePaths.filter((_,j) => j !== i) })}>✕</SCPButton>
                  </div>
                ))}
                <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                  <input className="scp-input" value={newPath} onChange={e => setNewPath(e.target.value)} placeholder="/path/to/monitor" style={{ flex: 1 }} />
                  <SCPButton color="#00ff88" onClick={() => { if (newPath) { upd({ storage_paths: [...storagePaths, newPath] }); setNewPath(''); } }}>ADD PATH</SCPButton>
                </div>
              </div>
              <SectionHeader>DISPLAY</SectionHeader>
              <FormRow label="REFRESH RATE">
                <select className="scp-select" value={settings.refresh_interval} onChange={e => upd({ refresh_interval: +e.target.value })}>
                  {[2, 5, 10, 30, 60].map(v => <option key={v} value={v}>{v} seconds</option>)}
                </select>
              </FormRow>
            </div>
          )}

          {/* ── Docker ── */}
          {activeTab === 'docker' && (
            <div>
              <SectionHeader>DOCKER ROOT</SectionHeader>
              <InputField label="DOCKER FOLDER PATH" value={settings.docker_root} onChange={v => upd({ docker_root: v })} placeholder="/home/ingo/docker" />
            </div>
          )}

          {/* ── Scripts ── */}
          {activeTab === 'scripts' && (
            <div>
              <SectionHeader>PATHS</SectionHeader>
              <InputField label="SCRIPTS DIRECTORY" value={settings.scripts_path} onChange={v => upd({ scripts_path: v })} placeholder="/opt/scripts" />
              <InputField label="PYTHON INTERPRETER" value={settings.python_path} onChange={v => upd({ python_path: v })} placeholder="/usr/bin/python3" />
            </div>
          )}

          {/* ── Cron ── */}
          {activeTab === 'cron' && (
            <div>
              <SectionHeader>CRON DAEMON</SectionHeader>
              <div style={{ fontSize: 14, color: 'rgba(0,200,255,0.5)', fontFamily: "'Share Tech Mono',monospace", lineHeight: 2 }}>
                <div>CRON USER: <span style={{ color: '#00c8ff' }}>ingo</span></div>
                <div style={{ fontSize: 13, color: 'rgba(0,200,255,0.3)' }}>Managed via crontab -u ingo. Only scripts in /opt/scripts/ can be scheduled.</div>
              </div>
            </div>
          )}

          {/* ── NTFY ── */}
          {activeTab === 'ntfy' && (
            <div>
              <SectionHeader>CONNECTION</SectionHeader>
              <InputField label="SERVER URL" value={settings.ntfy_server} onChange={v => upd({ ntfy_server: v })} placeholder="https://ntfy.sh" />
              <InputField label="TOPIC" value={settings.ntfy_topic} onChange={v => upd({ ntfy_topic: v })} placeholder="scp-alerts" />
              <div style={{ fontSize: 13, color: 'rgba(255,215,0,0.5)', fontFamily: "'Share Tech Mono',monospace", marginBottom: 14 }}>
                ⚠ NTFY token is set via SCP_NTFY_TOKEN env var — not editable here for security.
              </div>
              <SectionHeader style={{ marginTop: 20 }}>NOTIFY ON</SectionHeader>
              {[['onBackup','Backup completed'], ['onUpdate','Update completed'], ['onCron','Cron job finished'], ['onError','Any error'], ['onStart','Container start/stop']].map(([k, label]) => (
                <FormRow key={k} label={label.toUpperCase()}>
                  <Toggle value={!!(settings.ntfy_events || {})[k]} onChange={v => upd({ ntfy_events: { ...(settings.ntfy_events || {}), [k]: v } })} />
                </FormRow>
              ))}
              <div style={{ marginTop: 20 }}>
                <SCPButton color="#00c8ff" onClick={testNtfy}>SEND TEST NOTIFICATION</SCPButton>
              </div>
            </div>
          )}

        </div>
      </Panel>

      {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 }}>
          {toast.msg}
        </div>
      )}
    </div>
  );
}

function SectionHeader({ children, style }) {
  return (
    <div style={{ fontSize: 14, letterSpacing: '0.15em', textTransform: 'uppercase', color: 'rgba(0,200,255,0.55)', fontFamily: "'Share Tech Mono',monospace", borderBottom: '1px solid rgba(0,200,255,0.15)', paddingBottom: 8, marginBottom: 14, ...style }}>
      {children}
    </div>
  );
}

Object.assign(window, { SettingsPage });
