<?php
/**
 * ZERTI admin UI primitives — shared PHP render helpers.
 *
 * @see docs/DESIGN-SYSTEM.md
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Build a sanitized HTML attribute string from an associative array.
 *
 * @param array<string, scalar|null> $attrs
 */
function zerti_ui_attrs(array $attrs): string
{
    $parts = [];
    foreach ($attrs as $name => $value) {
        if ($value === null || $value === false) {
            continue;
        }
        if ($value === true) {
            $parts[] = esc_attr((string) $name);
            continue;
        }
        $parts[] = esc_attr((string) $name) . '="' . esc_attr((string) $value) . '"';
    }

    return $parts === [] ? '' : ' ' . implode(' ', $parts);
}

/**
 * Open a tab root wrapper: zerti-component zerti-component-{slug}.
 *
 * @param array<string, scalar|null> $attrs Extra attributes on the root div.
 */
function zerti_ui_component_open(string $slug, array $attrs = []): void
{
    $slug = sanitize_key($slug);
    $class = trim('zerti-component zerti-component-' . $slug . ' ' . (string) ($attrs['class'] ?? ''));
    unset($attrs['class']);
    echo '<div class="' . esc_attr($class) . '"' . zerti_ui_attrs($attrs) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- attributes escaped via zerti_ui_attrs().
}

/**
 * Close tab root wrapper opened with zerti_ui_component_open().
 */
function zerti_ui_component_close(): void
{
    echo '</div>';
}

/**
 * WooCommerce prerequisite notice (warning alert).
 */
function zerti_ui_wc_required_notice(string $message): void
{
    zerti_ui_alert($message, 'warning', ['class' => 'mb-0']);
}

/**
 * Bootstrap alert.
 *
 * @param array<string, scalar|null> $attrs
 */
function zerti_ui_alert(string $message, string $variant = 'warning', array $attrs = []): void
{
    $variant = sanitize_html_class($variant);
    $role = $variant === 'danger' ? 'alert' : 'status';
    $class = trim('alert alert-' . $variant . ' ' . (string) ($attrs['class'] ?? ''));
    unset($attrs['class']);
    if (!isset($attrs['role'])) {
        $attrs['role'] = $role;
    }
    echo '<p class="' . esc_attr($class) . '"' . zerti_ui_attrs($attrs) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- attributes escaped via zerti_ui_attrs().
    echo esc_html($message);
    echo '</p>';
}

/**
 * Empty / no-data state (often hidden until JS toggles visibility).
 */
function zerti_ui_empty_state(string $message, string $extra_class = '', bool $hidden = true): void
{
    $class = trim('text-body-secondary small p-3 ' . ($hidden ? 'd-none ' : '') . $extra_class);
    echo '<div class="' . esc_attr($class) . '" role="status">';
    echo esc_html($message);
    echo '</div>';
}

/**
 * Settings-style panel header (title + optional description).
 */
function zerti_ui_panel_header(string $title, string $description = ''): void
{
    echo '<div class="zerti-settings-panel__header mb-3">';
    echo '<h6 class="mb-1">' . esc_html($title) . '</h6>';
    if ($description !== '') {
        echo '<p class="text-body-secondary small mb-0">' . esc_html($description) . '</p>';
    }
    echo '</div>';
}

/**
 * Action button (primary / secondary toolbar pattern).
 *
 * Args:
 * - tag: button|a (default button)
 * - type: button type (default button)
 * - variant: primary|secondary|outline-secondary|link
 * - size: sm|'' 
 * - label: visible text
 * - label_class: extra class on label span
 * - icon: single Font Awesome class (fa-solid fa-plus)
 * - icons: list of Font Awesome classes
 * - title: tooltip
 * - class: feature-specific classes (e.g. zerti-shop-order-new-btn)
 * - href: for anchor tags
 * - attrs: extra HTML attributes
 *
 * @param array<string, mixed> $args
 */
function zerti_ui_button(array $args): void
{
    $tag = ($args['tag'] ?? 'button') === 'a' ? 'a' : 'button';
    $variant = sanitize_html_class((string) ($args['variant'] ?? 'primary'));
    $size = ($args['size'] ?? 'sm') === 'sm' ? 'btn-sm' : '';
    $extra = trim((string) ($args['class'] ?? ''));
    $classes = trim(
        'btn ' . $size . ' btn-' . $variant
        . ' d-inline-flex align-items-center gap-2 zerti-action-btn ' . $extra
    );

    $attrs = is_array($args['attrs'] ?? null) ? $args['attrs'] : [];
    if ($tag === 'button') {
        $attrs['type'] = (string) ($args['type'] ?? 'button');
    } else {
        $attrs['href'] = (string) ($args['href'] ?? '#');
    }
    if (!empty($args['title'])) {
        $attrs['title'] = (string) $args['title'];
    }

    $icons = [];
    if (!empty($args['icon'])) {
        $icons[] = (string) $args['icon'];
    }
    if (!empty($args['icons']) && is_array($args['icons'])) {
        foreach ($args['icons'] as $icon) {
            $icons[] = (string) $icon;
        }
    }

    echo '<' . $tag . ' class="' . esc_attr($classes) . '"' . zerti_ui_attrs($attrs) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- tag is button|a; attributes escaped via zerti_ui_attrs().
    foreach ($icons as $icon) {
        echo '<i class="' . esc_attr($icon) . '" aria-hidden="true"></i>';
    }
    if (!empty($args['label'])) {
        $label_class = trim((string) ($args['label_class'] ?? ''));
        $label_attr = $label_class !== '' ? ' class="' . esc_attr($label_class) . '"' : '';
        echo '<span' . $label_attr . '>' . esc_html((string) $args['label']) . '</span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- class attr escaped via esc_attr().
    }
    $suffix_icons = [];
    if (!empty($args['suffix_icon'])) {
        $suffix_icons[] = (string) $args['suffix_icon'];
    }
    if (!empty($args['suffix_icons']) && is_array($args['suffix_icons'])) {
        foreach ($args['suffix_icons'] as $icon) {
            $suffix_icons[] = (string) $icon;
        }
    }
    foreach ($suffix_icons as $icon) {
        echo '<i class="' . esc_attr($icon) . '" aria-hidden="true"></i>';
    }
    echo '</' . $tag . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- tag is button|a.
}

/**
 * Standard export toolbar button (Excel + download icons).
 *
 * @param array<string, mixed> $args label, title, class, label_class, attrs
 */
function zerti_ui_export_button(array $args): void
{
    $args['variant'] = $args['variant'] ?? 'outline-secondary';
    $args['icons'] = ['fa-solid fa-file-excel', 'fa-solid fa-download'];
    zerti_ui_button($args);
}

/**
 * Grid / form toolbar shell.
 *
 * @param array<string, scalar|null> $attrs
 */
function zerti_ui_toolbar_open(string $aria_label, string $toolbar_class = 'zerti-grid-toolbar', array $attrs = []): void
{
    $class = trim($toolbar_class . ' ' . (string) ($attrs['class'] ?? ''));
    unset($attrs['class']);
    $attrs['role'] = $attrs['role'] ?? 'toolbar';
    $attrs['aria-label'] = $aria_label;
    echo '<div class="' . esc_attr($class) . '"' . zerti_ui_attrs($attrs) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- attributes escaped via zerti_ui_attrs().
}

/**
 * Close toolbar opened with zerti_ui_toolbar_open().
 */
function zerti_ui_toolbar_close(): void
{
    echo '</div>';
}

/**
 * Toolbar section (start/actions column).
 */
function zerti_ui_toolbar_section_open(string $section_class): void
{
    echo '<div class="' . esc_attr(trim($section_class . ' d-flex flex-wrap gap-2')) . '">';
}

/**
 * Close toolbar section.
 */
function zerti_ui_toolbar_section_close(): void
{
    echo '</div>';
}

/**
 * AG Grid mount region.
 */
function zerti_ui_ag_grid_region(string $id, string $grid_class, string $aria_label): void
{
    $class = trim($grid_class . ' ag-theme-quartz ag-theme-zerti');
    echo '<div id="' . esc_attr($id) . '" class="' . esc_attr($class) . '" role="region" aria-label="' . esc_attr($aria_label) . '"></div>';
}

/**
 * Bootstrap grid form field (settings / inventory editor pattern).
 *
 * Args: id, name, label, type (text|email|tel|textarea|…), value, required, col_class,
 * size (sm), dir, inputmode, rows, attrs (on input).
 *
 * @param array<string, mixed> $args
 */
function zerti_ui_form_field(array $args): void
{
    $id = (string) ($args['id'] ?? '');
    $name = (string) ($args['name'] ?? '');
    $label = (string) ($args['label'] ?? '');
    $type = (string) ($args['type'] ?? 'text');
    $value = $args['value'] ?? '';
    $required = !empty($args['required']);
    $col_class = trim((string) ($args['col_class'] ?? 'col-12 col-lg-6'));
    $size = ($args['size'] ?? '') === 'sm' ? 'form-control-sm' : '';
    $dir = (string) ($args['dir'] ?? '');
    $inputmode = (string) ($args['inputmode'] ?? '');
    $rows = (int) ($args['rows'] ?? 3);
    $extra_attrs = is_array($args['attrs'] ?? null) ? $args['attrs'] : [];

    $input_class = trim('form-control ' . $size);
    $input_attrs = $extra_attrs;
    if ($id !== '') {
        $input_attrs['id'] = $id;
    }
    if ($name !== '') {
        $input_attrs['name'] = $name;
    }
    if ($required) {
        $input_attrs['required'] = true;
    }
    if ($dir !== '') {
        $input_attrs['dir'] = $dir;
    }
    if ($inputmode !== '') {
        $input_attrs['inputmode'] = $inputmode;
    }

    echo '<div class="' . esc_attr($col_class) . '">';
    if ($label !== '' && $id !== '') {
        echo '<label class="form-label" for="' . esc_attr($id) . '">' . esc_html($label);
        if ($required) {
            echo ' <span class="text-danger">*</span>';
        }
        echo '</label>';
    }

    if ($type === 'textarea') {
        echo '<textarea class="' . esc_attr($input_class) . '" rows="' . esc_attr((string) max(1, $rows)) . '"'
            . zerti_ui_attrs($input_attrs) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- attributes escaped via zerti_ui_attrs().
        echo esc_textarea((string) $value);
        echo '</textarea>';
    } else {
        $input_attrs['type'] = $type;
        $input_attrs['value'] = (string) $value;
        echo '<input class="' . esc_attr($input_class) . '"' . zerti_ui_attrs($input_attrs) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- attributes escaped via zerti_ui_attrs().
    }
    echo '</div>';
}

/**
 * Open a Bootstrap card shell.
 *
 * @param array<string, scalar|null> $attrs
 */
function zerti_ui_card_open(string $class, string $aria_label = '', array $attrs = []): void
{
    $class = trim('card ' . $class . ' ' . (string) ($attrs['class'] ?? ''));
    unset($attrs['class']);
    if ($aria_label !== '') {
        $attrs['aria-label'] = $aria_label;
    }
    echo '<div class="' . esc_attr($class) . '"' . zerti_ui_attrs($attrs) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- attributes escaped via zerti_ui_attrs().
}

/**
 * Close card opened with zerti_ui_card_open().
 */
function zerti_ui_card_close(): void
{
    echo '</div>';
}
