// Integrations marketplace — browse + filter + connection state.

const ScreenMarketplace = ({ openWizard }) => {
  const [filter, setFilter] = React.useState('All');
  const [query, setQuery] = React.useState('');
  const [showConnected, setShowConnected] = React.useState(false);

  const cats = ['All', 'Database', 'Files', 'SSO & Identity', 'Messaging', 'Custom'];
  const all = window.NX_DATA.CONNECTORS;

  const list = all.filter(c => {
    if (filter !== 'All' && c.cat !== filter) return false;
    if (showConnected && !(c.status === 'connected' || c.status === 'syncing')) return false;
    if (query && !c.name.toLowerCase().includes(query.toLowerCase())) return false;
    return true;
  });

  const connectedCount = all.filter(c => c.status === 'connected' || c.status === 'syncing').length;

  return (
    <div className="nx-page" style={{
      padding: '24px 32px 40px',
      maxWidth: 1280, margin: '0 auto',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 20 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em' }}>
            Integrations
          </h1>
          <div style={{ marginTop: 4, color: 'var(--ink-3)', fontSize: 13.5 }}>
            {connectedCount} of {all.length} connected · self-serve setup, no engineer required
          </div>
        </div>
        <button onClick={openWizard} className="nx-btn primary">
          <Icon name="plus" size={13} />
          New connection
        </button>
      </div>

      {/* Filter bar */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        marginBottom: 16, flexWrap: 'wrap',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6,
          background: 'var(--bg-elev)', border: '0.5px solid var(--line)',
          borderRadius: 8, padding: '0 10px', height: 32,
          flex: '0 1 280px',
        }}>
          <Icon name="search" size={13} style={{ color: 'var(--ink-4)' }} />
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search 200+ connectors"
            style={{ border: 0, outline: 0, background: 'transparent', flex: 1, fontSize: 13, color: 'var(--ink)', fontFamily: 'inherit' }}
          />
        </div>
        <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--bg-sunken)', borderRadius: 8 }}>
          {cats.map(c => (
            <button key={c}
              onClick={() => setFilter(c)}
              style={{
                padding: '0 10px', height: 26, border: 0, borderRadius: 5,
                background: filter === c ? 'var(--bg-elev)' : 'transparent',
                color: filter === c ? 'var(--ink)' : 'var(--ink-3)',
                fontSize: 12, fontWeight: 500, cursor: 'pointer',
                boxShadow: filter === c ? '0 1px 2px rgba(0,0,0,.06)' : 'none',
              }}
            >{c}</button>
          ))}
        </div>
        <div style={{ flex: 1 }} />
        <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--ink-3)', cursor: 'pointer' }}>
          <input type="checkbox" checked={showConnected} onChange={(e) => setShowConnected(e.target.checked)} />
          Connected only
        </label>
      </div>

      {/* Connector grid */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(248px, 1fr))',
        gap: 10,
      }}>
        {list.map(c => <ConnectorCard key={c.id} c={c} openWizard={openWizard} />)}
      </div>

      {list.length === 0 && (
        <div style={{ textAlign: 'center', padding: 40, color: 'var(--ink-4)' }}>
          No connectors match. <button onClick={() => { setFilter('All'); setQuery(''); setShowConnected(false); }} style={{ background: 'transparent', border: 0, color: 'var(--accent-ink)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13 }}>Clear filters</button>
        </div>
      )}
    </div>
  );
};

const ConnectorCard = ({ c, openWizard }) => {
  const isOn = c.status === 'connected' || c.status === 'syncing';
  return (
    <div className="nx-card" style={{
      padding: 14,
      display: 'flex', flexDirection: 'column', gap: 10,
      borderColor: c.highlight ? 'oklch(0.85 0.12 145)' : 'var(--line)',
      position: 'relative',
      transition: 'border-color .12s, transform .12s',
    }}>
      {c.highlight && (
        <div style={{
          position: 'absolute', top: -1, right: 12,
          background: 'oklch(0.62 0.13 145)', color: 'white',
          fontSize: 9.5, fontWeight: 600, letterSpacing: '0.05em',
          padding: '2px 7px', borderRadius: '0 0 5px 5px',
          textTransform: 'uppercase',
        }}>New</div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <ConnectorTile c={c} size={36} radius={8} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 13.5, fontWeight: 550, color: 'var(--ink)' }}>
            {c.name}
          </div>
          <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{c.cat}</div>
        </div>
      </div>

      {isOn ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11.5, color: 'var(--ink-3)' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              {c.status === 'syncing' ? (
                <><Icon name="refresh" size={11} className="nx-spin" style={{ color: 'var(--accent)' }} /> <span style={{ color: 'var(--accent)' }}>Syncing</span></>
              ) : (
                <><span style={{ width: 6, height: 6, borderRadius: 50, background: 'var(--ok)' }} /> <span style={{ color: 'var(--ok)' }}>Connected</span></>
              )}
            </span>
            <span className="nx-mono" style={{ fontSize: 11 }}>{c.synced}</span>
          </div>
          {c.records && (
            <div className="nx-mono" style={{ fontSize: 11, color: 'var(--ink-4)' }}>
              {c.records}
            </div>
          )}
          <div style={{ display: 'flex', gap: 6, marginTop: 2 }}>
            <button className="nx-btn sm ghost" style={{ flex: 1, justifyContent: 'center', color: 'var(--ink-3)' }}><Icon name="gear" size={12} />Configure</button>
            <button className="nx-btn sm ghost" style={{ color: 'var(--ink-3)' }}><Icon name="menu-dots" size={13} /></button>
          </div>
        </div>
      ) : (
        <>
          <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>
            Available · ~3 min setup
          </div>
          <button onClick={openWizard} className="nx-btn sm" style={{ justifyContent: 'center', width: '100%' }}>
            <Icon name="plus" size={12} /> Connect
          </button>
        </>
      )}
    </div>
  );
};

window.ScreenMarketplace = ScreenMarketplace;
