"use client";

interface Props<T> {
  items: T[];
  onChange: (items: T[]) => void;
  emptyItem: T;
  addLabel: string;
  renderItem: (
    item: T,
    update: (patch: Partial<T>) => void,
    index: number
  ) => React.ReactNode;
}

export default function RepeatableCardList<T>({
  items,
  onChange,
  emptyItem,
  addLabel,
  renderItem,
}: Props<T>) {
  const updateAt = (index: number, patch: Partial<T>) => {
    const next = items.slice();
    next[index] = { ...next[index], ...patch };
    onChange(next);
  };

  const removeAt = (index: number) => {
    onChange(items.filter((_, i) => i !== index));
  };

  return (
    <>
      {items.map((item, index) => (
        <div key={index} className="astrologer-repeat-card">
          {items.length > 1 && (
            <button
              type="button"
              className="astrologer-repeat-remove"
              onClick={() => removeAt(index)}
              aria-label="Remove"
            >
              &times;
            </button>
          )}

          {renderItem(item, (patch) => updateAt(index, patch), index)}
        </div>
      ))}

      <button
        type="button"
        className="astrologer-add-more"
        onClick={() => onChange([...items, emptyItem])}
      >
        + {addLabel}
      </button>
    </>
  );
}
