import React from 'react';
import { getPayload } from 'payload';
import configPromise from '@payload-config';
import { TeamGrid as TeamGridComponent } from './TeamGrid';

export interface TeamGridBlockProps {
  title?: string;
  subtitle?: string;
  filterBranch?: string;
}

export const TeamGridBlock = async (props: TeamGridBlockProps) => {
  const { title, subtitle, filterBranch } = props;
  const payload = await getPayload({ config: configPromise });

  const query: any = {
    collection: 'team',
    limit: 100,
    depth: 1,
  };

  if (filterBranch && filterBranch !== 'all') {
    query.where = {
      branch: {
        equals: filterBranch,
      },
    };
  }

  const { docs: teamMembers } = await payload.find(query);

  // Map Payload docs to TeamGrid expected format
  const members = teamMembers.map((m: any) => ({
    id: m.id,
    name: m.name,
    position: m.position,
    email: m.email,
    phone: m.phone,
    image: m.image,
    branch: m.branch,
  }));

  return (
    <div className="team-grid-block">
      {/* Passing data to the client component */}
      <TeamGridComponent members={members} />
    </div>
  );
};
