// Primus IQ — Search Screen

const ScreenSearch = ({ setRoute, allProjects = [], onOpenProject }) => {
  const [q, setQ] = React.useState('');
  const adapted = allProjects.map(adaptProject);
  const matches = q
    ? adapted.filter(p =>
        p.name.toLowerCase().includes(q.toLowerCase()) ||
        (p.desc && p.desc.toLowerCase().includes(q.toLowerCase())) ||
        (p.tag && p.tag.toLowerCase().includes(q.toLowerCase()))
      )
    : [];
  return (
    <div style={contentArea}>
      <div className="mobile-p-16" style={{ padding: '40px 48px 40px', maxWidth: 820, margin: '0 auto' }}>
        <h1 className="serif" style={{ fontSize: 28, fontWeight: 500, margin: 0, letterSpacing: '-0.02em', marginBottom: 6 }}>Search</h1>
        <p style={{ fontSize: 13, color: 'var(--mute)', margin: '0 0 22px' }}>
          Across all projects in the firm — your own and your colleagues'.
        </p>
        <div className="search-input" style={{ height: 52, paddingLeft: 18 }}>
          <PIcon name="search" size={18} color="var(--mute)" />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Try “GCC fintech”, “TCFD”, “MSME financing”…" autoFocus />
        </div>

        {!q && (
          <div style={{ marginTop: 32, textAlign: 'center', color: 'var(--mute)', fontSize: 13 }}>
            Start typing to search across all projects.
          </div>
        )}

        {q && (
          <>
            <div style={{ fontSize: 12, color: 'var(--mute)', margin: '24px 0 10px' }}>
              {matches.length} projects matching “{q}”
            </div>
            <div style={{ display: 'grid', gap: 10 }}>
              {matches.map(p => {
                const isMember = p.membership !== null;
                const isOwner = p.membership === 'owner';
                return <SearchProjectRow key={p.id} p={p} isMember={isMember} isOwner={isOwner} setRoute={setRoute} onOpenProject={onOpenProject}/>;
              })}
              {matches.length === 0 && (
                <div style={{ padding: 24, borderRadius: 12, background: 'var(--bg-card)', border: '1px solid var(--line)', fontSize: 13, color: 'var(--mute)', textAlign: 'center' }}>
                  No projects matched. Try a different keyword.
                </div>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
};

const SearchProjectRow = ({ p, isMember, isOwner, setRoute, onOpenProject }) => {
  const [requested, setRequested] = React.useState(p.hasPendingRequest || false);
  const handleRequestJoin = async () => {
    try {
      await PrimusAPI.joinProject(p.id);
      setRequested(true);
    } catch { setRequested(true); }
  };
  return (
    <div style={{
      background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 12,
      padding: 14, display: 'flex', alignItems: 'center', gap: 14,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 9,
        background: isMember ? 'var(--maroon-06)' : 'var(--bg-soft)',
        color: isMember ? 'var(--maroon)' : 'var(--mute)',
        display: 'grid', placeItems: 'center', flexShrink: 0,
      }}>
        <PIcon name="folder" size={17} color={isMember ? 'var(--maroon)' : 'var(--mute)'} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{p.name}</div>
          {isMember && p.membership && (
            <span className={`role-badge ${p.membership}`}>{p.membership.toUpperCase()}</span>
          )}
          {p.tag && <span className="tag-pill">{p.tag}</span>}
        </div>
        <div style={{ fontSize: 12, color: 'var(--mute)', marginTop: 3, display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{p.desc}</div>
      </div>
      {isMember ? (
        <button onClick={() => { onOpenProject && onOpenProject(p.id); setRoute('project-detail'); }} className="btn-secondary" style={{ height: 34, padding: '0 12px', fontSize: 13, flexShrink: 0 }}>Open</button>
      ) : (
        <button onClick={handleRequestJoin} disabled={requested} style={{
          height: 34, padding: '0 14px', borderRadius: 8,
          background: requested ? 'var(--bg-soft)' : 'var(--maroon)',
          color: requested ? 'var(--mute)' : 'white', border: 'none',
          fontSize: 12, fontFamily: 'inherit', fontWeight: 600,
          cursor: requested ? 'default' : 'pointer',
          flexShrink: 0,
        }}>{requested ? '✓ Requested' : 'Request to join'}</button>
      )}
    </div>
  );
};

Object.assign(window, {
  ScreenSearch,
  SearchProjectRow,
});
