// Settings panels: General, Timings, Captcha, Host Mapping

const OtpServerPicker = ({ otpServers, updateOtp }) => {
  const servers = [
    { key: 'lurkbd',  label: 'LurkBD OTP',  urlKey: 'lurkbd',  enabledKey: 'lurkbdEnabled' },
    { key: 'optimus', label: 'Optimus OTP',  urlKey: 'optimus', enabledKey: 'optimusEnabled' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)', display: 'flex', alignItems: 'center', gap: 6 }}>
        <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--green)' }} />OTP Server
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        {servers.map(s => {
          const isActive = otpServers.active === s.key;
          const isEnabled = otpServers[s.enabledKey] !== 'OFF';
          return (
            <div key={s.key} onClick={() => updateOtp('active')(s.key)} style={{
              flex: 1, padding: '8px 12px', borderRadius: 8, cursor: 'pointer',
              border: `1.5px solid ${isActive ? 'var(--green)' : 'var(--border)'}`,
              background: isActive ? 'var(--green-50)' : '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: isActive ? 'var(--green)' : (isEnabled ? 'var(--fg-3)' : 'var(--fg-4)'), boxShadow: isActive ? 'var(--ring-green)' : 'none' }} />
                <span style={{ fontSize: 12, fontWeight: 700, color: isActive ? 'var(--green-deep)' : 'var(--fg-2)' }}>{s.label}</span>
                {isActive && <span style={{ fontSize: 9, fontWeight: 800, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--green-deep)', background: 'var(--green-100)', padding: '1px 5px', borderRadius: 3 }}>ACTIVE</span>}
              </div>
              <div onClick={e => { e.stopPropagation(); updateOtp(s.enabledKey)(isEnabled ? 'OFF' : 'ON'); }} style={{
                width: 28, height: 16, borderRadius: 8, cursor: 'pointer', position: 'relative',
                background: isEnabled ? 'var(--green)' : 'var(--fg-4)', flexShrink: 0,
              }}>
                <span style={{ position: 'absolute', top: 2, left: isEnabled ? 14 : 2, width: 12, height: 12, borderRadius: '50%', background: '#fff', transition: 'left .15s' }} />
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-4)', paddingLeft: 2 }}>
        {otpServers.active === 'lurkbd' ? otpServers.lurkbd : otpServers.optimus}
      </div>
    </div>
  );
};

const GeneralPanel = ({ state, update, otpServers, updateOtp }) => (
  <SectionCard title="General">
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
      <OtpServerPicker otpServers={otpServers} updateOtp={updateOtp} />
      <Input label="Default Password" icon="lock" type="password" value={state.password} onChange={update('password')} suffix={<Icon name="eye" size={14} color="var(--fg-3)" />} />
    </div>
    <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
      <ToggleBar icon="volume-2" label="Sound" state={state.sound} onToggle={() => update('sound')(state.sound === 'ON' ? 'OFF' : 'ON')} />
      <ToggleBar icon="circle" label="Dev Mode" state={state.dev} onToggle={() => update('dev')(state.dev === 'ON' ? 'OFF' : 'ON')} />
    </div>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)', display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--teal)' }} />Parallel Requests
        </div>
        <Input required label="" type="number" min="1" max="10" value={state.parallelThreads || 3} onChange={update('parallelThreads')} mono suffix={<span style={{fontSize:11, fontWeight:700, color:'var(--fg-3)'}}>threads</span>} />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)', display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: state.sharedCaptchaMode === 'ON' ? 'var(--teal)' : 'var(--fg-4)' }} />Shared Captcha Mode
        </div>
        <ToggleBar icon="zap" label="SIGNIN SHARE TOKEN" state={state.sharedCaptchaMode || 'ON'} onToggle={() => update('sharedCaptchaMode')(state.sharedCaptchaMode === 'ON' ? 'OFF' : 'ON')} />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)', display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: state.parallelEnabled === 'ON' ? 'var(--green)' : 'var(--fg-4)' }} />Parallel Mode
        </div>
        <ToggleBar icon="zap" label="Enable Parallel" state={state.parallelEnabled || 'ON'} onToggle={() => update('parallelEnabled')(state.parallelEnabled === 'ON' ? 'OFF' : 'ON')} />
      </div>
    </div>
  </SectionCard>
);

const TimingsPanel = ({ state, update }) => (
  <SectionCard title="Timings">
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
      <Input label="Signin Retry (ms)" mono valueColor='var(--orange)' value={state.signin} onChange={update('signin')} suffix={<Icon name="rotate-ccw" size={14} color="var(--fg-4)" />} />
      <Input label="Reserve Retry (ms)" mono valueColor='var(--orange)' value={state.reserve} onChange={update('reserve')} suffix={<Icon name="rotate-ccw" size={14} color="var(--fg-4)" />} />
      <Input label="Payment Retry (ms)" mono valueColor='var(--orange)' value={state.payment} onChange={update('payment')} suffix={<Icon name="rotate-ccw" size={14} color="var(--fg-4)" />} />
      <Input label="Max Signin" mono valueColor='var(--orange)' value={state.maxSignin} onChange={update('maxSignin')} suffix={<Icon name="rotate-ccw" size={14} color="var(--fg-4)" />} />
      <Input label="Max Verify" mono valueColor='var(--orange)' value={state.maxVerify} onChange={update('maxVerify')} suffix={<Icon name="rotate-ccw" size={14} color="var(--fg-4)" />} />
      <Input label="Max OTP Polls" mono valueColor='var(--orange)' value={state.maxPolls} onChange={update('maxPolls')} suffix={<Icon name="rotate-ccw" size={14} color="var(--fg-4)" />} />
      <Input label="Verify Retry (ms)" mono valueColor='var(--orange)' value={state.verify ?? '3000'} onChange={update('verify')} suffix={<Icon name="rotate-ccw" size={14} color="var(--fg-4)" />} />
    </div>
  </SectionCard>
);

const CaptchaPanel = ({ onClear, initialSettings }) => {
  const [poolSize, setPoolSize] = React.useState(0);
  const [balance, setBalance] = React.useState('0.00');
  const [loading, setLoading] = React.useState(false);
  const [showSecret, setShowSecret] = React.useState(false);
  const [settings, setSettings] = React.useState(initialSettings || {
    secretKey: '',
    offset: '7',
    length: '24',
    capmonsterKey: '1110a6956e0eeb08c4fe96030c3303f3',
    tokenValidity: '240',
    signinSiteKey: '0x4AAAAAAAcghKkJHL1t7UkuZ',
    signinWidgetUrl: 'https://appointment.ivacbd.com/',
    reserveSiteKey: '0x4AAAAAAAcghKkJHL1t7UkuZ'
  });

  const initializedRef = React.useRef(false);
  React.useEffect(() => {
    if (initialSettings && !initializedRef.current) {
      setSettings(initialSettings);
      initializedRef.current = true;
    }
  }, [initialSettings]);

  React.useEffect(() => {
    fetchPoolStatus();
    fetchBalance();
    const interval = setInterval(() => {
      fetchPoolStatus();
      fetchBalance();
    }, 5000);
    return () => clearInterval(interval);
  }, []);

  const fetchPoolStatus = async () => {
    try {
      const resp = await fetch(window.location.origin + '/api/captcha/status');
      const data = await resp.json();
      if (data.success && data.farm) {
        setPoolSize(data.farm.reservePool || 0);
      }
    } catch (err) {
      console.error('Failed to fetch captcha status:', err);
    }
  };

  const fetchBalance = async () => {
    try {
      const token = localStorage.getItem('accessToken');
      const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
      const resp = await fetch(window.location.origin + '/api/captcha/balance', { headers });
      const data = await resp.json();
      if (data.success && typeof data.balance === 'number') {
        setBalance(data.balance.toFixed(2));
      }
    } catch (err) {
      console.error('Failed to fetch balance:', err);
    }
  };

  const handleClearPool = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('accessToken');
      const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
      const resp = await fetch(window.location.origin + '/api/captcha/pop', {
        method: 'DELETE',
        headers
      });
      if (resp.ok) {
        setPoolSize(0);
        onClear?.();
      }
    } catch (err) {
      console.error('Failed to clear pool:', err);
    } finally {
      setLoading(false);
    }
  };

  const updateSetting = (key) => (value) => {
    setSettings(s => ({ ...s, [key]: value }));
  };

  const handleSaveSettings = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('accessToken');
      const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
      const resp = await fetch(window.location.origin + '/api/settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...headers },
        body: JSON.stringify({ captcha: settings })
      });
      if (resp.ok) {
        console.log('Captcha settings saved');
      }
    } catch (err) {
      console.error('Failed to save settings:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <SectionCard title="Captcha Settings" subtitle="Sitekeys, URLs & token pool management">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 }}>
        <StatCard label='Reserve Pool' value={poolSize} valueColor='var(--green)' icon='shield' iconVariant='green' />
        <StatCard label='CapMonster Balance' value={`$${balance}`} valueColor='var(--orange)' icon='credit-card' iconVariant='orange' />
      </div>
      <Card style={{ padding: 14, boxShadow: 'none', marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
          <Icon name="key-round" size={13} color="var(--teal-ink)" />
          <SectionLabel>Reserve Encoding Key</SectionLabel>
        </div>
        <Input label="Secret Key" type={showSecret ? 'text' : 'password'} value={settings.secretKey || ''} onChange={updateSetting('secretKey')} suffix={<Icon name={showSecret ? 'eye-off' : 'eye'} size={14} color="var(--fg-3)" style={{ cursor: 'pointer' }} onClick={() => setShowSecret(!showSecret)} />} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 12 }}>
          <Input label="Offset" value={settings.offset} onChange={updateSetting('offset')} mono />
          <Input label="Length" value={settings.length} onChange={updateSetting('length')} mono />
        </div>
        <div style={{ marginTop: 14 }}>
          <Button variant="primary-green" icon="save" style={{ width: '100%', justifyContent: 'center' }} onClick={handleSaveSettings} disabled={loading}>{loading ? 'Saving...' : 'Save Encoding Key'}</Button>
        </div>
      </Card>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Card style={{ padding: 14, boxShadow: 'none' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
            <Icon name="cloud" size={13} color="var(--teal-ink)" />
            <SectionLabel>CapMonster Cloud</SectionLabel>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <Input label="API Key" value={settings.capmonsterKey} onChange={updateSetting('capmonsterKey')} mono suffix={<Icon name="copy" size={13} color="var(--fg-3)" />} />
            <Input label="Token Validity (seconds)" value={settings.tokenValidity} onChange={updateSetting('tokenValidity')} mono suffix={<Icon name="clock" size={13} color="var(--fg-3)" />} />
          </div>
          <div style={{ marginTop: 14 }}>
            <InlineAlert variant='success'>
              <b>CapMonster: Sign-In (primary) + Reserve (fallback).</b> Farm tokens via Chrome extension → <code style={{ fontFamily: 'var(--font-mono)' }}>farm_reserve</code> pool. CapMonster is used when no farm tokens are available.
            </InlineAlert>
          </div>
          <div style={{ marginTop: 12 }}>
            <Button variant="ghost-pink" icon="trash-2" style={{ width: '100%', justifyContent: 'center' }} disabled={loading} onClick={handleClearPool}>{loading ? 'Clearing...' : 'Clear Reserve Pool'}</Button>
          </div>
        </Card>
        <Card style={{ padding: 14, boxShadow: 'none' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
            <Icon name="shield" size={13} color="var(--teal-ink)" />
            <SectionLabel>Cloudflare Turnstile Widgets</SectionLabel>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--blue)' }} />
            <SectionLabel>Sign-In Widget</SectionLabel>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Input label="Site Key" value={settings.signinSiteKey} onChange={updateSetting('signinSiteKey')} mono suffix={<Icon name="external-link" size={12} color="var(--fg-3)" />} />
            <Input label="Widget URL" value={settings.signinWidgetUrl} onChange={updateSetting('signinWidgetUrl')} mono suffix={<Icon name="external-link" size={12} color="var(--fg-3)" />} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 14, marginBottom: 10 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--green)' }} />
            <SectionLabel>Reserve Slot Widget</SectionLabel>
            <span style={{ background: 'var(--green-50)', color: 'var(--green-deep)', padding: '2px 7px', borderRadius: 999, fontSize: 9, fontWeight: 700, letterSpacing: '0.06em' }}>0 READY</span>
          </div>
          <Input label="Site Key" value={settings.reserveSiteKey} onChange={updateSetting('reserveSiteKey')} mono suffix={<Icon name="external-link" size={12} color="var(--fg-3)" />} />
          <div style={{ marginTop: 14 }}>
            <Button variant="primary-green" icon="save" style={{ width: '100%', justifyContent: 'center' }} onClick={handleSaveSettings} disabled={loading}>{loading ? 'Saving...' : 'Save Widgets'}</Button>
          </div>
        </Card>
      </div>
    </SectionCard>
  );
};

const HostMappingPanel = ({ hosts, onDelete, onAdd, onUpdate, onSave, useDnsThread, onToggleDns }) => {
  const [testingId, setTestingId] = React.useState(null);
  const [testResults, setTestResults] = React.useState({});
  const [savingId, setSavingId] = React.useState(null);
  const [autoDetecting, setAutoDetecting] = React.useState(false);

  const handleAutoDetect = async () => {
    setAutoDetecting(true);
    const token = localStorage.getItem('accessToken');
    await Promise.all(hosts.map(async (h) => {
      const startTime = Date.now();
      try {
        const resp = await fetch('/api/hosts/test', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', ...(token && { 'Authorization': `Bearer ${token}` }) },
          body: JSON.stringify({ ip: h.ip, host: h.host }),
        });
        const data = await resp.json();
        const responseTime = Date.now() - startTime;
        setTestResults(prev => ({ ...prev, [h.id]: data.ok ? { ok: true, message: `OK (${responseTime}ms)`, time: responseTime } : { ok: false, message: data.message || 'Failed', time: responseTime } }));
      } catch (err) {
        setTestResults(prev => ({ ...prev, [h.id]: { ok: false, message: err.message } }));
      }
    }));
    setAutoDetecting(false);
  };

  const handleTest = async (h) => {
    setTestingId(h.id);
    const startTime = Date.now();
    try {
      const token = localStorage.getItem('accessToken');
      const resp = await fetch(`/api/hosts/test`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(token && { 'Authorization': `Bearer ${token}` })
        },
        body: JSON.stringify({ ip: h.ip, host: h.host })
      });
      const responseTime = Date.now() - startTime;
      const data = await resp.json();

      if (data.ok) {
        setTestResults(prev => ({
          ...prev,
          [h.id]: { ok: true, message: `Origin confirmed (${responseTime}ms)`, time: responseTime }
        }));
      } else {
        setTestResults(prev => ({
          ...prev,
          [h.id]: { ok: false, message: data.message || 'Connection failed', time: responseTime }
        }));
      }
    } catch (err) {
      const responseTime = Date.now() - startTime;
      setTestResults(prev => ({
        ...prev,
        [h.id]: { ok: false, message: `Test error: ${err.message}`, time: responseTime }
      }));
    } finally {
      setTestingId(null);
    }
  };

  return (
    <SectionCard title="Custom Host Mapping" subtitle="Override DNS — bypass Cloudflare by pointing to origin IP directly."
      action={
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {/* DNS thread toggle */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 12px', background: useDnsThread ? 'var(--teal-50)' : 'var(--bg-hover)', border: `1px solid ${useDnsThread ? 'var(--teal-100)' : 'var(--border)'}`, borderRadius: 20 }}>
            <Icon name="globe" size={12} color={useDnsThread ? 'var(--teal-ink)' : 'var(--fg-3)'} />
            <span style={{ fontSize: 11, fontWeight: 700, color: useDnsThread ? 'var(--teal-ink)' : 'var(--fg-3)', letterSpacing: '0.04em' }}>api.ivacbd.com</span>
            <button
              onClick={() => onToggleDns?.(!useDnsThread)}
              style={{
                width: 32, height: 18, borderRadius: 9, border: 'none', cursor: 'pointer', padding: 0, position: 'relative',
                background: useDnsThread ? 'var(--teal)' : 'var(--fg-3)', transition: 'background 0.2s',
              }}
            >
              <span style={{
                position: 'absolute', top: 2, left: useDnsThread ? 16 : 2, width: 14, height: 14,
                borderRadius: '50%', background: '#fff', transition: 'left 0.2s',
              }} />
            </button>
          </div>
          <Button variant="tinted-teal" icon={autoDetecting ? 'loader' : 'search'} disabled={autoDetecting} onClick={handleAutoDetect} className={autoDetecting ? 'icon-rotating' : ''}>{autoDetecting ? 'Detecting…' : 'Auto Detect'}</Button>
        </div>
      }>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {hosts.map((h, idx) => {
          const result = testResults[h.id];
          return (
            <div key={h.id}>
              <div style={{
                display: 'grid', gridTemplateColumns: '12px 70px 1fr 24px 1fr 36px 36px 36px',
                alignItems: 'center', gap: 14, padding: '12px 16px',
                background: '#fff', border: '1px solid var(--border)', borderRadius: 10,
              }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: result?.ok ? 'var(--green)' : 'var(--fg-1)' }} />
                <span style={{ background: 'var(--orange-50)', color: 'var(--orange-ink)', borderRadius: 999, padding: '4px 9px', fontSize: 9, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', textAlign: 'center' }}>Direct</span>
                <div style={{ height: 32, display: 'flex', alignItems: 'center', gap: 8, padding: '0 10px', background: '#fff', border: '1px solid var(--border)', borderRadius: 8 }}>
                  <input type="text" value={h.ip} onChange={(e) => onUpdate?.(idx, { ...h, ip: e.target.value })} placeholder="IP address"
                    style={{ flex: 1, border: 0, outline: 0, background: 'transparent', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-1)', minWidth: 0 }} />
                </div>
                <span style={{ color: 'var(--fg-4)', textAlign: 'center' }}>→</span>
                <div style={{ height: 32, display: 'flex', alignItems: 'center', gap: 8, padding: '0 10px', background: '#fff', border: '1px solid var(--border)', borderRadius: 8 }}>
                  <input type="text" value={h.host} onChange={(e) => onUpdate?.(idx, { ...h, host: e.target.value })} placeholder="hostname"
                    style={{ flex: 1, border: 0, outline: 0, background: 'transparent', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-1)', minWidth: 0 }} />
                </div>
                <IconButton icon={testingId === h.id ? 'loader' : 'play'} variant="teal" disabled={testingId === h.id} onClick={() => handleTest(h)} title="Test" className={testingId === h.id ? 'icon-rotating' : ''} />
                <IconButton icon={savingId === h.id ? 'loader' : 'save'} variant="green" disabled={savingId === h.id} onClick={() => { setSavingId(h.id); Promise.resolve(onSave?.(idx, h)).finally(() => setSavingId(null)); }} title="Save" />
                <IconButton icon="trash-2" variant="pink" onClick={() => onDelete?.(idx)} title="Delete" />
              </div>
              {result && (
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 6, marginTop: 6, padding: '8px 12px',
                  background: result.ok ? 'var(--green-50)' : 'var(--pink-50)',
                  border: `1px solid ${result.ok ? 'var(--green-100)' : 'var(--pink-100)'}`,
                  borderRadius: 8, fontSize: 12, color: result.ok ? 'var(--green-deep)' : 'var(--pink-ink)',
                }}>
                  <Icon name={result.ok ? 'check' : 'x'} size={14} />
                  {result.message}
                </div>
              )}
            </div>
          );
        })}
        <div onClick={onAdd} style={{
          padding: '14px', border: '1px dashed var(--border-strong)', borderRadius: 10,
          textAlign: 'center', fontSize: 12, color: 'var(--fg-3)', fontWeight: 500,
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}><Icon name="plus" size={14} />Add IP Entry</div>
      </div>
    </SectionCard>
  );
};

const OtpServerPanel = ({ state, update, onSave, loading }) => {
  const servers = [
    { key: 'lurkbd',  label: 'LurkBD OTP',  urlKey: 'lurkbd',  enabledKey: 'lurkbdEnabled' },
    { key: 'optimus', label: 'Optimus OTP',  urlKey: 'optimus', enabledKey: 'optimusEnabled' },
  ];
  return (
    <SectionCard title="OTP Servers" action={<Button variant="primary-green" icon="save" onClick={onSave} disabled={loading}>{loading ? 'Saving…' : 'Save'}</Button>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {servers.map(s => {
          const isActive = state.active === s.key;
          const isEnabled = state[s.enabledKey] !== 'OFF';
          return (
            <div key={s.key} style={{
              borderRadius: 12, overflow: 'hidden',
              border: `1.5px solid ${isActive ? 'var(--green)' : 'var(--border)'}`,
              boxShadow: isActive ? 'var(--ring-green)' : 'none',
            }}>
              {/* Header */}
              <div style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '10px 14px',
                background: isActive ? 'var(--green)' : 'var(--bg-app-2)',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{
                    width: 8, height: 8, borderRadius: '50%',
                    background: isActive ? '#fff' : (isEnabled ? '#4ade80' : 'var(--fg-4)'),
                    boxShadow: isEnabled ? '0 0 0 2px rgba(74,222,128,.25)' : 'none',
                  }} />
                  <span style={{ fontSize: 12, fontWeight: 700, color: isActive ? '#fff' : 'var(--fg-1)', letterSpacing: '-0.01em' }}>{s.label}</span>
                  {isActive && <span style={{ fontSize: 9, fontWeight: 800, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--green)', background: '#fff', padding: '2px 6px', borderRadius: 4 }}>ACTIVE</span>}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ fontSize: 10, fontWeight: 700, color: isActive ? 'rgba(255,255,255,.7)' : (isEnabled ? 'var(--green-deep)' : 'var(--fg-4)'), textTransform: 'uppercase', letterSpacing: '0.08em' }}>
                    {isEnabled ? 'ON' : 'OFF'}
                  </span>
                  <div
                    onClick={() => update(s.enabledKey)(isEnabled ? 'OFF' : 'ON')}
                    style={{
                      width: 32, height: 18, borderRadius: 9, cursor: 'pointer', position: 'relative', transition: 'background .2s',
                      background: isEnabled ? (isActive ? 'rgba(255,255,255,.35)' : 'var(--green)') : 'var(--fg-4)',
                    }}
                  >
                    <span style={{
                      position: 'absolute', top: 2, left: isEnabled ? 16 : 2, width: 14, height: 14,
                      borderRadius: '50%', background: '#fff', transition: 'left .2s',
                    }} />
                  </div>
                </div>
              </div>
              {/* URL row */}
              <div style={{ padding: '10px 14px', background: '#fff', borderTop: '1px solid var(--border-soft)' }}>
                <div style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-4)', marginBottom: 4 }}>Server URL</div>
                <input
                  value={state[s.urlKey] || ''}
                  onChange={e => update(s.urlKey)(e.target.value)}
                  style={{
                    width: '100%', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-2)',
                    background: 'var(--bg-app-2)', border: '1px solid var(--border-soft)',
                    borderRadius: 6, padding: '5px 8px', outline: 'none', boxSizing: 'border-box',
                  }}
                />
              </div>
              {/* Footer */}
              <div style={{ padding: '8px 14px', background: '#fff', borderTop: '1px solid var(--border-soft)', display: 'flex', justifyContent: 'flex-end' }}>
                <button
                  onClick={() => update('active')(s.key)}
                  disabled={isActive}
                  style={{
                    padding: '6px 14px', borderRadius: 7, fontSize: 11, fontWeight: 700,
                    cursor: isActive ? 'default' : 'pointer', transition: 'all .15s',
                    background: isActive ? 'var(--green-50)' : 'var(--green)',
                    color: isActive ? 'var(--green-deep)' : '#fff',
                    border: `1px solid ${isActive ? 'var(--green-100)' : 'var(--green)'}`,
                  }}
                >
                  {isActive ? '✓ Selected' : 'Use This Server'}
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </SectionCard>
  );
};

Object.assign(window, { GeneralPanel, TimingsPanel, CaptchaPanel, HostMappingPanel, OtpServerPanel });
