const ProxyPicker = ({ globalProxies, profiles, profileId, value, onChange }) => {
  const [dropOpen, setDropOpen] = React.useState(false);
  const ref = React.useRef(null);

  const selected = (value || '').split('\n').map(s => s.trim()).filter(Boolean);

  const label = (url) => url.replace(/^https?:\/\/|^socks\d?:\/\//, '').split('@').pop();

  const toggle = (url) => {
    const next = selected.includes(url) ? selected.filter(u => u !== url) : [...selected, url];
    onChange(next.join('\n'));
  };

  const remove = (url) => onChange(selected.filter(u => u !== url).join('\n'));

  // Close dropdown on outside click
  React.useEffect(() => {
    if (!dropOpen) return;
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setDropOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [dropOpen]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)' }}>Proxy List</div>

      {/* Selected chips */}
      {selected.length > 0 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
          {selected.map((url, i) => (
            <div key={i} title={url} style={{
              display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 8px',
              borderRadius: 6, background: 'var(--teal-50)', border: '1.5px solid var(--teal)',
              fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600, color: 'var(--teal-ink)',
            }}>
              <Icon name='shield' size={10} />{label(url)}
              <button onClick={() => remove(url)} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', display: 'flex', alignItems: 'center', color: 'var(--teal-ink)', opacity: 0.6 }}>
                <Icon name='x' size={10} />
              </button>
            </div>
          ))}
        </div>
      )}

      {/* Dropdown picker */}
      {globalProxies.length > 0 && (
        <div ref={ref} style={{ position: 'relative' }}>
          <button onClick={() => setDropOpen(o => !o)} style={{
            display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 12px', borderRadius: 8,
            border: '1.5px solid var(--border)', background: '#fff', fontSize: 12, fontWeight: 600,
            color: 'var(--fg-2)', cursor: 'pointer', width: '100%', justifyContent: 'space-between',
          }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name='shield' size={13} color='var(--fg-3)' />
              {selected.length === 0 ? 'Select from global proxies…' : `${selected.length} proxy selected`}
            </span>
            <Icon name={dropOpen ? 'chevron-up' : 'chevron-down'} size={13} color='var(--fg-3)' />
          </button>
          {dropOpen && (
            <div style={{
              position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 200, marginTop: 4,
              background: '#fff', border: '1.5px solid var(--border)', borderRadius: 10,
              boxShadow: 'var(--shadow-lg)', maxHeight: 220, overflowY: 'auto',
            }}>
              {globalProxies.map((url, i) => {
                const isSelected = selected.includes(url);
                const takenBy = profiles?.find(p => p.id !== profileId && (p.proxy || '').split('\n').map(s => s.trim()).includes(url));
                const taken = !!takenBy && !isSelected;
                return (
                  <div key={i} onClick={() => !taken && toggle(url)} title={taken ? `In use by: ${takenBy?.name || takenBy?.id}` : url} style={{
                    display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px',
                    cursor: taken ? 'not-allowed' : 'pointer', opacity: taken ? 0.4 : 1,
                    background: isSelected ? 'var(--teal-50)' : 'transparent',
                    borderBottom: i < globalProxies.length - 1 ? '1px solid var(--border-soft)' : 'none',
                  }}
                    onMouseEnter={e => { if (!taken && !isSelected) e.currentTarget.style.background = 'var(--bg-hover)'; }}
                    onMouseLeave={e => { if (!isSelected) e.currentTarget.style.background = isSelected ? 'var(--teal-50)' : 'transparent'; }}
                  >
                    <Icon name={isSelected ? 'check' : taken ? 'lock' : 'shield'} size={12} color={isSelected ? 'var(--teal)' : 'var(--fg-3)'} />
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: isSelected ? 'var(--teal-ink)' : 'var(--fg-1)', flex: 1 }}>{label(url)}</span>
                    {taken && <span style={{ fontSize: 10, color: 'var(--fg-4)' }}>{takenBy?.name}</span>}
                    <span style={{ fontSize: 10, fontWeight: 700, padding: '1px 5px', borderRadius: 4, background: 'var(--bg-hover)', color: 'var(--fg-3)', border: '1px solid var(--border-soft)', textTransform: 'uppercase' }}>
                      {url.startsWith('socks5') ? 'S5' : url.startsWith('socks4') ? 'S4' : 'HTTP'}
                    </span>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}
      <div style={{ fontSize: 10, color: 'var(--fg-4)' }}>Bot rotates randomly between selected proxies.</div>
    </div>
  );
};

// New/Edit Profile modal
const Modal = ({ open, onClose, children, width = 780 }) => {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(24,32,48,.35)', backdropFilter: 'blur(6px)',
      WebkitBackdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 100, padding: 24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width, maxWidth: '100%', maxHeight: '90vh', overflow: 'auto',
        background: '#fff', borderRadius: 20, boxShadow: 'var(--shadow-lg)', border: '1px solid var(--border)',
      }}>{children}</div>
    </div>
  );
};

const ProfileModal = ({ open, onClose, onSave, mode = 'new', initial, onExtract, profileId, userQuota, isSuperAdmin, users, globalProxies, profiles }) => {
  const blank = { name: '', phone: '', email: '', app_id: '', surname: '', given: '',
    passport: '', nid: '', dob: '', location: '', visa: '', password: '', slot_id: '', tags: '', mission_id: '', otp_server: 'auto', proxy: '', assigned_user_id: '' };
  const [form, setForm] = React.useState(blank);
  const [extracting, setExtracting] = React.useState(false);
  // For new profile: show user's profile creation quota. For edit: show PDF autofill quota.
  const [pdfQuota, setPdfQuota] = React.useState({ used: 0, limit: 999, remaining: 999 });
  const fileInputRef = React.useRef(null);
  const prevOpenRef = React.useRef(false);

  React.useEffect(() => {
    // Only initialize form when modal transitions closed → open
    const justOpened = open && !prevOpenRef.current;
    prevOpenRef.current = open;
    if (!justOpened) return;

    setForm(mode === 'edit' && initial ? { ...blank, ...initial } : blank);

    // Fetch PDF autofill quota only in edit mode
    if (profileId) {
      const token = localStorage.getItem('accessToken');
      fetch(`/api/profiles/${profileId}/quota`, {
        headers: token ? { 'Authorization': `Bearer ${token}` } : {}
      })
        .then(r => r.json())
        .then(data => {
          if (data.ok) setPdfQuota({ used: data.used, limit: data.limit, remaining: data.remaining });
        })
        .catch(err => console.error('Failed to fetch quota:', err));
    }
  }, [open, mode, initial, profileId]);

  // Which quota to display: new profile → user's profile limit, edit → PDF autofill quota
  const quota = (mode === 'new' && userQuota)
    ? { used: userQuota.used, limit: userQuota.limit, remaining: Math.max(0, userQuota.limit - userQuota.used) }
    : pdfQuota;

  const up = (k) => (v) => setForm(f => ({ ...f, [k]: v }));

  const handlePdfUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setExtracting(true);
    try {
      console.log('Extracting PDF:', file.name);
      const data = await window.PDFExtractor.extract(file);
      if (data && Object.keys(data).length > 0) {
        console.log('Auto-filling form with:', data);
        setForm(f => ({ ...f, ...data }));

        // Increment quota if editing existing profile
        if (profileId) {
          const token = localStorage.getItem('accessToken');
          fetch(`/api/profiles/${profileId}/quota/increment`, {
            method: 'POST',
            headers: token ? { 'Authorization': `Bearer ${token}` } : {}
          })
            .then(r => r.json())
            .then(data => {
              if (data.ok) {
                setPdfQuota({ used: data.used, limit: data.limit, remaining: data.remaining });
              }
            })
            .catch(err => console.error('Failed to increment quota:', err));
        }
      } else {
        alert('No data found in PDF. Make sure it contains form fields.');
      }
    } catch (err) {
      console.error('PDF extraction failed:', err);
      alert('PDF extraction failed: ' + err.message);
    } finally {
      setExtracting(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };
  const isEdit = mode === 'edit';
  const pdfBar = (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <button disabled={extracting} onClick={() => fileInputRef.current?.click()} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: extracting ? 'var(--fg-3)' : 'var(--green)', color: '#fff', border: 0, borderRadius: 7, padding: '6px 10px', fontWeight: 600, fontSize: 11, cursor: extracting ? 'not-allowed' : 'pointer', opacity: extracting ? 0.6 : 1, whiteSpace: 'nowrap' }}>
        <Icon name={extracting ? 'loader' : 'upload'} size={12} className={extracting ? 'icon-rotating' : ''} />{extracting ? 'Extracting…' : 'PDF Autofill'}
      </button>
      <input ref={fileInputRef} type="file" accept="application/pdf" onChange={handlePdfUpload} style={{ display: 'none' }} />
      <div style={{ width: 1, height: 18, background: 'var(--border)' }} />
      <div style={{ fontSize: 10, letterSpacing: '0.07em', fontWeight: 700, color: 'var(--fg-3)', textTransform: 'uppercase' }}>Quota</div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-1)', fontWeight: 700 }}>{quota.used}/{quota.limit}</div>
      <div style={{ fontSize: 10, color: 'var(--fg-4)' }}>·</div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--green)', fontWeight: 700 }}>{quota.remaining} left</div>
    </div>
  );
  return (
    <ModalShell open={open} onClose={onClose} width={820} icon='user-round' iconVariant='green' title={isEdit ? 'Edit Profile' : 'New Profile'} headerExtra={pdfBar} footer={<ModalFooter onClose={onClose} onConfirm={() => { onSave?.(form); onClose?.(); }} confirmLabel={isEdit ? 'Update Profile' : 'Save Profile'} confirmIcon='save' />}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {isSuperAdmin && users?.length > 0 && (
          <div style={{ gridColumn: '1 / -1', display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)' }}>Assign to User</div>
            <select
              value={form.assigned_user_id || ''}
              onChange={e => up('assigned_user_id')(e.target.value)}
              style={{ height: 40, padding: '0 12px', borderRadius: 10, border: '1px solid var(--border)', background: '#fff', fontSize: 13, color: 'var(--fg-1)', outline: 'none', cursor: 'pointer' }}
            >
              <option value="">— assign to yourself —</option>
              {users.map(u => (
                <option key={u.id} value={u.id}>{u.username}{u.name ? ` · ${u.name}` : ''}</option>
              ))}
            </select>
          </div>
        )}
        <Input required label="Profile Name" placeholder="Ex: Prime-01" value={form.name} onChange={up('name')} />
        <Input required label="Phone Number" placeholder="88017…" value={form.phone} onChange={up('phone')} />
        <Input required label="Email" placeholder="user@example.com" value={form.email} onChange={up('email')} />
        <Input required label="Password" type="password" value={form.password} onChange={up('password')} suffix={<Icon name="eye" size={14} color="var(--fg-3)" />} />
        <Input label="Slot ID" placeholder="UUID from reservation (e.g. 72498625...)" value={form.slot_id || ''} onChange={up('slot_id')} mono />
        <ProxyPicker
          globalProxies={globalProxies || []}
          profiles={profiles}
          profileId={profileId}
          value={form.proxy || ''}
          onChange={up('proxy')}
        />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)' }}>OTP Server</div>
          <div style={{ display: 'flex', gap: 6 }}>
            {[{ val: 'auto', label: 'Auto (Global)' }, { val: 'lurkbd', label: 'LurkBD' }, { val: 'optimus', label: 'Optimus' }].map(opt => (
              <button key={opt.val} onClick={() => up('otp_server')(opt.val)} style={{
                flex: 1, padding: '8px 6px', borderRadius: 8, fontSize: 11, fontWeight: 700, cursor: 'pointer',
                background: form.otp_server === opt.val ? 'var(--green)' : '#fff',
                color: form.otp_server === opt.val ? '#fff' : 'var(--fg-3)',
                border: `1.5px solid ${form.otp_server === opt.val ? 'var(--green)' : 'var(--border)'}`,
              }}>{opt.label}</button>
            ))}
          </div>
        </div>
      </div>
    </ModalShell>
  );
};

Object.assign(window, { Modal, ProfileModal });
