// Connector setup wizard — 3 step quick flow as a centered modal.
// Step 1: pick connector (or pre-selected)
// Step 2: authenticate (mock OAuth / credentials)
// Step 3: scope + test connection -> success

const WIZARD_PRESETS = {
  postgres: {
    name: 'Postgres', tone: '#336791', mono: 'Pg',
    auth: 'credentials',
    fields: [
      { id: 'host', label: 'Host', placeholder: 'db.internal.bankcorp.com', value: 'db.internal.bankcorp.com' },
      { id: 'port', label: 'Port', placeholder: '5432', value: '5432' },
      { id: 'db', label: 'Database', placeholder: 'analytics_prod', value: 'analytics_prod' },
      { id: 'user', label: 'Username', placeholder: 'nalarx_reader', value: 'nalarx_reader' },
      { id: 'pass', label: 'Password', placeholder: '••••••••', value: '', type: 'password' },
    ],
  },
  bigquery: {
    name: 'BigQuery', tone: '#4285f4', mono: 'Bq', auth: 'oauth',
  },
  snowflake: {
    name: 'Snowflake', tone: '#29b5e8', mono: 'Sn', auth: 'oauth',
  },
  sharepoint: {
    name: 'SharePoint', tone: '#0078d4', mono: 'Sp', auth: 'oauth',
  },
  okta: {
    name: 'Okta', tone: '#007dc1', mono: 'Ok', auth: 'oauth',
  },
};

const ScreenWizard = ({ onClose }) => {
  const [step, setStep] = React.useState(1);
  const [picked, setPicked] = React.useState(null); // connector id
  const [authState, setAuthState] = React.useState('idle'); // idle | connecting | authed
  const [testState, setTestState] = React.useState('idle'); // idle | testing | success | error
  const [scopes, setScopes] = React.useState({
    public: true, finance_ops: true, hr_data: false, audit_logs: true,
  });
  const [syncFreq, setSyncFreq] = React.useState('15m');

  const pickedConn = picked ? window.NX_DATA.CONNECTORS.find(c => c.id === picked) : null;
  const preset = picked && WIZARD_PRESETS[picked];

  const reset = () => { setStep(1); setPicked(null); setAuthState('idle'); setTestState('idle'); };

  const startAuth = () => {
    setAuthState('connecting');
    setTimeout(() => setAuthState('authed'), 1300);
  };
  const runTest = () => {
    setTestState('testing');
    setTimeout(() => setTestState('success'), 1600);
  };

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 50,
      background: 'rgba(20,18,14,.42)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24, animation: 'nx-fade-up .18s ease-out',
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: 'min(640px, 100%)',
        maxHeight: 'calc(100vh - 48px)',
        background: 'var(--bg-elev)',
        border: '0.5px solid var(--line-strong)',
        borderRadius: 16,
        boxShadow: '0 20px 60px rgba(0,0,0,.18)',
        display: 'flex', flexDirection: 'column',
        overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{
          padding: '16px 20px', borderBottom: '0.5px solid var(--line)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: '-0.01em' }}>
              {step === 1 && 'Choose a source to connect'}
              {step === 2 && `Connect ${pickedConn?.name || 'source'}`}
              {step === 3 && `Configure ${pickedConn?.name || 'source'}`}
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>
              Step {step} of 3 · ~{step === 1 ? 3 : step === 2 ? 1 : 1} min remaining
            </div>
          </div>
          <button onClick={onClose} className="nx-btn ghost sm" style={{ padding: 0, width: 28, justifyContent: 'center' }}>
            <Icon name="x" size={14} />
          </button>
        </div>

        {/* Stepper */}
        <div style={{ display: 'flex', padding: '12px 20px 0', gap: 4 }}>
          {[1, 2, 3].map(n => (
            <div key={n} style={{
              flex: 1, height: 3, borderRadius: 2,
              background: n <= step ? 'var(--accent)' : 'var(--line)',
              transition: 'background .2s',
            }} />
          ))}
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '20px' }}>
          {step === 1 && (
            <Step1Pick picked={picked} setPicked={setPicked} />
          )}
          {step === 2 && (
            <Step2Auth conn={pickedConn} preset={preset} authState={authState} startAuth={startAuth} />
          )}
          {step === 3 && (
            <Step3Test conn={pickedConn} testState={testState} runTest={runTest}
              scopes={scopes} setScopes={setScopes} syncFreq={syncFreq} setSyncFreq={setSyncFreq} />
          )}
        </div>

        {/* Footer */}
        <div style={{
          padding: '12px 20px', borderTop: '0.5px solid var(--line)',
          display: 'flex', alignItems: 'center', gap: 8,
          background: 'var(--bg-sunken)',
        }}>
          {step > 1 ? (
            <button onClick={() => setStep(s => s - 1)} className="nx-btn sm ghost">
              <Icon name="arrow-left" size={12} /> Back
            </button>
          ) : (
            <button onClick={onClose} className="nx-btn sm ghost">Cancel</button>
          )}
          <div style={{ flex: 1, textAlign: 'center', fontSize: 11.5, color: 'var(--ink-4)' }}>
            {step === 1 && picked && <span>Selected: <b style={{ color: 'var(--ink-2)' }}>{pickedConn?.name}</b></span>}
            {step === 2 && authState === 'authed' && <span style={{ color: 'var(--ok)' }}><Icon name="check" size={11} /> Authenticated</span>}
            {step === 3 && testState === 'success' && <span style={{ color: 'var(--ok)' }}><Icon name="check" size={11} /> Connection healthy</span>}
          </div>
          {step === 1 && (
            <button onClick={() => setStep(2)} disabled={!picked}
              className="nx-btn primary sm"
              style={{ opacity: picked ? 1 : 0.4, cursor: picked ? 'pointer' : 'not-allowed' }}>
              Continue <Icon name="arrow-right" size={12} />
            </button>
          )}
          {step === 2 && (
            <button onClick={() => setStep(3)} disabled={authState !== 'authed'}
              className="nx-btn primary sm"
              style={{ opacity: authState === 'authed' ? 1 : 0.4, cursor: authState === 'authed' ? 'pointer' : 'not-allowed' }}>
              Continue <Icon name="arrow-right" size={12} />
            </button>
          )}
          {step === 3 && (
            testState === 'success' ? (
              <button onClick={() => { onClose(); reset(); }} className="nx-btn accent sm">
                <Icon name="check" size={12} /> Finish
              </button>
            ) : (
              <button onClick={runTest} disabled={testState === 'testing'} className="nx-btn primary sm">
                {testState === 'testing' ? (<><Icon name="refresh" size={12} className="nx-spin" /> Testing</>) : (<><Icon name="play" size={12} /> Test & enable</>)}
              </button>
            )
          )}
        </div>
      </div>
    </div>
  );
};

const Step1Pick = ({ picked, setPicked }) => {
  const all = window.NX_DATA.CONNECTORS.filter(c => WIZARD_PRESETS[c.id] || c.status === 'available');
  const cats = ['Database', 'Files', 'SSO & Identity', 'Messaging', 'Custom'];
  const [q, setQ] = React.useState('');
  const list = all.filter(c => !q || c.name.toLowerCase().includes(q.toLowerCase()));

  return (
    <div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        background: 'var(--bg-sunken)', border: '0.5px solid var(--line)',
        borderRadius: 8, padding: '0 10px', height: 32, marginBottom: 14,
      }}>
        <Icon name="search" size={13} style={{ color: 'var(--ink-4)' }} />
        <input autoFocus value={q} onChange={(e) => setQ(e.target.value)}
          placeholder="Search connectors…"
          style={{ border: 0, outline: 0, background: 'transparent', flex: 1, fontSize: 13, fontFamily: 'inherit', color: 'var(--ink)' }} />
      </div>
      {cats.map(cat => {
        const inCat = list.filter(c => c.cat === cat);
        if (inCat.length === 0) return null;
        return (
          <div key={cat} style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 8 }}>
              {cat}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
              {inCat.map(c => (
                <button key={c.id}
                  onClick={() => setPicked(c.id)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '9px 10px', textAlign: 'left',
                    background: picked === c.id ? 'var(--accent-soft)' : 'var(--bg-elev)',
                    border: `0.5px solid ${picked === c.id ? 'var(--accent)' : 'var(--line)'}`,
                    borderRadius: 8, cursor: 'pointer',
                    transition: 'border-color .12s, background .12s',
                  }}
                >
                  <ConnectorTile c={c} size={26} radius={6} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--ink)' }}>{c.name}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--ink-4)' }}>
                      {c.status === 'connected' ? 'Already connected' : 'Quick setup'}
                    </div>
                  </div>
                  {picked === c.id && <Icon name="check" size={14} style={{ color: 'var(--accent)' }} />}
                </button>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
};

const Step2Auth = ({ conn, preset, authState, startAuth }) => {
  if (!conn || !preset) return null;
  const isOAuth = preset.auth === 'oauth';

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
        <ConnectorTile c={conn} size={44} radius={10} />
        <div>
          <div style={{ fontSize: 16, fontWeight: 550 }}>{conn.name}</div>
          <div style={{ fontSize: 12, color: 'var(--ink-4)' }}>
            {isOAuth ? 'OAuth 2.0 — single click' : 'Service account credentials'}
          </div>
        </div>
      </div>

      {isOAuth ? (
        <div>
          <div style={{
            padding: 16, background: 'var(--bg-sunken)',
            borderRadius: 10, marginBottom: 14,
          }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8 }}>
              NalarX will request the following permissions:
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
              {['Read project metadata', 'Read tables and views', 'Read row counts and schemas'].map((p, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--ink-2)' }}>
                  <Icon name="check" size={12} style={{ color: 'var(--ok)' }} />
                  {p}
                </div>
              ))}
            </div>
          </div>
          <button
            onClick={startAuth}
            disabled={authState !== 'idle'}
            style={{
              width: '100%', height: 38, borderRadius: 9,
              border: authState === 'authed' ? '0.5px solid var(--ok)' : '0.5px solid var(--line-strong)',
              background: authState === 'authed' ? 'var(--ok-soft)' : 'var(--bg-elev)',
              color: authState === 'authed' ? 'var(--ok)' : 'var(--ink)',
              fontSize: 13.5, fontWeight: 550, cursor: authState === 'idle' ? 'pointer' : 'default',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              fontFamily: 'inherit',
            }}
          >
            {authState === 'idle' && (<><Icon name="external" size={14} /> Sign in with {conn.name}</>)}
            {authState === 'connecting' && (<><Icon name="refresh" size={14} className="nx-spin" /> Opening {conn.name}…</>)}
            {authState === 'authed' && (<><Icon name="check-circle" size={14} /> Authenticated as nalarx@bankcorp.com</>)}
          </button>
          <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 10, textAlign: 'center' }}>
            <Icon name="lock" size={11} style={{ verticalAlign: '-2px', marginRight: 4 }} />
            Tokens encrypted at rest (AES-256). Revocable any time.
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {preset.fields.map(f => (
            <div key={f.id}>
              <label style={{ fontSize: 11.5, fontWeight: 550, color: 'var(--ink-3)', display: 'block', marginBottom: 4 }}>
                {f.label}
              </label>
              <input
                type={f.type || 'text'}
                defaultValue={f.value}
                placeholder={f.placeholder}
                style={{
                  width: '100%', height: 32, padding: '0 10px',
                  border: '0.5px solid var(--line-strong)',
                  borderRadius: 7, background: 'var(--bg-elev)',
                  fontSize: 13, fontFamily: f.id === 'pass' ? 'var(--font-mono)' : 'inherit',
                  color: 'var(--ink)', outline: 'none',
                }}
              />
            </div>
          ))}
          <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>
            <input type="checkbox" /> Use SSH tunnel
          </label>
          <button onClick={startAuth} disabled={authState !== 'idle'}
            className="nx-btn primary" style={{ marginTop: 6, justifyContent: 'center', height: 34 }}>
            {authState === 'idle' && (<><Icon name="lock" size={13} /> Save credentials</>)}
            {authState === 'connecting' && (<><Icon name="refresh" size={13} className="nx-spin" /> Verifying…</>)}
            {authState === 'authed' && (<><Icon name="check" size={13} /> Saved</>)}
          </button>
        </div>
      )}
    </div>
  );
};

const Step3Test = ({ conn, testState, runTest, scopes, setScopes, syncFreq, setSyncFreq }) => {
  const scopeList = [
    { id: 'public', label: 'public', detail: '142 tables · 24.1M rows' },
    { id: 'finance_ops', label: 'finance_ops', detail: '38 tables · 8.4M rows' },
    { id: 'hr_data', label: 'hr_data', detail: '22 tables · 1.2M rows · contains PII', warn: true },
    { id: 'audit_logs', label: 'audit_logs', detail: '4 tables · 92M rows' },
  ];
  const freqs = [
    { id: '5m', label: 'Every 5 min' },
    { id: '15m', label: 'Every 15 min' },
    { id: '1h', label: 'Hourly' },
    { id: 'manual', label: 'Manual' },
  ];

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
        <ConnectorTile c={conn} size={36} radius={8} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 550 }}>{conn.name}</div>
          <div style={{ fontSize: 11.5, color: 'var(--ok)' }}>
            <Icon name="check" size={11} /> Authenticated · choose what to index
          </div>
        </div>
      </div>

      <div style={{ marginBottom: 16 }}>
        <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
          Schemas to index
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {scopeList.map(s => (
            <label key={s.id} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '8px 10px', borderRadius: 7,
              background: scopes[s.id] ? 'var(--bg-sunken)' : 'transparent',
              border: '0.5px solid var(--line)',
              cursor: 'pointer',
            }}>
              <input type="checkbox" checked={scopes[s.id] || false}
                onChange={(e) => setScopes(p => ({ ...p, [s.id]: e.target.checked }))} />
              <div style={{ flex: 1 }}>
                <div className="nx-mono" style={{ fontSize: 12.5, color: 'var(--ink)' }}>{s.label}</div>
                <div style={{ fontSize: 11, color: s.warn ? 'var(--warn)' : 'var(--ink-4)' }}>
                  {s.warn && <Icon name="shield" size={10} style={{ marginRight: 3, verticalAlign: '-1px' }} />}
                  {s.detail}
                </div>
              </div>
            </label>
          ))}
        </div>
      </div>

      <div style={{ marginBottom: 16 }}>
        <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
          Sync frequency
        </div>
        <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--bg-sunken)', borderRadius: 8 }}>
          {freqs.map(f => (
            <button key={f.id} onClick={() => setSyncFreq(f.id)}
              style={{
                flex: 1, height: 26, border: 0, borderRadius: 5,
                background: syncFreq === f.id ? 'var(--bg-elev)' : 'transparent',
                color: syncFreq === f.id ? 'var(--ink)' : 'var(--ink-3)',
                fontSize: 12, fontWeight: 500, cursor: 'pointer',
                boxShadow: syncFreq === f.id ? '0 1px 2px rgba(0,0,0,.06)' : 'none',
              }}>{f.label}</button>
          ))}
        </div>
      </div>

      {/* Test connection result */}
      <div style={{
        padding: 12, borderRadius: 9,
        background: testState === 'success' ? 'var(--ok-soft)' : 'var(--bg-sunken)',
        border: `0.5px solid ${testState === 'success' ? 'oklch(0.85 0.1 155)' : 'var(--line)'}`,
        fontSize: 12.5,
      }}>
        {testState === 'idle' && (
          <div style={{ color: 'var(--ink-3)' }}>
            <Icon name="play" size={12} style={{ verticalAlign: '-1px', marginRight: 6 }} />
            Click <b style={{ color: 'var(--ink)' }}>Test & enable</b> to validate the connection and start indexing.
          </div>
        )}
        {testState === 'testing' && (
          <div style={{ color: 'var(--ink-2)', display: 'flex', flexDirection: 'column', gap: 4 }}>
            {['Resolving host', 'TLS handshake', 'Reading schema', 'Sampling rows'].map((step, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12 }}>
                <Icon name="refresh" size={11} className="nx-spin" style={{ color: 'var(--accent)' }} />
                <span className="nx-mono" style={{ color: 'var(--ink-3)' }}>{step}…</span>
              </div>
            ))}
          </div>
        )}
        {testState === 'success' && (
          <div style={{ color: 'var(--ok)' }}>
            <Icon name="check-circle" size={13} style={{ verticalAlign: '-2px', marginRight: 6 }} />
            <b>Connection healthy.</b> Initial sync queued — indexing will begin in the background.
          </div>
        )}
      </div>
    </div>
  );
};

window.ScreenWizard = ScreenWizard;
