# Arbeitszeitrechner - Comprehensive Documentation

**Last Updated:** 2026-01-21

**Recent Updates (2026-01-07):**

- ✅ Multi-year holiday support: Holidays are now loaded for all years in a date range
- ✅ Improved date iteration: Replaced for loop with reliable while loop to prevent timezone issues
- ✅ Holiday API integration: Uses shared HolidayService with OpenHolidays API
- ✅ Enhanced error handling: Improved error visibility and fallback mechanisms
- ✅ Comprehensive logging: Added detailed console logs for debugging

## Tool Overview

### Basic Information

- **Tool Name:** Arbeitszeitrechner (Working Time Calculator)
- **Slug:** `arbeitszeitrechner`
- **URL:** `https://www.ordio.com/tools/arbeitszeitrechner`
- **Status:** Available
- **Last Updated:** 2026-01-21

### Purpose

## Technical Implementation

### Files

- **PHP:** `v2/pages/tools_arbeitszeitrechner.php`
- **JavaScript:** `/v2/js/shared/holiday-service.js?v=<?php echo filemtime(__DIR__ . `
- **JavaScript:** `/v2/js/tools-arbeitszeit-calculator.js?v=<?php echo filemtime(__DIR__ . `
- **JavaScript:** `/v2/js/lead-capture-triggers.min.js?v=<?php echo filemtime(__DIR__ . `
Calculate working times, breaks, and overtime according to German Arbeitszeitgesetz (ArbZG) and Jugendarbeitsschutzgesetz (JArbSchG). Includes comprehensive compliance checks, daily/weekly calculations, industry-specific templates, and export functionality. Supports both simple quick calculations and advanced multi-day calculations with detailed compliance analysis.

### Use Cases

- **Employees:** Calculate working hours and breaks
- **Employers:** Ensure Arbeitszeitgesetz compliance
- **HR Professionals:** Process time records
- **Compliance Officers:** Verify legal compliance
- **Shift Workers:** Calculate shift hours and breaks
- **Part-time Workers:** Track working hours

### Real-World Scenarios

**Scenario 1: Shift Worker Tracking Weekly Hours**
- **User:** Shift worker tracking hours for payroll
- **Situation:** Works varying shifts (8h, 10h, 6h) across 5 days, needs to calculate total hours
- **Goal:** Calculate total working hours including breaks for payroll
- **Steps:**
  1. Select Simple Mode
  2. Add day cards for each shift
  3. Enter start time, end time, break duration for each day
  4. Review calculated hours (Brutto/Netto)
  5. Copy total hours for payroll submission
- **Result:** Sees total 40 hours (Brutto), 36 hours (Netto after breaks)
- **Related Tools:** [Stundenlohnrechner](stundenlohnrechner-documentation.md) (for hourly rate calculation), [Zuschlagsrechner](zuschlagsrechner-documentation.md) (for shift surcharges)

**Scenario 2: HR Manager Ensuring Compliance**
- **User:** HR professional verifying Arbeitszeitgesetz compliance
- **Situation:** Employee worked 10 hours/day for 3 consecutive days, need to verify compliance
- **Goal:** Check if working hours comply with ArbZG regulations
- **Steps:**
  1. Select Advanced Mode
  2. Enter period dates
  3. Enter daily working hours: 10 hours
  4. Review compliance warnings
  5. Check daily/weekly limits
  6. Document compliance status
- **Result:** Sees compliance warning (10h exceeds 8h daily limit, requires approval)
- **Related Tools:** [Zuschlagsrechner](zuschlagsrechner-documentation.md) (for overtime surcharges), [Urlaubsanspruch-Rechner](urlaubsanspruch-rechner-documentation.md) (for vacation calculation)

**Scenario 3: Employer Planning Shift Schedule**
- **User:** Business owner planning weekly shift schedule
- **Situation:** Need to plan shifts for 5 employees, ensure compliance with ArbZG
- **Goal:** Calculate total hours per employee and verify compliance
- **Steps:**
  1. Use Advanced Mode
  2. Enter contract hours: 40 hours/week
  3. Plan shifts for each employee
  4. Review total hours and compliance
  5. Adjust schedule if needed
- **Result:** Sees total hours per employee, compliance status, can optimize schedule
- **Related Tools:** [ROI-Rechner Schichtplanung](roi-rechner-schichtplanung-documentation.md) (for cost optimization), [Kostenrechner](kostenrechner-documentation.md) (for labor costs)

**Scenario 4: Part-Time Worker Verifying Hours**
- **User:** Part-time worker verifying hours match contract
- **Situation:** Contract: 20 hours/week, worked 22 hours this week, need to verify
- **Goal:** Calculate actual hours and compare with contract
- **Steps:**
  1. Enter contract hours: 20 hours/week
  2. Enter actual working hours for each day
  3. Review calculated total
  4. Compare with contract
  5. Document overtime if applicable
- **Result:** Sees 22 hours total, 2 hours overtime, can claim overtime pay
- **Related Tools:** [Brutto-Netto-Rechner](brutto-netto-rechner-documentation.md) (for salary calculation), [Zuschlagsrechner](zuschlagsrechner-documentation.md) (for overtime surcharges)

### Target Audience

- Employees
- Employers
- HR professionals
- Compliance officers
- Shift workers
- Part-time workers

### Visual Description

**Hero Section:**

- Layout: Centered hero section with badge, headline, and description
- Badge: "Arbeitszeitrechner" badge
- Headline: Large bold headline "Arbeitszeitrechner 2026: Kostenlos Arbeitszeit berechnen" with blue accent
- Description: Paragraph explaining calculator features
- Background: Subtle dot pattern background

**Visual Examples (To Be Added):**

**Hero Section Screenshot:**
- Location: `docs/guides/tools-pages/screenshots/arbeitszeitrechner-hero.png`
- Description: Full hero section showing badge, headline, description
- Dimensions: 1920x1080 (desktop), 375x667 (mobile)
- Shows: Complete above-fold content with visual styling

**Simple Mode Form Screenshot:**
- Location: `docs/guides/tools-pages/screenshots/arbeitszeitrechner-simple.png`
- Description: Simple mode showing day cards with time inputs
- Dimensions: 1920x1080 (desktop)
- Shows: Day cards, time inputs, break duration, calculated hours, templates

**Advanced Mode Form Screenshot:**
- Location: `docs/guides/tools-pages/screenshots/arbeitszeitrechner-advanced.png`
- Description: Advanced mode showing period settings, compliance checks
- Dimensions: 1920x1080 (desktop)
- Shows: Period inputs, Bundesland selection, compliance warnings, detailed breakdown

**Compliance Flow Diagram:**
- Location: `docs/guides/tools-pages/diagrams/arbeitszeitrechner-compliance.svg`
- Description: Flow diagram showing Arbeitszeitgesetz compliance checking process
- Format: SVG (vector) for scalability
- Shows: Input → Compliance Check → Warning/Approval → Output flow

**Mode Selection:**

- Layout: Tab switcher (Simple Mode / Advanced Mode)
- Simple Mode Tab: "Schnell-Rechner" (Quick Calculator)
- Advanced Mode Tab: "Detaillierter Rechner" (Detailed Calculator)
- Styling: Blue accent for active tab, gray for inactive

**Simple Mode Form:**

- Layout: Centered single-column layout
- Day Cards: Multiple day cards (can add/remove/clone days)
- Each Day Card:
  - Day number badge
  - Start Time input (HH:MM)
  - End Time input (HH:MM)
  - Break Duration input (HH:MM)
  - Calculated hours display (Brutto/Netto)
  - Clone/Delete buttons
- Quick Templates: Buttons for Standard/Early/Late shifts
- Industry Templates: Buttons for Gastronomie/Einzelhandel/Pflege/Büro/Schichtarbeit/Handwerk
- Result Display: Total hours (Brutto/Netto), Copy button
- Styling: Blue accent color (#4D8EF3), rounded cards, responsive grid

**Advanced Mode Form:**

- Layout: Centered single-column layout with collapsible sections
- Basic Settings Section (Always Visible):
  - Period: Start date and End date inputs
  - Bundesland: Dropdown (16 German states)
  - Consider Holidays: Toggle
  - Week Model: Radio buttons (5-day/6-day week)
  - Contract Hours: Weekly and Daily inputs
- Advanced Settings Section (Collapsible):
  - Tarifabweichung: Toggle
  - Tarif Reference Months: Number input
  - Industry Night Window: Dropdown (Standard/Bakery)
  - Minor Mode: Toggle (JArbSchG)
  - Rounding: Dropdown (Off/1min/5min/15min)
- Bulk Settings Section (Collapsible):
  - Work Start/End: Time inputs
  - Break Start/End: Time inputs
  - Break Paid: Toggle
  - Include Weekends/Holidays: Toggles
  - Apply Bulk Settings: Button
- Daily Entries Section (Collapsible):
  - Daily entry cards for each day in period
  - Each card: Date, Segments (multiple work periods), Breaks (multiple breaks), Add/Remove buttons
- Calculate Button: Triggers calculation and scrolls to results
- Styling: Blue accent color (#4D8EF3), gradient backgrounds for sections, rounded corners

**Result Display:**

- Layout: Below form, centered
- Summary Cards: Multiple cards showing:
  - Total Gross Working Time (before breaks)
  - Total Net Working Time (after breaks)
  - Total Paid Time (working + paid breaks)
  - Total Break Time
  - Total Night Hours
  - Total Sunday Hours
  - Total Holiday Hours
  - Total Overtime
  - Average per Day/Work Day/Week
- Compliance Status: Visual indicator (OK/Warning/Error)
- Violations List: Detailed list of compliance violations with severity
- Daily Results Table: Paginated table showing day-by-day breakdown
- Export Buttons: PDF and CSV export buttons
- Email Gating: Results gated behind email collection (first time only)
- Styling: Green accent for compliant, yellow for warnings, red for errors, responsive cards

### UI/UX Flow

**Initial Load:**

- Page loads with hero section visible
- Simple Mode selected by default
- One day card shown with default values (08:00-16:30, 30min break)
- No results displayed initially
- Advanced sections collapsed

**Simple Mode Flow:**

1. User enters start/end times and break duration
2. Calculation runs automatically (real-time)
3. Result displays below form (Brutto/Netto hours)
4. User can add more days (clone or add new)
5. User can apply templates (Standard/Early/Late)
6. User can apply industry templates
7. Total hours update automatically
8. User can copy result to clipboard

**Advanced Mode Flow:**

1. User selects Advanced Mode tab
2. User enters period (start/end dates)
3. User selects Bundesland
4. User enters contract hours
5. Daily entries generated automatically for period
6. User optionally expands sections and fills additional data
7. User can apply bulk settings to all days
8. User can customize individual days (segments/breaks)
9. User clicks "Berechnen" button
10. Calculation runs
11. If first calculation: Email modal appears
12. Email collected and stored in localStorage
13. Results display below form
14. User can export results (PDF/CSV)
15. User can modify inputs and recalculate
16. Subsequent calculations: No email prompt (email remembered)

**Email Gating Flow:**

1. User calculates working time (Advanced Mode)
2. If email not collected: Email modal appears
3. User enters email
4. Email validated
5. Email sent to HubSpot API
6. Email stored in localStorage
7. Results unlocked
8. Subsequent calculations: No email prompt

## Technical Documentation

### File Structure

- **PHP File:** `v2/pages/tools_arbeitszeitrechner.php` (5,381 lines)
- **JavaScript:** `v2/js/tools-arbeitszeit-calculator.js` (3,331 lines, extracted)
- **CSS:** Uses shared `v2/css/tools-pages.css` + extensive inline styles

### Code Organization

**Alpine.js Component Structure:**

- Main component: `arbeitszeitCalculator()` function (line 12 in JS file)
- Registered with: `Alpine.data('arbeitszeitCalculator', arbeitszeitCalculator)`
- External JS file: `v2/js/tools-arbeitszeit-calculator.js`
- All logic in external JS file (extracted from PHP)

**State Management:**

- Alpine.js reactive state for all UI state
- Calculation cache for performance optimization
- localStorage for email collection and user preferences
- No server-side state

**Code Patterns:**

- Alpine.js reactive data properties
- Real-time calculation updates (Simple Mode)
- On-demand calculation (Advanced Mode)
- Progressive disclosure (collapsible sections)
- Email gating for results
- Export functionality (PDF/CSV)

### Calculation Modes

**Mode 1: Simple Mode (Schnell-Rechner)**

- **Visual Description:** Quick calculator with day cards
- **Purpose:** Fast calculation for single or multiple days
- **Input Fields:**
  - `simpleDays` (array of day objects): Each day has:
    - `start` (time input): Start time (HH:MM format)
    - `end` (time input): End time (HH:MM format)
    - `break` (time input): Break duration (HH:MM format)
  - Quick Templates: Standard (08:00-16:30), Early (06:00-14:00), Late (14:00-21:30)
  - Industry Templates: Pre-filled templates for different industries
- **Output Fields:**
  - `simpleResult` (display): Total net working hours
  - Gross Hours (display): Total gross working hours
  - Net Hours (display): Total net working hours (after breaks)
  - Break Hours (display): Total break hours
- **Formula:**

  ```
  For each day:
    Start Minutes = timeToMinutes(day.start)
    End Minutes = timeToMinutes(day.end)
    Break Minutes = timeToMinutes(day.break)

    Duration = End Minutes - Start Minutes
    If Duration < 0:
      Duration += 24 * 60  // Handle overnight shifts

    Gross Hours = Duration / 60
    Net Hours = max(0, (Duration - Break Minutes) / 60)

  Total Gross Hours = sum of all Gross Hours
  Total Net Hours = sum of all Net Hours
  Total Break Hours = sum of all Break Minutes / 60
  ```

- **Example Calculation:**

  ```
  Input: Day 1: 08:00-17:00, Break 00:30
  Calculation:
    Start Minutes = 8 * 60 = 480
    End Minutes = 17 * 60 = 1020
    Duration = 1020 - 480 = 540 minutes = 9 hours
    Break Minutes = 30
    Net Hours = (540 - 30) / 60 = 8.5 hours
  Result: Gross 9h, Net 8.5h
  ```

- **Validation:**
  - Time format: HH:MM (24-hour format)
  - Start time before end time (or overnight shift)
  - Break duration: 0-4 hours
  - Error messages: Display in validation area

**Mode 2: Advanced Mode (Detaillierter Rechner)**

- **Visual Description:** Comprehensive calculator with period selection and daily entries
- **Purpose:** Detailed calculation with compliance checks
- **Input Fields:**
  - `periodStart` (date input): Start date of period
  - `periodEnd` (date input): End date of period
  - `bundesland` (select): German state (16 states)
  - `considerHolidays` (toggle): Consider holidays in calculation
  - `weekModel` (radio): 5-day or 6-day week
  - `contractHoursWeek` (number input): Contractual weekly hours (0-80, step 0.5)
  - `contractHoursDay` (number input): Contractual daily hours (0-16, step 0.5)
  - `tarifabweichung` (toggle): Tariff deviation enabled
  - `tarifRefMonths` (number input): Reference months for tariff (1-12, default 6)
  - `industryNightWindow` (select): Night window (Standard 23:00-06:00 / Bakery 22:00-05:00)
  - `minorMode` (toggle): Minor mode (JArbSchG)
  - `rounding` (select): Rounding (Off/1min/5min/15min)
  - `bulkModeEnabled` (toggle): Enable bulk settings
  - `bulkSettings` (object): Bulk settings for all days:
    - `workStart` (time input): Work start time
    - `workEnd` (time input): Work end time
    - `breakStart` (time input): Break start time
    - `breakEnd` (time input): Break end time
    - `breakPaid` (toggle): Break is paid
    - `includeWeekends` (toggle): Include weekends
    - `includeHolidays` (toggle): Include holidays
  - `dailyEntries` (array): Array of day objects, each with:
    - `date` (string): Date (YYYY-MM-DD)
    - `dayOfWeek` (number): Day of week (0-6)
    - `isWeekend` (boolean): Is weekend
    - `isHoliday` (boolean): Is holiday
    - `segments` (array): Work segments (multiple allowed):
      - `start` (time input): Segment start time
      - `end` (time input): Segment end time
    - `breaks` (array): Break periods (multiple allowed):
      - `start` (time input): Break start time
      - `end` (time input): Break end time
      - `paid` (toggle): Break is paid
      - `durationOnly` (boolean): Duration-only break (no times)
      - `duration` (number): Duration in minutes (if durationOnly)
- **Output Fields:**
  - `results.summary.totalGrossWorkingTime` (display): Total gross working time (before breaks)
  - `results.summary.totalWorkingTime` (display): Total net working time (after breaks)
  - `results.summary.totalPaidTime` (display): Total paid time (working + paid breaks)
  - `results.summary.totalBreakTime` (display): Total break time
  - `results.summary.totalNightHours` (display): Total night hours (23:00-06:00 or 22:00-05:00)
  - `results.summary.totalSundayHours` (display): Total Sunday hours
  - `results.summary.totalHolidayHours` (display): Total holiday hours
  - `results.summary.totalOvertime` (display): Total overtime hours
  - `results.summary.averagePerDay` (display): Average hours per day
  - `results.summary.averagePerWorkDay` (display): Average hours per work day
  - `results.summary.averageWeeklyHours` (display): Average hours per week
  - `results.summary.violations` (display): Array of compliance violations
  - `results.summary.complianceStatus` (display): Compliance status (ok/warning/error)
  - `results.dailyResults` (table): Day-by-day breakdown
- **Formula:**

  ```
  // Generate daily entries for period
  // 1. Load holidays for all years in period (multi-year support)
  Years = get all years from periodStart to periodEnd
  For each year in Years:
    loadHolidays(year) // Load and cache holidays for this year

  // 2. Generate daily entries with reliable date iteration
  currentDate = periodStart
  While currentDate <= periodEnd:
    dateStr = formatDate(currentDate) // YYYY-MM-DD format
    Day Object = {
      date: dateStr,
      dayOfWeek: currentDate.getDay(),
      isWeekend: dayOfWeek === 0 || dayOfWeek === 6,
      isHoliday: isHoliday(dateStr), // Checks cached holidays for year
      segments: [],
      breaks: []
    }
    currentDate = currentDate + 1 day

  // Calculate working time for each day
  For each day in dailyEntries:
    // Calculate total working minutes from segments
    Total Working Minutes = 0
    For each segment:
      Start Minutes = timeToMinutes(segment.start)
      End Minutes = timeToMinutes(segment.end)
      Duration = End Minutes - Start Minutes
      If Duration < 0:
        Duration += 24 * 60  // Handle overnight shifts
      Total Working Minutes += Duration

    Gross Working Minutes = Total Working Minutes

    // Calculate unpaid break minutes (only those overlapping with work)
    Unpaid Break Minutes = calculateUnpaidBreakMinutes(day)

    // Calculate net working time
    Net Working Minutes = max(0, Gross Working Minutes - Unpaid Break Minutes)

    // Calculate paid time
    Paid Break Minutes = calculatePaidBreakMinutes(day)
    Paid Minutes = Net Working Minutes + Paid Break Minutes

    // Calculate night hours (23:00-06:00 or 22:00-05:00)
    Night Minutes = calculateNightMinutes(day, industryNightWindow)

    // Calculate Sunday/Holiday hours
    If day.isHoliday:
      Holiday Minutes = Net Working Minutes
      Sunday Minutes = 0
    Else if day.isWeekend:
      Sunday Minutes = Net Working Minutes
      Holiday Minutes = 0
    Else:
      Sunday Minutes = 0
      Holiday Minutes = 0

    // Apply rounding if enabled
    If rounding !== 'off':
      Net Working Minutes = round(Net Working Minutes, rounding)
      Gross Working Minutes = round(Gross Working Minutes, rounding)

  // Calculate summary
  Total Gross Working Time = sum of all Gross Working Minutes / 60
  Total Net Working Time = sum of all Net Working Minutes / 60
  Total Paid Time = sum of all Paid Minutes / 60
  Total Break Time = sum of all Break Minutes / 60
  Total Night Hours = sum of all Night Minutes / 60
  Total Sunday Hours = sum of all Sunday Minutes / 60
  Total Holiday Hours = sum of all Holiday Minutes / 60

  // Calculate averages
  Total Days = dailyEntries.length
  Work Days Count = count of days with work (excluding weekends/holidays unless work done)
  Average Per Day = Total Net Working Time / Total Days
  Average Per Work Day = Total Net Working Time / Work Days Count
  Average Weekly Hours = (Total Net Working Time / Total Days) * 7

  // Calculate overtime
  Period Weeks = Total Days / 7
  Total Contract Minutes = contractHoursWeek * 60 * Period Weeks
  Total Overtime = max(0, (Total Net Working Minutes - Total Contract Minutes) / 60)

  // Check compliance violations
  Violations = checkDayCompliance(day, dayResult) for each day
  + checkWeeklyCompliance(summary)
  ```

- **Example Calculation:**

  ```
  Input: Period 2026-01-01 to 2026-01-07, Berlin, 5-day week, 40h/week contract
  Day 1 (Monday): 08:00-17:00, Break 12:00-12:30 (unpaid)
  Calculation:
    Gross Minutes = (17*60) - (8*60) = 540 minutes = 9 hours
    Break Minutes = 30 minutes (overlaps with work)
    Net Minutes = 540 - 30 = 510 minutes = 8.5 hours
    Night Minutes = 0 (no night work)
    Sunday Minutes = 0 (not Sunday)
    Holiday Minutes = 0 (not holiday)

  Summary (7 days, 5 work days):
    Total Net Working Time = 8.5 * 5 = 42.5 hours
    Average Per Day = 42.5 / 7 = 6.07 hours
    Average Per Work Day = 42.5 / 5 = 8.5 hours
    Average Weekly Hours = (42.5 / 7) * 7 = 42.5 hours
    Total Overtime = max(0, 42.5 - 40) = 2.5 hours
  Result: Total 42.5h, Average 8.5h/work day, Overtime 2.5h
  ```

- **Validation:**
  - Period: Valid date range (start <= end)
  - Bundesland: Required (16 states)
  - Contract Hours: 0-80 hours/week, 0-16 hours/day
  - Time format: HH:MM (24-hour format)
  - Segments: No overlapping segments
  - Breaks: No overlapping breaks
  - Break overlap: Breaks must overlap with work segments
  - Error messages: Display in validation area

### Compliance Checks

**Daily Compliance Checks:**

- **Maximum Daily Work (§ 3 ArbZG):**

  - Regular: 8 hours (can be extended to 10 hours with compensation)
  - Minor Mode (JArbSchG): 8 hours maximum
  - Violation: Error if > 10 hours (regular) or > 8 hours (minor)

- **Break Requirements (§ 4 ArbZG / JArbSchG):**

  - Regular: 30 min if > 6h, 45 min if > 9h
  - Minor Mode: 30 min if > 4.5h, 60 min if > 6h
  - Violation: Error if break requirement not met

- **Continuous Work (§ 4 ArbZG):**

  - Regular: Max 6 hours without break
  - Minor Mode: Max 4.5 hours without break
  - Violation: Error if continuous work exceeds limit

- **Sunday/Holiday Work (§ 9-11 ArbZG):**
  - Warning: Sunday/holiday work requires replacement rest day within 2 weeks
  - Violation: Warning if > 2 hours on Sunday/holiday

**Weekly Compliance Checks:**

- **EU 48-Hour Weekly Average (RL 2003/88/EG Art. 6):**

  - Maximum: 48 hours/week average over reference period
  - Violation: Error if > 48h/week, Warning if > 47h/week

- **Minor Weekly Limit (JArbSchG):**
  - Maximum: 40 hours/week for minors
  - Violation: Error if > 40h/week (minor mode)

**Rest Period Checks:**

- **Daily Rest Period (§ 5 ArbZG):**

  - Minimum: 11 hours between shifts
  - Violation: Warning if < 11 hours

- **Weekly Rest Period (§ 11 ArbZG):**
  - Minimum: 24 hours continuous rest per week
  - Violation: Warning if not met

### Constants and Thresholds

**2026 Values:**

- **Maximum Daily Work:** 8 hours (regular), 10 hours (extended), 8 hours (minor)
- **Maximum Weekly Work:** 48 hours/week average (EU directive), 40 hours/week (minor)
- **Break Thresholds:**
  - Regular: 30 min if > 6h, 45 min if > 9h
  - Minor: 30 min if > 4.5h, 60 min if > 6h
- **Rest Periods:**
  - Between shifts: 11 hours minimum
  - Weekly rest: 24 hours minimum
- **Night Window:**
  - Standard: 23:00-06:00
  - Bakery: 22:00-05:00
- **Holidays:** ✅ Uses OpenHolidays API via shared HolidayService (updated 2026-01-07)
  - Multi-year support: Automatically loads holidays for all years in date range
  - Regional support: All 16 German states supported
  - Fallback mechanism: Uses local data if API unavailable
- **Rounding Options:** Off, 1 minute, 5 minutes, 15 minutes
- **Tariff Reference Period:** 6 months (default)

**Previous Values (for reference):**

- Holidays 2026: Hardcoded in `holidays2026` object (updated to 2026)
- EU Directive Reference: "RL 2003/88/EG Art. 6 (2026)" (line 1098, 1106) - needs 2026 update

### Validation Rules

- **Period:** Start date <= End date, valid date format
- **Bundesland:** Required (16 German states)
- **Contract Hours Week:** min=0, max=80, step=0.5
- **Contract Hours Day:** min=0, max=16, step=0.5
- **Time Format:** HH:MM (24-hour format, 00:00-23:59)
- **Break Duration:** min=0, max=4 hours
- **Segments:** No overlapping segments per day
- **Breaks:** No overlapping breaks per day
- **Break Overlap:** Breaks must overlap with work segments

### Edge Cases Handled

- Overnight shifts (end time < start time)
- Multiple work segments per day
- Multiple breaks per day
- Paid vs unpaid breaks
- Duration-only breaks (no time range)
- Break overlap with work segments
- Weekend work
- Holiday work
- Night work (different windows)
- Part-time employment
- Tariff deviations
- Minor mode (JArbSchG)
- Rounding (1min/5min/15min)
- Long periods (multiple weeks/months)
- Compliance violations (errors/warnings)

### Dependencies

- **External Libraries:**
  - jsPDF + html2canvas (PDF export, lazy-loaded)
- **APIs:** HubSpot Forms API v3 (email collection via `/v2/api/collect-lead.php`)
- **Alpine.js:** Used for reactive UI (version from base includes)
- **localStorage:** Email collection and user preferences
- **External JS File:** `v2/js/tools-arbeitszeit-calculator.js` (3,331 lines)

## Functions & Methods

### Main Component Function

**Function:** `arbeitszeitCalculator()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:12`
- **Purpose:** Main Alpine.js component for Arbeitszeit calculator
- **Returns:** Alpine.js component object
- **Dependencies:** Alpine.js framework, jsPDF (lazy-loaded), html2canvas (lazy-loaded)
- **Side Effects:** Manages DOM state, triggers calculations, manages email collection, manages exports

### Calculation Functions

**Function:** `calculateSimple()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2182`
- **Purpose:** Calculate simple mode total
- **Returns:** void (sets component state)
- **Dependencies:** `calculateSimpleTotal()`, `calculateSimpleTotalGross()`
- **Side Effects:** Updates simpleResult

**Function:** `calculateSimpleTotal()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2297`
- **Purpose:** Calculate total net working hours from all simple days
- **Returns:** Number (total hours)
- **Dependencies:** `calculateSimpleDayHours()`

**Function:** `calculateSimpleDayHours(day)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2365`
- **Purpose:** Calculate net working hours for a single simple day
- **Formula:** `(End Minutes - Start Minutes - Break Minutes) / 60`

**Function:** `calculateWorkingTime()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:967`
- **Purpose:** Main advanced mode calculation function
- **Returns:** void (sets component state)
- **Dependencies:** `validateAllSettings()`, `calculateDayWorkingTime()`, `checkDayCompliance()`
- **Side Effects:** Updates results, triggers email modal if needed

**Function:** `calculateDayWorkingTime(day)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:1142`
- **Purpose:** Calculate working time for a single day
- **Returns:** Object (day result with violations)
- **Dependencies:** `calculateTotalWorkingMinutes()`, `calculateUnpaidBreakMinutes()`, `calculatePaidBreakMinutes()`, `calculateNightMinutes()`, `checkDayCompliance()`

**Function:** `calculateTotalWorkingMinutes(day)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:1300+` (approximate)
- **Purpose:** Calculate total working minutes from all segments
- **Returns:** Number (total minutes)
- **Formula:** Sum of all segment durations

**Function:** `calculateUnpaidBreakMinutes(day)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:1299+` (approximate)
- **Purpose:** Calculate unpaid break minutes overlapping with work
- **Returns:** Number (break minutes)
- **Formula:** Sum of unpaid break overlaps with work segments

**Function:** `calculatePaidBreakMinutes(day)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:1300+` (approximate)
- **Purpose:** Calculate paid break minutes overlapping with work
- **Returns:** Number (break minutes)
- **Formula:** Sum of paid break overlaps with work segments

**Function:** `calculateTotalBreakMinutes(day)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:1962`
- **Purpose:** Calculate total break minutes (all breaks, overlapping with work)
- **Returns:** Number (break minutes)
- **Formula:** Sum of all break overlaps with work segments (merged ranges)

**Function:** `calculateNightMinutes(day)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2100+` (approximate)
- **Purpose:** Calculate night hours (23:00-06:00 or 22:00-05:00)
- **Returns:** Number (night minutes)
- **Formula:** Sum of work minutes within night window

**Function:** `calculateRestPeriod(day)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2052`
- **Purpose:** Calculate rest period from end of work to midnight
- **Returns:** Number (rest minutes)
- **Formula:** `24 * 60 - lastSegmentEnd`

**Function:** `calculateMaxContinuousWork(day)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2064`
- **Purpose:** Calculate maximum continuous work without break
- **Returns:** Number (continuous minutes)
- **Formula:** Longest period between unpaid breaks

### Compliance Functions

**Function:** `checkDayCompliance(day, dayResult)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:1816`
- **Purpose:** Check compliance violations for a single day
- **Returns:** Array (violations)
- **Checks:** Daily limits, break requirements, continuous work, Sunday/holiday work

**Function:** `validateAllSettings()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:923`
- **Purpose:** Comprehensive validation for all settings
- **Returns:** Object (errors, warnings)
- **Dependencies:** `validateBulkSettings()`, `validateDaySettings()`, `validateSimpleDay()`

**Function:** `validateDaySettings(day, dayIndex)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:736`
- **Purpose:** Validate individual day settings
- **Returns:** Object (errors, warnings)
- **Checks:** Segments overlap, breaks overlap, break-work overlap, total working time

**Function:** `validateSimpleDay(day, dayIndex)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:884`
- **Purpose:** Validate simple mode day
- **Returns:** Object (errors, warnings)
- **Checks:** Time range validity, break duration

### Utility Functions

**Function:** `timeToMinutes(timeStr)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:1241`
- **Purpose:** Convert time string (HH:MM) to minutes
- **Returns:** Number (minutes)

**Function:** `minutesToTime(minutes)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:1293`
- **Purpose:** Convert minutes to time string (HH:MM)
- **Returns:** String (HH:MM)

**Function:** `validateTimeRange(startTime, endTime, allowOvernight)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:1249`
- **Purpose:** Validate time range
- **Returns:** Object (valid, duration/error)

**Function:** `validateTimeInput(input)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:1284`
- **Purpose:** Validate time input format
- **Returns:** Object (valid, error)

**Function:** `formatTime(hours)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2400+` (approximate)
- **Purpose:** Format hours as "Xh Ymin"
- **Returns:** String (formatted time)

**Function:** `applyRounding(minutes)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2400+` (approximate)
- **Purpose:** Apply rounding to minutes
- **Returns:** Number (rounded minutes)

**Function:** `loadHolidays(year = null)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:389`
- **Purpose:** Load holidays for a specific year and bundesland
- **Parameters:** `year` (optional, defaults to `this.year`)
- **Returns:** Promise<void>
- **Dependencies:** `holidayService`, `getRegionCode()`
- **Caching:** Uses `holidaysCache` with key `${bundesland}-${year}`
- **Error Handling:** Falls back to empty array on error

**Function:** `loadHolidaysForPeriod(startDate, endDate)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:417`
- **Purpose:** Load holidays for all years in a date range
- **Parameters:** `startDate`, `endDate` (Date objects or date strings)
- **Returns:** Promise<void>
- **Multi-Year Support:** Automatically detects all years in range and loads holidays for each
- **Dependencies:** `loadHolidays()`

**Function:** `isHoliday(dateStr)`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:420`
- **Purpose:** Check if date is a holiday (checks all cached years)
- **Parameters:** `dateStr` (YYYY-MM-DD format)
- **Returns:** Boolean
- **Dependencies:** `holidaysCache`, `loadHolidays()`
- **Multi-Year Support:** Extracts year from date string and checks appropriate cache

**Function:** `generateDailyEntries()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:325`
- **Purpose:** Generate daily entries for selected period (now async)
- **Returns:** Promise<void>
- **Dependencies:** `loadHolidaysForPeriod()`, `isHoliday()`, `formatDate()`
- **Multi-Year Support:** Loads holidays for all years in period before generating entries
- **Date Iteration:** Uses reliable while loop to prevent timezone issues

**Function:** `applyBulkSettings()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:580`
- **Purpose:** Apply bulk settings to all days
- **Returns:** void (updates dailyEntries)

### Export Functions

**Function:** `exportPDF()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2527`
- **Purpose:** Export results as PDF
- **Dependencies:** jsPDF, html2canvas libraries
- **Side Effects:** Downloads PDF file

**Function:** `exportCSV()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2643`
- **Purpose:** Export results as CSV
- **Dependencies:** None (native JavaScript)
- **Side Effects:** Downloads CSV file

**Function:** `generatePDFHTML()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2668`
- **Purpose:** Generate PDF HTML content
- **Returns:** String (HTML)
- **Note:** ✅ Mentions "Deutsche Arbeitszeitgesetze 2026" (line 2683) - needs 2026 update

**Function:** `generateCSVContent()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2800+` (approximate)
- **Purpose:** Generate CSV content
- **Returns:** String (CSV)

### Email Collection Functions

**Function:** `submitEmail()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2900+` (approximate)
- **Purpose:** Submit email to HubSpot API
- **Dependencies:** HubSpot Forms API v3, UTM tracking
- **Side Effects:** Stores email in localStorage, unlocks results

**Function:** `checkEmailStatus()`

- **Location:** `v2/js/tools-arbeitszeit-calculator.js:2950+` (approximate)
- **Purpose:** Check if email was already collected
- **Dependencies:** localStorage
- **Side Effects:** Sets emailCollected flag if email found

## Formulas & Calculations

### Primary Formulas

**Simple Mode:**

```
For each day:
  Start Minutes = timeToMinutes(day.start)
  End Minutes = timeToMinutes(day.end)
  Break Minutes = timeToMinutes(day.break)

  Duration = End Minutes - Start Minutes
  If Duration < 0:
    Duration += 24 * 60  // Handle overnight shifts

  Gross Hours = Duration / 60
  Net Hours = max(0, (Duration - Break Minutes) / 60)

Total Gross Hours = sum of all Gross Hours
Total Net Hours = sum of all Net Hours
Total Break Hours = sum of all Break Minutes / 60
```

**Advanced Mode:**

```
// Generate daily entries
For each day from periodStart to periodEnd:
  Day = {
    date: date,
    dayOfWeek: day.getDay(),
    isWeekend: dayOfWeek === 0 || dayOfWeek === 6,
    isHoliday: isHoliday(date, bundesland),
    segments: [],
    breaks: []
  }

// Calculate working time for each day
For each day:
  // Calculate gross working minutes from segments
  Gross Working Minutes = 0
  For each segment:
    Start = timeToMinutes(segment.start)
    End = timeToMinutes(segment.end)
    Duration = End - Start
    If Duration < 0:
      Duration += 24 * 60  // Handle overnight
    Gross Working Minutes += Duration

  // Calculate unpaid break minutes (overlapping with work)
  Unpaid Break Minutes = calculateUnpaidBreakMinutes(day)

  // Calculate net working minutes
  Net Working Minutes = max(0, Gross Working Minutes - Unpaid Break Minutes)

  // Calculate paid time
  Paid Break Minutes = calculatePaidBreakMinutes(day)
  Paid Minutes = Net Working Minutes + Paid Break Minutes

  // Calculate night hours
  Night Minutes = calculateNightMinutes(day, industryNightWindow)

  // Calculate Sunday/Holiday hours
  If day.isHoliday:
    Holiday Minutes = Net Working Minutes
    Sunday Minutes = 0
  Else if day.isWeekend:
    Sunday Minutes = Net Working Minutes
    Holiday Minutes = 0
  Else:
    Sunday Minutes = 0
    Holiday Minutes = 0

  // Apply rounding if enabled
  If rounding !== 'off':
    Net Working Minutes = round(Net Working Minutes, rounding)
    Gross Working Minutes = round(Gross Working Minutes, rounding)

// Calculate summary
Total Gross Working Time = sum(Gross Working Minutes) / 60
Total Net Working Time = sum(Net Working Minutes) / 60
Total Paid Time = sum(Paid Minutes) / 60
Total Break Time = sum(Break Minutes) / 60
Total Night Hours = sum(Night Minutes) / 60
Total Sunday Hours = sum(Sunday Minutes) / 60
Total Holiday Hours = sum(Holiday Minutes) / 60

// Calculate averages
Total Days = dailyEntries.length
Work Days Count = count of days with work
Average Per Day = Total Net Working Time / Total Days
Average Per Work Day = Total Net Working Time / Work Days Count
Average Weekly Hours = (Total Net Working Time / Total Days) * 7

// Calculate overtime
Period Weeks = Total Days / 7
Total Contract Minutes = contractHoursWeek * 60 * Period Weeks
Total Overtime = max(0, (Total Net Working Minutes - Total Contract Minutes) / 60)
```

**Break Overlap Calculation:**

```
For each break:
  Break Start = timeToMinutes(break.start)
  Break End = timeToMinutes(break.end)
  If Break End < Break Start:
    Break End += 24 * 60  // Handle overnight breaks

  For each work segment:
    Segment Start = timeToMinutes(segment.start)
    Segment End = timeToMinutes(segment.end)
    If Segment End < Segment Start:
      Segment End += 24 * 60  // Handle overnight segments

    Overlap Start = max(Break Start, Segment Start)
    Overlap End = min(Break End, Segment End)

    If Overlap End > Overlap Start:
      Overlap Minutes = Overlap End - Overlap Start
      Add to total break minutes

Total Break Minutes = sum of all overlaps (merged ranges)
```

**Night Hours Calculation:**

```
Night Window = industryNightWindow === 'bakery' ? 22:00-05:00 : 23:00-06:00
Night Start = timeToMinutes(nightWindow.start)
Night End = timeToMinutes(nightWindow.end)

For each work segment:
  Segment Start = timeToMinutes(segment.start)
  Segment End = timeToMinutes(segment.end)
  If Segment End < Segment Start:
    Segment End += 24 * 60  // Handle overnight segments

  // Calculate overlap with night window
  Overlap Start = max(Segment Start, Night Start)
  Overlap End = min(Segment End, Night End)

  If Overlap End > Overlap Start:
    Night Minutes += Overlap End - Overlap Start

Total Night Minutes = sum of all overlaps
```

### Legal Basis

- **Arbeitszeitgesetz (ArbZG):** German Working Time Act
  - § 3: Maximum daily working time (8h regular, 10h extended)
  - § 4: Break requirements (30min if >6h, 45min if >9h)
  - § 5: Daily rest period (11 hours minimum)
  - § 9-11: Sunday and holiday work regulations
- **Jugendarbeitsschutzgesetz (JArbSchG):** Youth Employment Protection Act
  - Maximum daily work: 8 hours
  - Maximum weekly work: 40 hours
  - Break requirements: 30min if >4.5h, 60min if >6h
  - Continuous work: Max 4.5 hours without break
- **EU Working Time Directive (RL 2003/88/EG):**
  - Art. 6: Maximum 48 hours/week average over reference period
- **Feiertagsgesetze:** Holiday regulations by state (Bundesland)

### Step-by-Step Calculation Examples

**Example 1: Simple Mode**

- Input: Day 1: 08:00-17:00, Break 00:30
- Step 1: Calculate duration: 17:00 - 08:00 = 9 hours
- Step 2: Subtract break: 9h - 0.5h = 8.5 hours
- Result: Gross 9h, Net 8.5h

**Example 2: Advanced Mode - Single Day**

- Input: 2026-01-01 (Monday), 08:00-17:00, Break 12:00-12:30 (unpaid), Berlin, 40h/week contract
- Step 1: Calculate gross: 17:00 - 08:00 = 9 hours
- Step 2: Calculate break overlap: 30 minutes (overlaps with work)
- Step 3: Calculate net: 9h - 0.5h = 8.5 hours
- Step 4: Check break requirement: 8.5h > 6h → 30min required ✓
- Step 5: Check daily limit: 8.5h < 10h ✓
- Step 6: Calculate overtime: 8.5h - 8h = 0.5 hours
- Result: Net 8.5h, Overtime 0.5h, Compliance OK

**Example 3: Advanced Mode - Week with Compliance Violation**

- Input: Period 2026-01-01 to 2026-01-07, 5 days × 10h/day, Berlin, 40h/week contract
- Step 1: Calculate total: 5 × 10h = 50 hours
- Step 2: Calculate average: 50h / 7 days × 7 = 50h/week
- Step 3: Check EU limit: 50h > 48h → Violation
- Step 4: Check daily limit: 10h > 8h → Warning (extended hours)
- Step 5: Check break requirement: 10h > 9h → 45min required
- Result: Total 50h, Average 50h/week, Violations: EU 48h limit exceeded, Extended daily hours

## Export Functionality

### Export Types

**PDF Export (.pdf):**

- Format: PDF format (A4)
- Content:
  - Ordio branding header
  - Period information
  - Summary section (gross/net/paid time, overtime, averages)
  - Special hours section (night/Sunday/holiday)
  - EU compliance check
  - Daily results table (all days)
  - Violations list (if any)
- Filename: `Ordio_Arbeitszeitbericht_[StartDate]_[EndDate].pdf`
- Libraries: jsPDF, html2canvas
- Note: ✅ Mentions "Deutsche Arbeitszeitgesetze 2026" (line 2683) - needs 2026 update

**CSV Export (.csv):**

- Format: CSV format (comma-separated)
- Content:
  - Period information
  - Summary data
  - Daily breakdown (all days with details)
- Filename: `Ordio_Arbeitszeit_[StartDate]_[EndDate].csv`
- Library: Native JavaScript

### Email Gating

- **First Export:** Email modal appears (Advanced Mode only)
- **Email Collection:** Email stored in localStorage
- **Subsequent Exports:** No email prompt (email remembered)
- **Email Validation:** Basic email format validation
- **HubSpot Integration:** Email sent to HubSpot Forms API v3

### Sharing

- **Simple Mode:** Copy result to clipboard
- **Advanced Mode:** Export PDF/CSV for sharing

## Results & Insights

### Result Display

**Simple Mode Results:**

- Gross Hours: Total gross working hours
- Net Hours: Total net working hours (after breaks)
- Break Hours: Total break hours
- Copy Button: Copy result to clipboard

**Advanced Mode Results:**

**Summary Cards:**

- Total Gross Working Time: Large number display (before breaks)
- Total Net Working Time: Large number display (after breaks)
- Total Paid Time: Number display (working + paid breaks)
- Total Break Time: Number display
- Total Night Hours: Number display
- Total Sunday Hours: Number display
- Total Holiday Hours: Number display
- Total Overtime: Number display
- Average Per Day: Number display
- Average Per Work Day: Number display
- Average Weekly Hours: Number display

**Compliance Status:**

- Visual Indicator: Green (OK), Yellow (Warning), Red (Error)
- Status Text: "Rechtssicher" / "Warnungen" / "Fehler"

**Violations List:**

- Grouped by severity (Errors, Warnings)
- Each violation shows: Code, Message, Paragraph reference, Affected days count
- Click to expand details

**Daily Results Table:**

- Columns: Date, Day, Gross Time, Net Time, Paid Time, Break Time, Night Hours, Sunday Hours, Holiday Hours, Overtime, Violations
- Pagination: Configurable items per page
- Sortable: By date (ascending)

**Email Gating:**

- Results gated behind email collection (first time only)
- Placeholder values shown until email collected
- Email modal appears on first calculation
- Email stored in localStorage for session persistence

### Smart Features

- **Auto-calculation:** Real-time in Simple Mode, on-demand in Advanced Mode
- **Progressive Disclosure:** Collapsible sections (advanced settings, daily entries)
- **Bulk Settings:** Apply same times to all days
- **Industry Templates:** Pre-filled templates for common industries
- **Quick Templates:** Standard/Early/Late shift templates
- **Compliance Checks:** Real-time compliance validation
- **Violation Tracking:** Detailed violation list with affected days
- **Export Functionality:** PDF and CSV export
- **Email Gating:** Email collection for lead generation
- **User Preferences:** Save settings in localStorage

## Browser Testing Results

### Desktop Browsers

**Chrome (Latest):**

- Status: ✅ Fully functional
- Issues: None
- Notes: All features working correctly, PDF export works

**Firefox (Latest):**

- Status: ✅ Fully functional
- Issues: None
- Notes: All features working correctly

**Safari (Latest):**

- Status: ✅ Fully functional
- Issues: None
- Notes: All features working correctly

**Edge (Latest):**

- Status: ✅ Fully functional
- Issues: None
- Notes: All features working correctly

### Mobile Testing

**iOS Safari:**

- Status: ✅ Functional
- Device: iPhone (tested)
- Issues: Minor UI adjustments on small screens
- Notes: Day cards adapt to mobile, table scrolls horizontally

**Android Chrome:**

- Status: ✅ Functional
- Device: Android (tested)
- Issues: None
- Notes: Touch interactions work correctly

**Mobile UI Differences:**

- Simple Mode: Day cards stack vertically on mobile
- Advanced Mode: Form becomes single column on mobile
- Daily entries: Cards stack vertically
- Table: Scrolls horizontally on mobile
- Export buttons: Stack vertically on mobile

### Responsive Design

**Desktop (>1024px):**

- Layout: Centered single-column
- Form Grid: Multi-column grids for inputs
- Day Cards: Grid layout (2-3 columns)
- Table: Full width with pagination

**Tablet (768px-1024px):**

- Layout: Centered single-column
- Form Grid: 2-column grids
- Day Cards: 2-column grid
- Table: Full width with pagination

**Mobile (<768px):**

- Layout: Full-width single-column
- Form Grid: Single column
- Day Cards: Single column
- Table: Horizontal scroll

**Breakpoints:**

- Mobile: < 768px
- Tablet: 768px - 1024px
- Desktop: > 1024px

### Accessibility

**Keyboard Navigation:**

- Tab navigation works through all form fields
- Enter to calculate (Advanced Mode)
- Focus indicators visible

**Screen Reader:**

- Form labels properly associated
- Results announced after calculation
- Table has proper roles
- Violations announced

**ARIA Labels:**

- Input fields have labels
- Buttons have descriptive text
- Table has proper roles
- Collapsible sections have proper ARIA attributes

## Code Analysis

### Key Functions Location

- Main component: `v2/js/tools-arbeitszeit-calculator.js:12`
- Simple calculation: `v2/js/tools-arbeitszeit-calculator.js:2182`
- Advanced calculation: `v2/js/tools-arbeitszeit-calculator.js:967`
- Compliance checks: `v2/js/tools-arbeitszeit-calculator.js:1816`
- Export functions: `v2/js/tools-arbeitszeit-calculator.js:2527+`
- Email collection: `v2/js/tools-arbeitszeit-calculator.js:2900+` (approximate)

### Constants Location

- Holidays data: Uses shared `HolidayService` (`v2/js/shared/holiday-service.js`)
  - API: OpenHolidays API (https://openholidaysapi.org)
  - Fallback: Local data in `v2/data/holidays-fallback.json`
  - Caching: 24-hour cache per bundesland-year combination
  - Multi-year: Automatically loads holidays for all years in date range
- Industry templates: `industryTemplates` object (line 84)
- Compliance thresholds: Hardcoded in compliance functions
- Night windows: Hardcoded in `calculateNightMinutes()` function

### Calculation Logic Flow

1. **User Input:**

   - Simple Mode: User enters times for each day
   - Advanced Mode: User selects period, enters contract hours, fills daily entries

2. **Validation:**

   - Inputs validated (time format, ranges, overlaps)
   - Error messages displayed if invalid

3. **Calculation:**

   - Simple Mode: Calculate each day, sum totals
   - Advanced Mode:
     - Generate daily entries for period
     - Calculate each day (segments, breaks, night hours)
     - Check compliance violations
     - Calculate summary (totals, averages, overtime)
     - Check weekly compliance

4. **Display:**

   - Results updated in component state
   - UI updates automatically (Alpine.js reactivity)
   - Email modal appears if first calculation (Advanced Mode)
   - Results displayed after email collection

5. **Export:**
   - PDF: Generate HTML, convert to canvas, create PDF
   - CSV: Generate CSV string, download file

## Content Documentation

### Hero Section

- **H1:** "Arbeitszeitrechner 2026: Kostenlos Arbeitszeit berechnen" (✅ Already "2026")
- **Description:** "Kostenloser Arbeitszeitrechner 2026: Arbeitszeit, Pausen & Überstunden nach ArbZG berechnen. Rechtssicher, minutengenau & ohne Anmeldung. Jetzt testen!"

### Educational Content Sections

1. **Arbeitszeitgesetz Basics**

   - Maximum daily/weekly hours explained
   - Break requirements explained
   - Rest periods explained

2. **Compliance Checks**

   - Daily limits
   - Weekly limits
   - Break requirements
   - Rest periods

3. **Calculation Details**

   - Gross vs net working time
   - Paid vs unpaid breaks
   - Night hours calculation
   - Overtime calculation

### FAQ Section

- **Total FAQs:** ~15 FAQs
- **FAQ Topics:**
  - Calculation: 5 FAQs
  - Compliance: 5 FAQs
  - Breaks: 3 FAQs
  - Overtime: 2 FAQs

**Sample FAQs:**

1. "Wie berechne ich meine Arbeitszeit richtig?"
2. "Welche Pausen sind gesetzlich vorgeschrieben?"
3. "Wie viele Überstunden sind erlaubt?"
4. "Was gilt für Nachtarbeit?"

### Meta Tags

- **Title:** "Arbeitszeitrechner 2026: Kostenlos Arbeitszeit berechnen - Ordio" (✅ Already "2026")
- **Description:** "Kostenloser Arbeitszeitrechner 2026: Arbeitszeit, Pausen & Überstunden nach ArbZG berechnen. Rechtssicher, minutengenau & ohne Anmeldung. Jetzt testen!" (✅ Already "2026")

### Schema Markup

- **WebApplication schema:** Yes
- **FAQPage schema:** Yes
- **HowTo schema:** Yes
- **BreadcrumbList schema:** Yes

### Internal Linking

- Links to: Related time tracking tools
- Link count: 2-3 internal links

## 2026 Update Requirements

### Immediate Updates (Required for Jan 1, 2026)

**Constants/Values:**

- ✅ **Holidays Data:** Updated `holidays2025` to `holidays2026` - ✅ COMPLETE
- ✅ **EU Directive Reference:** Update "RL 2003/88/EG Art. 6 (2026)" to "2026" (line 1098, 1106)
- ✅ **PDF Header:** Update "Deutsche Arbeitszeitgesetze 2026" to "2026" (line 2683)
- ✅ Compliance thresholds: Typically stable (verify unchanged)

**Content:**

- ✅ Meta tags: Already "2026"
- ✅ FAQs: Review and update year references (~15 FAQs)
- ✅ Educational sections: Review for "2025" → "2026" updates

**Priority:** 🟡 MEDIUM (Holidays update needed, year references in code)

### Throughout 2026 Updates

**Scheduled Updates:**

- **Holidays:** Uses OpenHolidays API (automatic updates)
  - Fallback data: Update `v2/data/holidays-fallback.json` annually
  - Regional holidays: Check for new regional holidays (e.g., Berlin's Internationaler Frauentag)
  - Multi-year support: Automatically handles holidays across year boundaries
- **Compliance Thresholds:** Monitor for changes (typically stable)

### Monitoring Requirements

- **Bundesländer:** Check for holiday updates (annual, varies by state)
- **Bundesministerium für Arbeit und Soziales:** Check for ArbZG changes (rare)
- **EU:** Check for Working Time Directive updates (rare)
- **Frequency:** Annually (January) or when laws change
- **Source:** Official holiday calendars, BMAS announcements

## Testing

### Test Cases

**Simple Mode:**

- Test 1: Single day 08:00-17:00, Break 00:30 → Expected: Gross 9h, Net 8.5h
- Test 2: Multiple days → Expected: Correct sum
- Test 3: Overnight shift → Expected: Correct calculation
- Test 4: Templates → Expected: Correct pre-fill

**Advanced Mode:**

- Test 1: Week with 5 days × 8h → Expected: Total 40h, Average 8h/work day
- Test 2: With breaks → Expected: Correct net calculation
- Test 3: With night hours → Expected: Correct night hours
- Test 4: With compliance violations → Expected: Correct violations list
- Test 5: With overtime → Expected: Correct overtime calculation
- Test 6: Export PDF → Expected: PDF generated correctly
- Test 7: Export CSV → Expected: CSV generated correctly

**Edge Cases:**

- Edge case 1: Overnight shifts → Expected: Correct calculation
- Edge case 2: Multiple segments → Expected: Correct sum
- Edge case 3: Multiple breaks → Expected: Correct overlap calculation
- Edge case 4: Break outside work → Expected: Warning
- Edge case 5: Compliance violations → Expected: Correct violation detection
- Edge case 6: Long periods → Expected: Correct calculation

### Browser Testing

- Chrome: ✅ Tested, working
- Firefox: ✅ Tested, working
- Safari: ✅ Tested, working
- Mobile: ✅ Tested, working

### Export Testing

- PDF: ✅ Functional (jsPDF + html2canvas)
- CSV: ✅ Functional (native JavaScript)

## Content Structure

### Hero Section

- **H1 Title:** To be documented
- **Meta Description:** Kostenloser Arbeitszeitrechner 2026: Arbeitszeit, Pausen & Überstunden nach ArbZG berechnen. Rechtss

### FAQs

- **Total FAQs:** 8
- Q: Wie nutze ich den Arbeitszeitrechner richtig (online & kostenlos)?...
- Q: Was zählt als Arbeitszeit – und wie sind Pausen geregelt?...
- Q: Welche Grenzen gelten nach dem Arbeitszeitgesetz (ArbZG)?...

## Test Coverage

### Automated Testing

The Arbeitszeitrechner includes comprehensive automated test coverage via `v2/scripts/dev-helpers/test-arbeitszeit-calculations.js`.

**Test Suite Overview:**
- **Total Test Cases:** 47
- **Coverage Areas:**
  - Simple Mode Calculations (7 tests)
  - Advanced Mode Segment Calculations (6 tests)
  - Break Calculation Overlaps (4 tests)
  - Compliance Checks - Daily Limits (6 tests)
  - Compliance Checks - Break Requirements (9 tests)
  - Compliance Checks - Continuous Work (4 tests)
  - Edge Cases (7 tests)
  - Weekly Limit Validations (4 tests)

**Running Tests:**
```bash
node v2/scripts/dev-helpers/test-arbeitszeit-calculations.js
```

**Test Results:** All 47 tests pass (100% pass rate)

**Key Test Scenarios:**
- Standard working time calculations (8:00-16:30 with breaks)
- Overnight shift handling
- Multiple overlapping segments
- Break overlap calculations
- Daily limit violations (8h/10h for regular, 8h for minors)
- Break requirement violations (30min/45min for regular, 30min/60min for minors)
- Continuous work violations (6h for regular, 4.5h for minors)
- Tolerance edge cases
- Weekly limit validations (48h EU, 40h minors)

**Test Constants Verified:**
- ArbZG daily limits: 8h (regular normal), 10h (regular extended), 8h (minors)
- Break requirements: 30min (>6h), 45min (>9h) for regular; 30min (>4.5h), 60min (>6h) for minors
- Continuous work limits: 6h (regular), 4.5h (minors)
- Weekly limits: 48h (EU average), 40h (minors)
- Tolerance values: 30min (daily), 5min (breaks), 15min (continuous)

## Maintenance Notes

### Known Issues

- Holidays data shows 2026 (needs 2026 update)
- PDF header updated to "2026"
- EU directive reference updated to "2026"
- External JS file makes updates easier (good structure)

### Future Improvements

- Add more industry templates
- Add comparison mode (multiple scenarios)
- Add historical data visualization
- Improve compliance violation explanations
- Add more export formats (Excel)

### Related Tools

**Complementary Tools:**

- **[Stundenlohnrechner](stundenlohnrechner-documentation.md)** - Calculate hourly wage from monthly salary
  - Use together when: Need both working hours and hourly rate calculations
  - Example workflow: Calculate working hours → Calculate hourly rate → Total compensation

- **[Zuschlagsrechner](zuschlagsrechner-documentation.md)** - Calculate shift surcharges (night, Sunday, holiday)
  - Use together when: Need to calculate surcharges for shift work
  - Example workflow: Calculate working hours → Calculate surcharges → Total compensation

- **[Urlaubsanspruch-Rechner](urlaubsanspruch-rechner-documentation.md)** - Calculate vacation entitlement
  - Use together when: Need to calculate vacation based on working hours
  - Example workflow: Calculate working hours → Calculate vacation entitlement → Plan vacation

- **[Arbeitstage-Rechner](arbeitstage-rechner-documentation.md)** - Calculate working days in a period
  - Use together when: Need both working days and working hours calculations
  - Example workflow: Calculate working days → Calculate working hours → Total time tracking

**Sequential Tools:**

- **[Brutto-Netto-Rechner](brutto-netto-rechner-documentation.md)** - Calculate net salary
  - Use after: Calculating total working hours
  - Use before: Final salary calculation

- **[ROI-Rechner Schichtplanung](roi-rechner-schichtplanung-documentation.md)** - Calculate shift planning ROI
  - Use after: Calculating working hours and compliance
  - Use before: Optimizing shift schedules for cost efficiency

- **[Kostenrechner](kostenrechner-documentation.md)** - Calculate labor costs
  - Use after: Calculating working hours
  - Use before: Overall cost planning

## References

### Official Sources

- **Arbeitszeitgesetz (ArbZG):** German Working Time Act
- **Jugendarbeitsschutzgesetz (JArbSchG):** Youth Employment Protection Act
- **EU Working Time Directive (RL 2003/88/EG):** European regulations
- **Feiertagsgesetze:** Holiday regulations by state

### Documentation Files

- `BROWSER_TESTING_FRAMEWORK.md`: Browser testing guidelines
- `CODE_ANALYSIS_FRAMEWORK.md`: Code analysis guidelines
- `TOOL_DOCUMENTATION_TEMPLATE.md`: Documentation template
