// Global Proxy Manager

const PROXY_TYPES = ['HTTP', 'SOCKS4', 'SOCKS5'];

const proxyToUrl = ({ type, host, port, user, pass }) => {
  const scheme = type === 'SOCKS5' ? 'socks5' : type === 'SOCKS4' ? 'socks4' : 'http';
  const auth = user && pass ? `${encodeURIComponent(user)}:${encodeURIComponent(pass)}@` : user ? `${encodeURIComponent(user)}@` : '';
  return `${scheme}://${auth}${host}:${port}`;
};

const urlToFields = (url) => {
  try {
    const u = new URL(url);
    const type = u.protocol.startsWith('socks5') ? 'SOCKS5' : u.protocol.startsWith('socks4') ? 'SOCKS4' : 'HTTP';
    return {
      type,
      host: u.hostname,
      port: u.port,
      user: decodeURIComponent(u.username || ''),
      pass: decodeURIComponent(u.password || ''),
    };
  } catch {
    return { type: 'HTTP', host: url, port: '', user: '', pass: '' };
  }
};

const TypeSelector = ({ value, onChange }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)' }}>Type</div>
    <div style={{ display: 'flex', gap: 4 }}>
      {PROXY_TYPES.map(t => (
        <button key={t} onClick={() => onChange(t)} style={{
          flex: 1, padding: '8px 4px', borderRadius: 8, fontSize: 11, fontWeight: 700, cursor: 'pointer',
          background: value === t ? 'var(--teal)' : '#fff',
          color: value === t ? '#fff' : 'var(--fg-3)',
          border: `1.5px solid ${value === t ? 'var(--teal)' : 'var(--border)'}`,
        }}>{t}</button>
      ))}
    </div>
  </div>
);

const ProxyForm = ({ initial, onSave, onCancel, saveLabel = 'Add Proxy', testing, onTest, testResult }) => {
  const blank = { type: 'HTTP', host: '', port: '', user: '', pass: '' };
  const [fields, setFields] = React.useState(initial || blank);
  const up = k => v => setFields(f => ({ ...f, [k]: v }));
  const isValid = fields.host.trim() && fields.port.trim();
  const url = isValid ? proxyToUrl(fields) : '';

  const initRef = React.useRef(false);
  React.useEffect(() => {
    if (!initRef.current) { setFields(initial || blank); initRef.current = true; }
  }, [initial]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <TypeSelector value={fields.type} onChange={up('type')} />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 120px', gap: 10 }}>
        <Input label="Host" placeholder="103.31.210.15" value={fields.host} onChange={up('host')} mono />
        <Input label="Port" placeholder="50100" value={fields.port} onChange={up('port')} mono />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <Input label="Username" placeholder="optional" value={fields.user} onChange={up('user')} />
        <Input label="Password" type="password" placeholder="optional" value={fields.pass} onChange={up('pass')} suffix={<Icon name="eye" size={13} color="var(--fg-3)" />} />
      </div>
      {url && (
        <div style={{ padding: '7px 10px', borderRadius: 8, background: 'var(--bg-hover)', border: '1px solid var(--border-soft)', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-2)', wordBreak: 'break-all' }}>
          {url}
        </div>
      )}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        {onTest && (
          <button onClick={() => onTest(url)} disabled={!isValid || testing} style={{
            display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 14px', borderRadius: 8,
            border: '1.5px solid var(--border)', background: '#fff', fontSize: 12, fontWeight: 600,
            color: 'var(--fg-2)', cursor: isValid && !testing ? 'pointer' : 'not-allowed', opacity: isValid ? 1 : 0.5,
          }}>
            <Icon name={testing ? 'loader' : 'zap'} size={13} className={testing ? 'icon-rotating' : ''} color="var(--teal)" />
            {testing ? 'Testing…' : 'Test'}
          </button>
        )}
        {testResult && (
          <span style={{ fontSize: 12, fontWeight: 600, color: testResult.ok ? 'var(--green)' : 'var(--pink)', display: 'flex', alignItems: 'center', gap: 5 }}>
            <Icon name={testResult.ok ? 'check-circle' : 'x-circle'} size={13} />
            {testResult.ok ? `OK · ${testResult.latency}ms` : testResult.error}
          </span>
        )}
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          {onCancel && <Button variant="ghost" onClick={onCancel}>Cancel</Button>}
          <Button variant="primary-teal" icon="save" onClick={() => isValid && onSave(fields, url)} disabled={!isValid}>{saveLabel}</Button>
        </div>
      </div>
    </div>
  );
};

const ProxyManagerPanel = ({ proxies, onAdd, onUpdate, onDelete, profiles }) => {
  const [adding, setAdding] = React.useState(false);
  const [editIdx, setEditIdx] = React.useState(null);
  const [testing, setTesting] = React.useState(null); // idx or 'new'
  const [testResults, setTestResults] = React.useState({}); // idx -> result

  const handleTest = async (url, key) => {
    setTesting(key);
    const token = localStorage.getItem('accessToken');
    try {
      const r = await fetch('/api/proxies/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
        body: JSON.stringify({ url }),
      });
      const d = await r.json();
      setTestResults(prev => ({ ...prev, [key]: d }));
    } catch (e) {
      setTestResults(prev => ({ ...prev, [key]: { ok: false, error: e.message } }));
    } finally {
      setTesting(null);
    }
  };

  const typeBadge = (url) => {
    const t = url.startsWith('socks5') ? 'SOCKS5' : url.startsWith('socks4') ? 'SOCKS4' : 'HTTP';
    const bg = t === 'SOCKS5' ? 'var(--teal-50)' : t === 'SOCKS4' ? 'var(--orange-50,#FFF7ED)' : 'var(--bg-hover)';
    const color = t !== 'HTTP' ? 'var(--teal-ink)' : 'var(--fg-3)';
    return <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 4, background: bg, color, border: '1px solid var(--border-soft)', textTransform: 'uppercase', flexShrink: 0 }}>{t}</span>;
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        {!adding && <Button variant='primary-teal' icon='plus' onClick={() => { setAdding(true); setEditIdx(null); }}>Add Proxy</Button>}
      </div>

      {/* Add form */}
      {adding && (
        <div style={{ background: '#fff', border: '1.5px solid var(--teal)', borderRadius: 14, padding: 20 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--teal-ink)', marginBottom: 14 }}>New Proxy</div>
          <ProxyForm
            saveLabel="Add Proxy"
            testing={testing === 'new'}
            testResult={testResults['new']}
            onTest={url => handleTest(url, 'new')}
            onSave={(fields, url) => { onAdd?.(url); setAdding(false); setTestResults(p => ({ ...p, new: undefined })); }}
            onCancel={() => { setAdding(false); setTestResults(p => ({ ...p, new: undefined })); }}
          />
        </div>
      )}

      {/* Proxy list */}
      <div style={{ background: '#fff', border: '1px solid var(--border)', borderRadius: 14, padding: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)' }}>Pool</div>
          <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--fg-4)' }}>{proxies.length} proxies</span>
        </div>
        {proxies.length === 0 ? (
          <EmptyState icon="shield-off" title="No proxies yet" subtitle="Add a proxy above to build the global pool." />
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {proxies.map((url, idx) => {
              const assignedProfile = profiles?.find(p => (p.proxy || '').split('\n').map(s => s.trim()).includes(url));
              const testRes = testResults[idx];
              const isEditing = editIdx === idx;

              return (
                <div key={idx} style={{
                  border: isEditing ? '1.5px solid var(--teal)' : '1px solid var(--border)',
                  borderRadius: 10, overflow: 'hidden',
                }}>
                  {/* Row */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', background: isEditing ? 'var(--teal-50)' : 'var(--bg-app)' }}>
                    <Icon name={url.startsWith('socks') ? 'layers' : 'globe'} size={13} color="var(--fg-3)" />
                    {typeBadge(url)}
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-1)', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {(() => { try { const u = new URL(url); return u.hostname + ':' + u.port; } catch { return url; } })()}
                    </span>
                    {testRes && (
                      <span style={{ fontSize: 11, fontWeight: 600, color: testRes.ok ? 'var(--green)' : 'var(--pink)', display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
                        <Icon name={testRes.ok ? 'check-circle' : 'x-circle'} size={12} />
                        {testRes.ok ? `${testRes.latency}ms` : 'Failed'}
                      </span>
                    )}
                    {assignedProfile ? (
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 4, background: 'var(--teal-50)', color: 'var(--teal-ink)', border: '1px solid var(--teal-100,#99F6E4)', whiteSpace: 'nowrap', flexShrink: 0 }}>
                        <Icon name='user' size={9} />{assignedProfile.name}
                      </span>
                    ) : (
                      <span style={{ fontSize: 10, color: 'var(--fg-4)', fontWeight: 500, flexShrink: 0 }}>free</span>
                    )}
                    <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
                      <button onClick={() => handleTest(url, idx)} disabled={testing === idx} title="Test proxy" style={{
                        display: 'inline-flex', alignItems: 'center', gap: 4, padding: '4px 8px', borderRadius: 6,
                        border: '1px solid var(--border)', background: '#fff', fontSize: 11, fontWeight: 600,
                        color: 'var(--teal-ink)', cursor: testing === idx ? 'not-allowed' : 'pointer',
                      }}>
                        <Icon name={testing === idx ? 'loader' : 'zap'} size={11} className={testing === idx ? 'icon-rotating' : ''} />
                        {testing === idx ? '' : 'Test'}
                      </button>
                      <IconButton icon="pencil" onClick={() => setEditIdx(isEditing ? null : idx)} title="Edit proxy" />
                      <IconButton icon="trash-2" variant="pink" onClick={() => { onDelete?.(idx); if (editIdx === idx) setEditIdx(null); }} title="Delete proxy" />
                    </div>
                  </div>

                  {/* Edit form */}
                  {isEditing && (
                    <div style={{ padding: 16, borderTop: '1px solid var(--border-soft)', background: '#fff' }}>
                      <ProxyForm
                        initial={urlToFields(url)}
                        saveLabel="Save Changes"
                        testing={testing === `edit-${idx}`}
                        testResult={testResults[`edit-${idx}`]}
                        onTest={u => handleTest(u, `edit-${idx}`)}
                        onSave={(fields, newUrl) => { onUpdate?.(idx, newUrl); setEditIdx(null); }}
                        onCancel={() => setEditIdx(null)}
                      />
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { ProxyManagerPanel });
