<script lang="ts">
  import SkillBadge from './SkillBadge.svelte'
  import { Marquee } from '@/components/ui/marquee'
  import type { Component } from 'svelte'

  interface Skill {
    name: string
    icon: Component
  }

  interface Props {
    title: string
    skills: Skill[]
    direction?: 'left' | 'up'
    reverse?: boolean
    fade?: boolean
    pauseOnHover?: boolean
    duration?: string
    gap?: string
    maxPerRow?: number
    class?: string
  }

  let {
    title,
    skills,
    direction = 'left',
    reverse = false,
    fade = true,
    pauseOnHover = false,
    duration = '20s',
    gap = '1rem',
    maxPerRow,
    class: className = ''
  }: Props = $props()

  // Smart chunking - balances rows to avoid sparse last row
  function balancedChunk<T>(array: T[], max: number): T[][] {
    const total = array.length

    // If fits in one row, use one row
    if (total <= max) return [array]

    // Calculate number of rows needed
    const numRows = Math.ceil(total / max)

    // Calculate ideal items per row (distribute evenly)
    const basePerRow = Math.floor(total / numRows)
    const remainder = total % numRows

    const chunks: T[][] = []
    let index = 0

    for (let i = 0; i < numRows; i++) {
      // Distribute remainder across first rows
      const rowSize = basePerRow + (i < remainder ? 1 : 0)
      chunks.push(array.slice(index, index + rowSize))
      index += rowSize
    }

    return chunks
  }

  let rows = $derived(
    maxPerRow ? balancedChunk(skills, maxPerRow) : [skills]
  )
</script>

<section class="space-y-4">
  <h3 class="text-foreground font-custom text-xl font-bold">{title}</h3>
  <div class="space-y-3">
    {#each rows as rowSkills, rowIndex (rowIndex)}
      <Marquee
        {direction}
        {fade}
        reverse={rowIndex % 2 === 0 ? reverse : !reverse}
        {pauseOnHover}
        {duration}
        {gap}
        class={className}
      >
        {#each rowSkills as skill (skill.name)}
          <SkillBadge name={skill.name} icon={skill.icon} />
        {/each}
      </Marquee>
    {/each}
  </div>
</section>
