# AGENTS.md — HB Jewish Calendar

Welcome to **HB Jewish Calendar**. This document provides essential context, architectural principles, code organization, and development guidelines for AI agents and developers working on this codebase.

---

## 1. Project Overview

- **Plugin Name:** HB Jewish Calendar (`hb-jewish-calendar`)
- **Author:** HBCode
- **WordPress Requirements:** WordPress 6.5+ (tested up to 6.9), PHP 7.4+
- **Text Domain:** `hb-jewish-calendar` (i18n domain path: `/languages`)
- **License:** GPL v3 or later

### Core Functionality
The plugin provides Hebrew calendar tools for WordPress sites:
1. **Interactive Monthly Calendar:** Client-rendered monthly Hebrew calendar with Gregorian cross-reference, navigation, and holiday markers.
2. **Current Date & Weekday:** Outputs today's Hebrew date (in Hebrew Gematriya or English) and localized weekday name.
3. **Weekly Parasha:** Displays the current week's Torah portion, configurable for Israel or Diaspora schedules.
4. **Zmanim (Halachic Times):** Calculates and formats 20+ prayer and astronomical times (e.g., sunrise, sunset, latest Shema, chatzot) based on a selected city and optional minute offsets.
5. **Elementor Integration:** Provides 5 native Elementor widgets. Today, weekday, parasha, and zmanim expose styling and typography controls; the calendar widget has no custom controls.

---

## 2. Key Architecture Principles

### Client-Side Calculation Model (v2.0+)
- **Browser Calculations:** Hebrew dates, holidays, parashot, and zmanim are calculated in the browser using the bundled `js/hebcal.min.js` (Hebcal ES6). The weekday shortcode is an exception: PHP renders it using `gmdate('N')`, based on UTC.
- **Server Markup:** Today, parasha, and zmanim output span placeholders (e.g., `<span class="jcal-zmanim" data-type="shkiah" data-offset="0"></span>`). The calendar outputs a full table skeleton with empty date/event containers; the weekday outputs translated text.
- **Data Bridge (`wp_localize_script`):** Configuration options from the database (`jcal_options`) are passed from PHP to JS via the global `jcal_settings` object attached to `js/settings.js`.
- **Hydration & Lifecycle:** On DOM ready, `js/shortcodes.js` and `js/calendar.js` inspect the DOM and hydrate placeholder elements.
- **Elementor Live Preview:** Both script files hook into `elementor/frontend/init` and register `frontend/element_ready/<widget_name>.default` handlers only in edit mode. Handlers exist for `hebrew_calendar`, `today_date`, `parashat_shavua`, and `zmanim`; the weekday is rendered by PHP.


### Settings Contract

Settings are stored in the `jcal_options` option and exposed through `jcal_settings`:

| Stored option key | Default | JavaScript field |
| :--- | :--- | :--- |
| `city` | `31.76904_35.21633_Asia/Jerusalem` (Jerusalem) | `zmanim_location`, encoded as `latitude_longitude_timezone` |
| `jcal_parasha_display_diaspora` | `israel` | `display_diaspora`, true only for `diaspora` |

The diaspora setting controls both weekly parasha and calendar events through Hebcal's `il: !display_diaspora`. The `locale` field comes from the WordPress locale, not a saved plugin option. The admin page uses `admin/cities.txt` and requires `manage_options`.

### Current Limitations

- Only one calendar per page is supported: `js/calendar.js` shares month state and uses document-wide selectors.
- Browser date calculations use the browser's current date. Zmanim output is formatted in the selected city's timezone; the PHP weekday uses UTC. These sources can disagree near date boundaries.
- Hydration runs on page ready and the relevant Elementor edit-mode hooks; there is no timer to refresh at midnight.

---

## 3. Directory & File Structure

```
hb-jewish-calendar/
├── hb-jewish-calendar.php       # Bootstrap, class JewishCalendar, shortcode/script registration, hooks
├── shortcodes.php               # Shortcode callbacks and HTML markup generators
├── template-loader.php          # jcal_get_template_html() helper for rendering template files
├── uninstall.php                # Cleanup on plugin deletion (deletes 'jcal_options')
├── readme.txt                   # WordPress plugin repository documentation
│
├── admin/
│   ├── settings-page.php        # Class JcalSettingsPage, WordPress Settings API integration
│   ├── cities.txt               # Dataset of ~400 cities formatted: "City Name,lat_long_timezone"
│   └── hb-settings.css          # Styling for admin options screen
│
├── templates/
│   ├── calendar.php             # Table grid template for monthly calendar (6 rows x 7 days)
│   └── calendar-single-day.php  # Single day cell template containing Hebrew & Gregorian numbers and events
│
├── widgets/                     # Elementor widget definitions (classes extending \Elementor\Widget_Base)
│   ├── jcal-elementor-calendar-widget.php   # Widget: 'hebrew_calendar'
│   ├── jcal-elementor-today-widget.php      # Widget: 'today_date'
│   ├── jcal-elementor-parasha-widget.php    # Widget: 'parashat_shavua'
│   ├── jcal-elementor-zmanim-widget.php     # Widget: 'zmanim'
│   └── jcal-elementor-dayinweek-widget.php  # Widget: 'day_in_week'
│
├── js/
│   ├── hebcal.min.js            # Bundled Hebcal ES6 engine (Do not edit directly)
│   ├── hebcal-leyning.min.js    # Bundled @hebcal/leyning 9.2.7 (do not edit directly)
│   ├── hebcal-leyning.LICENSE   # Leyning BSD-2-Clause license
│   ├── settings.js              # Accessors: jcalGetLocale(), jcalGetDisplayDiaspora(), jcalGetZmanimLocation()
│   ├── shortcodes.js            # Injects Parasha, Today date, and Zmanim values into DOM
│   ├── calendar.js              # Calendar navigation, populating dates & holidays, dispatches jcalCalendarPopulated
│   └── cities.json              # City dataset; not referenced by runtime code
│
├── css/
│   └── calendar.css             # Frontend styles for the calendar grid, responsive layouts, buttons
│
└── languages/                   # Localization files
    ├── hb-jewish-calendar.pot
    ├── hb-jewish-calendar-he_IL.po
    ├── hb-jewish-calendar-he_IL.mo
    └── hb-jewish-calendar-he_IL.l10n.php
```

---

## 4. Shortcodes & Elementor Widgets Reference

| Feature | Shortcode | Shortcode Attributes | Elementor Widget Class | Elementor Widget ID |
| :--- | :--- | :--- | :--- | :--- |
| **Monthly Calendar** | `[jcal_heb_calendar]` | None | `Jcal_Elementor_calendar_Widget` | `hebrew_calendar` |
| **Today Date** | `[jcal_today_hdate]` | None | `Jcal_Elementor_today_Widget` | `today_date` |
| **Day of Week** | `[jcal_day_in_week]` | None | `Jcal_Elementor_dayinweek_Widget` | `day_in_week` |
| **Parashat Hashavua**| `[jcal_parasha]` | None | `Jcal_Elementor_parasha_Widget` | `parashat_shavua` |
| **Zmanim** | `[jcal_zmanim]` | `type` (e.g. `shkiah`), `offset` (min) | `Jcal_Elementor_zmanim_Widget` | `zmanim` |

The bootstrap also registers `[jcal_shabbat_times]`, but its callback is a stub returning `null`; it has no widget and produces no output.

### Supported Zmanim Types
`chatzotNight`, `alotHaShachar`, `alotHaShachar72`, `misheyakir`, `neitzHaChama`, `sunrise`, `sofZmanShma`, `sofZmanShmaMGA`, `sofZmanShmaMGA16Point1`, `sofZmanTfilla`, `sofZmanTfillaMGA`, `sofZmanTfillaMGA16Point1`, `chatzot`, `minchaGedola`, `minchaGedolaMGA`, `minchaKetana`, `minchaKetanaMGA`, `plagHaMincha`, `sunset`, `shkiah`, `beinHaShmashos`, `dusk`, `tzeit`.

The list above describes shortcode support (23 types). The Elementor selector omits `sunrise`, `sunset`, and `dusk`. Shortcode defaults are `type="shkiah"` and `offset="0"`; offsets are parsed as integer minutes and may be negative. The Elementor offset control is constrained to 0–100 minutes.

---

## 5. Development Guidelines & Rules

### WordPress Standards & Security
1. **Direct Access Protection:** Handwritten runtime PHP files should guard access before executing plugin logic:
   ```php
   if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
   ```
   Preserve the `WP_UNINSTALL_PLUGIN` guard in `uninstall.php`. Generated translation files are exempt; do not hand-edit them to add guards. Existing gap: `shortcodes.php` currently has no `ABSPATH` guard.
2. **Escaping & Sanitization:**
   - Always sanitize inputs in settings callbacks (`sanitize_text_field`, etc.).
   - Always escape output in templates and widgets (`esc_html`, `esc_attr`, `wp_kses_post`, `esc_html__`, `esc_attr_e`).
3. **Internationalization (i18n):**
   - Use the text domain `'hb-jewish-calendar'` for all user-facing strings.
   - For Hebrew vs English date logic in JavaScript, use `jcalGetLocale()`. PHP maps WordPress locale `he_IL` to `he` and all others to `en`; JavaScript maps `en` to `en` and any other value to `he-x-NoNikud`.
4. **Conditional Asset Loading:**
   - Script handles: `jcal_hebcal`, `jcal_leyning`, `jcal_settings_js`, `jcal_calendar_js`, `jcal_shortcodes_js`.
   - Stylesheet handle: `jcal_calendar_css`.
   - Keep frontend assets conditional on shortcode/widget use. `jcal_settings_js` is always enqueued on the frontend and depends on jQuery. Both renderer scripts depend on jQuery, `jcal_hebcal`, and `jcal_settings_js`; `jcal_shortcodes_js` also depends on `jcal_leyning`, which depends on `jcal_hebcal`. The calendar shortcode also enqueues its CSS. The weekday shortcode needs no JS, although its widget currently declares `jcal_shortcodes_js`. Some widget control-registration callbacks also invoke shortcode callbacks that enqueue scripts.

### JavaScript & Hebcal Usage
1. **Hebcal Library Integrity:** Never edit `js/hebcal.min.js` directly. Its bundled header identifies `@hebcal/core v5.10.1`. Known documentation discrepancy: the bundle header says GPLv2, while `readme.txt` credits Hebcal as CC BY 4.0. Reconcile against upstream license material before changing dependency license claims.
2. **Hebrew Calendar Math:**
   - Month numbering in Hebcal `HDate`: Nisan = 1, Tishrei = 7, Adar I = 12, Adar II = 13 (leap year).
   - In non-leap years, Adar = 12.
   - When calculating next/prev months, handle year increment at month 7 (Tishrei) and leap year transitions as implemented in `js/calendar.js`.
3. **Elementor Re-rendering:**
   - When modifying or adding shortcode/widget render functions in JavaScript, make sure you register the handler with `elementorFrontend.hooks.addAction('frontend/element_ready/<widget_name>.default', callback)` so live previews in the Elementor builder stay updated.

### Extensibility & Existing Hooks
Preserve these existing hook contracts when modifying the codebase:
- **`jcal_on_calendar_shortcode`** (`do_action`): Fired before rendering the monthly calendar shortcode.
- **`jcal_calendar_shortcode_html_filter`** (`apply_filters`): Filters the returned calendar shortcode HTML string.
- **`jcal_adminpage_on_register_settings`** (`do_action`): Allows external/pro add-ons to register additional admin settings sections and fields.
- **`jcal_adminpage_sanitize_options`** (`apply_filters`): Filters the sanitized options array before saving `jcal_options`.
- **`jcalCalendarPopulated`** (`CustomEvent` on `document`): Dispatched by `calendar.js` after the month grid finishes rendering. Detail contains `{ currentDate }`.

---

## 6. Common Recipes & Workflows

### Adding a New Zman Type
1. Add the key and translated label to the inline `'options'` array of the `zmanim_type` control in `widgets/jcal-elementor-zmanim-widget.php`.
2. Add the corresponding case statement to `jcalGetZmanByType()` in `js/shortcodes.js` invoking the appropriate Hebcal `Zmanim` method.
3. Update `readme.txt` under `[jcal_zmanim]` usage documentation and the supported types in this guide.

### Adding a New Elementor Widget
1. Create `widgets/jcal-elementor-<name>-widget.php` extending `\Elementor\Widget_Base`.
2. Implement `get_name()`, `get_title()`, `get_icon()`, `get_categories()` (use `['hebrew_calendar']`), `register_controls()`, `render()`, and `get_script_depends()`.
3. Require and register the widget in `JewishCalendar::jcal_register_hebrew_calendar_widgets()` in `hb-jewish-calendar.php`.
4. If frontend JS is required, add an Elementor frontend hook in the appropriate JS file (`shortcodes.js` or `calendar.js`).

### Validation

There is no automated test suite or build configuration checked into this repository. For code changes, run syntax checks on affected files with the available PHP/Node runtimes, for example:

```sh
php -l shortcodes.php
node --check js/shortcodes.js
node --check js/calendar.js
git diff --check
```

Match manual checks to the changed behavior:

- Render affected shortcodes and widgets in WordPress, checking Hebrew/English and Israel/Diaspora settings.
- For calendar changes, check next/previous navigation across Elul/Tishrei and Adar/Nisan in leap and non-leap years, including the optional sixth row.
- For zmanim changes, check city/timezone selection and positive/negative shortcode offsets.
- For widget changes, check Elementor initial rendering and repeated edits.
- For asset changes, check pages with and without relevant shortcodes/widgets and verify dependencies and calendar CSS load correctly.

For documentation-only changes, verify claims against source and check whitespace; runtime tests are unnecessary. Report checks actually performed and any checks that could not be run.
