// Primus IQ — Projects Listing Screen

const SAMPLE_PROJECTS = [
  { id: 'p1', name: 'GCC Market Entry · Acme',  desc: 'Sector Potential Realization — KSA vs UAE entry sequencing, pricing strategy, talent map.', tag: 'Sector Potential Realization', role: 'OWNER',  files: 24, members: ['N', 'A', 'P'], more: 8,  updated: '24 May' },
  { id: 'p2', name: 'Globex APAC Reorg',         desc: 'Impact Realization — operating model redesign across 6 markets, change roadmap with cost guardrails.', tag: 'Impact Realization',        role: 'MEMBER', files: 38, members: ['N', 'M'],      more: 4,  updated: '22 May' },
  { id: 'p3', name: 'India Public Policy 2026', desc: 'Policy track for FY26 — state-level digital governance benchmarks and procurement reform notes.', tag: 'Public Policy Realization', role: 'OWNER',  files: 12, members: ['N', 'V'],      more: 20, updated: '18 May' },
  { id: 'p4', name: 'TCFD · Portfolio Co.',     desc: 'Climate disclosure rollup across 18 portfolio companies — Scope 1/2 baselines, gap remediation.', tag: 'Economic Potential Realization', role: 'MEMBER', files: 19, members: ['N', 'S'],     more: 5,  updated: '12 May' },
];

const DISCOVER_PROJECTS = [
  { id: 'd1', name: 'Indian MSME Financing',  desc: 'Quarterly research on fintech, NBFC and public scheme penetration in MSME credit.', tag: 'Economic Potential Realization', owner: 'A. Mehta',   members: 9,  files: 47, updated: '23 May' },
  { id: 'd2', name: 'Healthcare Supply Atlas', desc: 'Live corpus on global pharma logistics — 220 papers, 40 interviews, monthly refresh.',  tag: 'Transaction Realization',         owner: 'P. Rao',     members: 32, files: 220, updated: '20 May' },
  { id: 'd3', name: 'Auto OEM EV Roadmap',     desc: 'Buy-side diligence for an EV component supplier — capacity, IP, customer concentration.', tag: 'Sector Potential Realization',    owner: 'V. Kumar',   members: 6,  files: 31, updated: '19 May' },
  { id: 'd4', name: 'PSU Disinvestment Track', desc: 'Cross-firm track of PSU strategic-sale candidates, valuation desks and timelines.',     tag: 'Public Policy Realization',       owner: 'S. Iyer',    members: 14, files: 88, updated: '17 May' },
  { id: 'd5', name: 'GCC Renewables 2026',     desc: 'Annual thought-leadership flagship — 80pp report covering capex, regulation, partnerships.', tag: 'Economic Potential Realization', owner: 'N. Singh',   members: 12, files: 65, updated: '20 May' },
  { id: 'd6', name: 'CSR Effectiveness Index',  desc: 'Multi-state index of CSR spend efficiency — quantitative model + interview corpus.',   tag: 'Impact Realization',              owner: 'R. Banerjee', members: 8, files: 28, updated: '14 May' },
];

const adaptProject = (p) => ({
  id: p.id,
  name: p.name,
  desc: p.description || '',
  tag: p.practice || '',
  role: p.membership ? p.membership.toUpperCase() : null,
  membership: p.membership || null,
  hasPendingRequest: p.has_pending_request || false,
  files: p.artifact_count || 0,
  memberCount: p.member_count || 0,
  members: (p.members || []).slice(0, 3).map(m => (m.full_name || '?')[0].toUpperCase()),
  more: Math.max(0, (p.member_count || 0) - 3),
  updated: p.created_at ? new Date(p.created_at).toLocaleDateString('en-IN', { day: 'numeric', month: 'short' }) : '—',
});

const YoursProjectCard = ({ p, onClick, onInvite }) => (
  <div onClick={onClick} style={{
    background: 'white', border: '1px solid var(--line)', borderRadius: 12,
    padding: 16, cursor: 'pointer', transition: 'all 0.18s',
    display: 'flex', flexDirection: 'column', gap: 10,
  }}
  onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--maroon-20)'; e.currentTarget.style.boxShadow = '0 6px 18px rgba(60,30,20,0.06)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
  onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'translateY(0)'; }}
  >
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
        <div style={{
          width: 30, height: 30, borderRadius: 8,
          background: 'var(--maroon-06)', color: 'var(--maroon)',
          display: 'grid', placeItems: 'center', flexShrink: 0,
        }}>
          <PIcon name="folder" size={15} color="var(--maroon)" />
        </div>
        <h3 style={{ fontSize: 14, fontWeight: 600, margin: 0, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</h3>
      </div>
      {p.role && <span className={`role-badge ${p.role === 'OWNER' ? 'owner' : ''}`}>{p.role}</span>}
    </div>

    <p title={p.desc} style={{ fontSize: 12, lineHeight: 1.5, color: 'var(--mute)', margin: 0,
                display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{p.desc}</p>

    <div><span className="tag-pill" style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.tag}</span></div>

    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginTop: 'auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 11, color: 'var(--mute)' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }} title="Files in sources">
          <PIcon name="book" size={12} color="var(--mute)" /> {p.files}
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }} title="Members">
          <PIcon name="users" size={12} color="var(--mute)" /> {p.memberCount}
        </span>
        <span style={{ color: 'var(--mute-2)' }}>· {p.updated}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        {p.role === 'OWNER' && onInvite && (
          <button onClick={(e) => { e.stopPropagation(); onInvite(p); }} title="Invite" style={{
            width: 26, height: 26, borderRadius: 7,
            background: 'transparent', border: '1px solid var(--line-2)',
            cursor: 'pointer', display: 'grid', placeItems: 'center',
            color: 'var(--ink-2)', flexShrink: 0,
          }}>
            <PIcon name="plus" size={11} color="var(--ink-2)" />
          </button>
        )}
      </div>
    </div>
  </div>
);

const DiscoverProjectCard = ({ p, onOpenProject, onJoined }) => {
  const [requested, setRequested] = React.useState(p.hasPendingRequest || false);
  const isMember = !!p.membership;
  const isOwner = p.membership === 'owner';
  const handleRequestJoin = async (e) => {
    e.stopPropagation();
    setRequested(true);
    try {
      await PrimusAPI.joinProject(p.id);
      // Leadership auto-joins → refresh so it moves into "Your projects"; others get pending state.
      if (onJoined) onJoined();
    } catch { setRequested(false); }
  };

  return (
    <div style={{
      background: 'white', border: '1px solid var(--line)', borderRadius: 12,
      padding: 16, transition: 'all 0.18s',
      display: 'flex', flexDirection: 'column', gap: 10,
      cursor: isMember ? 'pointer' : 'default',
    }}
    onMouseEnter={e => e.currentTarget.style.borderColor = isMember ? 'var(--maroon-20)' : 'var(--line-2)'}
    onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--line)'}
    onClick={() => isMember && onOpenProject && onOpenProject(p.id)}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 30, height: 30, borderRadius: 8,
          background: isMember ? 'var(--maroon-06)' : 'var(--bg-soft)',
          color: isMember ? 'var(--maroon)' : 'var(--mute)',
          display: 'grid', placeItems: 'center', flexShrink: 0,
        }}>
          <PIcon name="folder" size={15} color={isMember ? 'var(--maroon)' : 'var(--mute)'} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h3 style={{ fontSize: 14, fontWeight: 600, margin: 0, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</h3>
          <div style={{ fontSize: 11, color: 'var(--mute)', marginTop: 1 }}>
            {p.files} files · {p.memberCount} members · {p.updated}
          </div>
        </div>
        {isMember && <span className={`role-badge ${isOwner ? 'owner' : ''}`}>{p.role}</span>}
      </div>

      <p title={p.desc} style={{ fontSize: 12, lineHeight: 1.5, color: 'var(--mute)', margin: 0,
                  display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{p.desc}</p>

      <div><span className="tag-pill" style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.tag}</span></div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginTop: 'auto' }}>
        <span style={{ fontSize: 11, color: 'var(--mute)', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {isMember ? 'You have access.' : 'Membership required'}
        </span>
        {!isMember && (
          <button onClick={handleRequestJoin} disabled={requested} style={{
            height: 28, padding: '0 11px', borderRadius: 8,
            background: requested ? 'var(--bg-soft)' : 'var(--maroon)',
            color: requested ? 'var(--mute)' : 'white',
            border: 'none', cursor: requested ? 'default' : 'pointer',
            fontSize: 11.5, fontWeight: 600, fontFamily: 'inherit',
            display: 'inline-flex', alignItems: 'center', gap: 5, flexShrink: 0,
            transition: 'all 0.15s',
          }}>
            {requested ? (
              <>
                <svg width="11" height="11" viewBox="0 0 12 12"><path d="M3 6.5l2 2 4-4.5" stroke="currentColor" fill="none" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                Requested
              </>
            ) : (
              <>
                Request to join
                <svg width="10" height="10" viewBox="0 0 12 12"><path d="M3 6h6M6 3l3 3-3 3" stroke="white" fill="none" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </>
            )}
          </button>
        )}
        {isMember && (
          <button onClick={(e) => { e.stopPropagation(); onOpenProject && onOpenProject(p.id); }} className="btn-secondary" style={{ height: 28, padding: '0 11px', fontSize: 11.5, flexShrink: 0 }}>
            Open
          </button>
        )}
      </div>
    </div>
  );
};

const ProjectsListing = ({ setRoute, openCreate, openInvite, projects, onOpenProject, currentUser, onJoined }) => {
  const [tab, setTab] = React.useState(0);
  const [q, setQ] = React.useState('');
  // Only Management / Leadership may create projects (mirrors backend RBAC).
  const canCreateProject = currentUser?.tier === 'management' || currentUser?.tier === 'leadership';

  // Instant client-side filter — the full list is already loaded, so no network round-trip.
  const allData = projects ? projects.map(adaptProject) : [];
  const myData = allData.filter(p => p.membership !== null);
  const discData = allData;
  const data = tab === 0 ? myData : discData;
  const ql = q.trim().toLowerCase();
  const filtered = ql
    ? data.filter(p => (p.name || '').toLowerCase().includes(ql) || (p.desc || '').toLowerCase().includes(ql))
    : data;

  return (
    <div style={{ flex: 1, height: '100%', background: 'var(--bg)', position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <div className="mobile-p-16" style={{ padding: '40px 48px 0', flexShrink: 0 }}>
        <div style={{ maxWidth: 1120, margin: '0 auto' }}>
        <div className="mobile-stack" style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 28 }}>
          <div>
            <h1 className="serif" style={{ fontSize: 28, fontWeight: 500, margin: 0, letterSpacing: '-0.02em' }}>Projects</h1>
            <p style={{ fontSize: 13, color: 'var(--mute)', margin: '6px 0 0' }}>
              Workspaces with their own files, instructions and chat history.
            </p>
          </div>
          {canCreateProject && (
            <button className="btn-primary" onClick={openCreate}>
              <PIcon name="plus" size={14} color="white"/> New project
            </button>
          )}
        </div>
        <div className="mobile-stack" style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 0, borderBottom: '1px solid var(--line)' }}>
          {['Your projects', 'Discover'].map((t, i) => (
            <button key={t} onClick={() => setTab(i)} style={{
              padding: '12px 2px', background: 'transparent', border: 'none', cursor: 'pointer',
              fontSize: 14, fontFamily: 'inherit', fontWeight: tab === i ? 600 : 500,
              color: tab === i ? 'var(--ink)' : 'var(--mute)',
              borderBottom: tab === i ? '2px solid var(--maroon)' : '2px solid transparent',
              marginBottom: -1, transition: 'color 0.15s',
            }}>
              {t}
              {i === 1 && <span style={{ marginLeft: 6, fontSize: 11, color: 'var(--mute-2)', fontWeight: 500 }}>· {discData.length} firmwide</span>}
            </button>
          ))}
          <div style={{ flex: 1 }} />
          <div className="search-input" style={{ width: 280, height: 36 }}>
            <PIcon name="search" size={16} color="var(--mute)" />
            <input value={q} onChange={e => setQ(e.target.value)} placeholder={tab === 0 ? 'Filter your projects' : 'Search all projects in the firm'} />
          </div>
        </div>
        </div>
      </div>

      <div className="pi-thin-scroll mobile-p-16" style={{ flex: 1, overflowY: 'auto', padding: '20px 48px 40px' }}>
        <div style={{ maxWidth: 1120, margin: '0 auto' }}>
          {tab === 1 && (
            <div style={{
              padding: '12px 16px', borderRadius: 10, marginBottom: 18,
              background: 'var(--gold-soft)', border: '1px solid var(--cli-bd)',
              display: 'flex', alignItems: 'center', gap: 10,
              fontSize: 13, color: 'var(--cli-fg)',
            }}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <circle cx="8" cy="8" r="6.5" stroke="currentColor" strokeWidth="1.4"/>
                <path d="M8 5v3.5M8 11v.01" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
              </svg>
              Discover surfaces every project across Primus Partners. Request to join, or browse public deliverables.
            </div>
          )}
          <div className="pi-grid-3" style={{ gap: 14 }}>
            {filtered.map(p => tab === 0
              ? <YoursProjectCard key={p.id} p={p} onClick={() => onOpenProject ? onOpenProject(p.id) : setRoute('project-detail')} onInvite={openInvite} />
              : <DiscoverProjectCard key={p.id} p={p} onOpenProject={onOpenProject} onJoined={onJoined} />
            )}
          </div>
          {filtered.length === 0 && (
            <div style={{
              padding: 60, borderRadius: 14, background: 'white', border: '1px dashed var(--line-2)',
              textAlign: 'center', fontSize: 14, color: 'var(--mute)',
            }}>
              {q
                ? `No projects match "${q}".`
                : tab === 0
                  ? <span>No projects yet. <button onClick={openCreate} style={{ background: 'none', border: 'none', color: 'var(--maroon)', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14 }}>Create your first project.</button></span>
                  : 'No firm-wide projects found.'}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, {
  SAMPLE_PROJECTS,
  DISCOVER_PROJECTS,
  adaptProject,
  YoursProjectCard,
  DiscoverProjectCard,
  ProjectsListing,
});
