'use client'

import { memo, useMemo } from 'react'
import { DAY_ABBREV, formatDateKey, getISOWeek, isToday, MONTH_NAMES } from '@/lib/planning-config'
import type { CalendarColors } from '@/lib/planning-settings'
import { SNAP_NAME_COL_W, SNAP_DAY_COL_W } from '@/lib/planning/grid-snap'

// ── Helpers ──────────────────────────────────────────────────────────────────

function hexToRgba(hex: string, alpha: number): string {
 const r = parseInt(hex.slice(1, 3), 16)
 const g = parseInt(hex.slice(3, 5), 16)
 const b = parseInt(hex.slice(5, 7), 16)
 return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

// ── Props ─────────────────────────────────────────────────────────────────────

interface Props {
 days: Date[]
 selectedWeeks: Set<number>
 calendarColors: CalendarColors
 holidayMap: Map<string, string>
 onToggleWeek: (week: number) => void
}

// ── Row heights + sticky offsets ──────────────────────────────────────────────
// Row 0 — Month names: h-4  = 16px  → sticky top-0
// Row 1 — KW numbers:  h-6  = 24px  → sticky top-4   (16px)
// Row 2 — Day cells:   h-7  = 28px  → sticky top-10  (40px)
// Total header height = 68px
//
// BORDER MODEL: table uses border-separate border-spacing-0.
// All borders are element borders (border-box), identical to body day-div borders.
// Row-separator borders are on <th> cells, NOT on <tr> elements.
//
// MONTH NAMES: position:absolute inside overflow:hidden <th> → zero width influence.
// KW LABELS:   position:absolute + left:50% translateX(-50%) → always centered over colSpan.

// ── Component ─────────────────────────────────────────────────────────────────

function PlanningHeaderInner({ days, selectedWeeks, calendarColors, holidayMap, onToggleWeek }: Props) {
 const selColor = calendarColors.selectionHighlightColor ?? '#3B82F6'
 const selOp   = calendarColors.selectionHighlightOpacity ?? 8

 // Month groups: consecutive days sharing the same calendar month.
 const monthGroups = useMemo(() => {
  const groups: { month: number; year: number; count: number }[] = []
  for (const day of days) {
   const m = day.getMonth()
   const y = day.getFullYear()
   const last = groups[groups.length - 1]
   if (!last || last.month !== m || last.year !== y) {
    groups.push({ month: m, year: y, count: 1 })
   } else {
    last.count++
   }
  }
  return groups
 }, [days])

 // KW groups: a new group starts every Monday (or the first day of the range).
 // Breaks only at week boundaries — NOT at month boundaries.
 const weekGroups = useMemo(() => {
  const groups: { kw: number; count: number }[] = []
  for (const day of days) {
   const kw = getISOWeek(day)
   if (groups.length === 0 || day.getDay() === 1) {
    groups.push({ kw, count: 1 })
   } else {
    groups[groups.length - 1].count++
   }
  }
  return groups
 }, [days])

 return (
  <thead>
   {/* ── Row 0: Month names (16px) ──────────────────────────────────────────
       Each <th> has overflow:hidden so the absolutely-positioned month label
       never participates in column-width calculation.                        */}
   <tr>
    {/* Name column: rowSpan=3 covers all 3 header rows */}
    <th
     rowSpan={3}
     className="sticky left-0 top-0 z-[45] bg-muted border-r border-b-2 border-input px-3 align-middle text-left text-[11px] font-semibold text-muted-foreground whitespace-nowrap"
     style={{ width: SNAP_NAME_COL_W, minWidth: SNAP_NAME_COL_W }}
    >
     Mitarbeiter
    </th>

    {monthGroups.map((mg, i) => (
     <th
      key={`month-${mg.year}-${mg.month}`}
      colSpan={mg.count}
      className={[
       'sticky top-0 z-30 h-4 border-r border-b border-input',
       /* overflow:hidden prevents the abs-positioned label from widening the column */
       'overflow-hidden relative',
       i % 2 === 0 ? 'bg-muted' : 'bg-[#E8EDF2]',
      ].join(' ')}
     >
      {/* position:absolute + whitespace-nowrap → no flow contribution */}
      <span className="absolute left-2 top-1/2 -translate-y-1/2 text-[10px] font-semibold text-muted-foreground whitespace-nowrap pointer-events-none">
       {MONTH_NAMES[mg.month]}
      </span>
     </th>
    ))}
   </tr>

   {/* ── Row 1: KW numbers (24px) ───────────────────────────────────────────
       KW label is position:absolute + left:50% translateX(-50%) so it is always
       centered over the full colSpan, even for partial weeks at month edges.  */}
   <tr>
    {weekGroups.map((wg, i) => {
     const active = selectedWeeks.has(wg.kw)
     return (
      <th
       key={`kw-${i}-${wg.kw}`}
       colSpan={wg.count}
       className="sticky top-4 z-30 h-6 bg-muted border-r border-b border-input relative cursor-pointer select-none"
       style={active ? {
        backgroundColor: hexToRgba(selColor, (selOp + 2) / 100),
        borderBottomWidth: '2px',
        borderBottomColor: 'var(--primary)',
       } : undefined}
       onClick={() => onToggleWeek(wg.kw)}
      >
       {/* Centered over the colSpan regardless of partial-week width */}
       <span
        className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 font-condensed font-bold text-[10px] text-[#374151] whitespace-nowrap pointer-events-none"
        style={{ left: `${(wg.count * SNAP_DAY_COL_W) / 2}px` }}
       >
        KW{wg.kw}
       </span>
      </th>
     )
    })}
   </tr>

   {/* ── Row 2: Day number + abbreviation (28px) ────────────────────────── */}
   <tr>
    {days.map((day, di) => {
     const dk           = formatDateKey(day)
     const todayDay     = isToday(day)
     const weekend      = day.getDay() === 0 || day.getDay() === 6
     const holidayName  = holidayMap.get(dk)
     const isSpecial    = weekend || !!holidayName
     const isMonthStart = day.getDate() === 1 && di > 0
     return (
      <th
       key={dk}
       data-date={dk}
       title={holidayName}
       className={[
        'sticky top-10 z-30 h-7 py-0.5 border-b-2 border-input text-center whitespace-nowrap',
        isMonthStart
         ? 'border-l-2 border-l-input border-r border-r-input'
         : 'border-r border-input',
        todayDay    ? 'bg-[#EFF6FF] text-[#1D4ED8]'
        : isSpecial ? 'bg-[#E5E7EB] text-[#888888]'
        : 'bg-muted text-foreground',
       ].join(' ')}
       style={{ width: SNAP_DAY_COL_W, minWidth: SNAP_DAY_COL_W, maxWidth: SNAP_DAY_COL_W }}
      >
       <div className="text-[9px] leading-tight">{DAY_ABBREV[day.getDay()]}</div>
       <div className={`text-[11px] font-bold leading-tight ${todayDay ? 'text-[#1D4ED8]' : ''}`}>
        {day.getDate()}
       </div>
       {holidayName && (
        <div className="flex justify-center">
         <span className="w-1 h-1 rounded-full bg-[#F59E0B]" />
        </div>
       )}
      </th>
     )
    })}
   </tr>
  </thead>
 )
}

export default memo(PlanningHeaderInner)
