<?php
$integration = is_array($settings ?? null) ? $settings : [];
$activeTab = (string) ($activeTab ?? 'integration');
$environment = (string) ($integration['environment'] ?? 'sandbox');
$clientId = (string) ($integration['client_id'] ?? '');
$hasClientSecret = (bool) ($integration['has_client_secret'] ?? false);
$redirectUri = (string) ($integration['redirect_uri'] ?? '');
$ordersFetchEnabled = (bool) ($integration['orders_fetch_enabled'] ?? false);
$ordersFetchStartDate = (string) ($integration['orders_fetch_start_date'] ?? '');
$isConnected = (bool) ($integration['is_connected'] ?? false);
$tokenExpiresAt = (string) ($integration['token_expires_at'] ?? '');
$connectedAt = (string) ($integration['connected_at'] ?? '');
$defaultCallback = (string) ($defaultRedirectUri ?? '');
$importIntervalSeconds = max(60, (int) ($importIntervalSeconds ?? 300));
$importIntervalMinutes = max(1, (int) floor($importIntervalSeconds / 60));
$statusSyncDirection = (string) ($statusSyncDirection ?? 'allegro_to_orderpro');
$statusSyncIntervalMinutes = max(1, (int) ($statusSyncIntervalMinutes ?? 15));
$statusMappings = is_array($statusMappings ?? null) ? $statusMappings : [];
$orderproStatuses = is_array($orderproStatuses ?? null) ? $orderproStatuses : [];
?>

<section class="card">
  <h2 class="section-title"><?= $e($t('settings.allegro.title')) ?></h2>
  <p class="muted mt-12"><?= $e($t('settings.allegro.description')) ?></p>

  <?php if (!empty($errorMessage)): ?>
    <div class="alert alert--danger mt-12" role="alert"><?= $e((string) $errorMessage) ?></div>
  <?php endif; ?>

  <?php if (!empty($successMessage)): ?>
    <div class="alert alert--success mt-12" role="status"><?= $e((string) $successMessage) ?></div>
  <?php endif; ?>

  <?php if (!empty($warningMessage)): ?>
    <div class="alert alert--warning mt-12" role="alert"><?= $e((string) $warningMessage) ?></div>
  <?php endif; ?>
</section>

<section class="card mt-16">
  <nav class="content-tabs-nav" aria-label="<?= $e($t('settings.allegro.tabs.label')) ?>">
    <button type="button" class="content-tab-btn<?= $activeTab === 'integration' ? ' is-active' : '' ?>" data-tab-target="allegro-tab-integration">
      <?= $e($t('settings.allegro.tabs.integration')) ?>
    </button>
    <button type="button" class="content-tab-btn<?= $activeTab === 'statuses' ? ' is-active' : '' ?>" data-tab-target="allegro-tab-statuses">
      <?= $e($t('settings.allegro.tabs.statuses')) ?>
    </button>
    <button type="button" class="content-tab-btn<?= $activeTab === 'settings' ? ' is-active' : '' ?>" data-tab-target="allegro-tab-settings">
      <?= $e($t('settings.allegro.tabs.settings')) ?>
    </button>
    <button type="button" class="content-tab-btn<?= $activeTab === 'delivery' ? ' is-active' : '' ?>" data-tab-target="allegro-tab-delivery">
      <?= $e($t('settings.allegro.tabs.delivery')) ?>
    </button>
  </nav>

  <div class="content-tab-panel<?= $activeTab === 'integration' ? ' is-active' : '' ?>" data-tab-panel="allegro-tab-integration">
    <section class="mt-16">
      <h3 class="section-title"><?= $e($t('settings.allegro.callback.title')) ?></h3>
      <p class="muted mt-12"><?= $e($t('settings.allegro.callback.hint')) ?></p>
      <code class="settings-allegro-callback mt-12"><?= $e($defaultCallback) ?></code>
    </section>

    <section class="mt-16">
      <h3 class="section-title"><?= $e($t('settings.allegro.config.title')) ?></h3>
      <form class="statuses-form mt-16" action="/settings/integrations/allegro/save" method="post" novalidate>
        <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">

        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.fields.environment')) ?></span>
          <select class="form-control" name="environment" id="allegro-env-select">
            <option value="sandbox"<?= $environment === 'sandbox' ? ' selected' : '' ?>><?= $e($t('settings.allegro.environment.sandbox')) ?></option>
            <option value="production"<?= $environment === 'production' ? ' selected' : '' ?>><?= $e($t('settings.allegro.environment.production')) ?></option>
          </select>
          <span class="muted"><?= $e($t('settings.allegro.fields.environment_hint')) ?></span>
        </label>

        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.fields.client_id')) ?></span>
          <input class="form-control" type="text" name="client_id" maxlength="128" value="<?= $e($clientId) ?>">
        </label>

        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.fields.client_secret')) ?></span>
          <input class="form-control" type="password" name="client_secret" autocomplete="new-password">
          <span class="muted"><?= $e($hasClientSecret ? $t('settings.allegro.client_secret.saved') : $t('settings.allegro.client_secret.missing')) ?></span>
        </label>

        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.fields.redirect_uri')) ?></span>
          <input class="form-control" type="url" name="redirect_uri" maxlength="255" value="<?= $e($redirectUri) ?>">
          <span class="muted"><?= $e($t('settings.allegro.fields.redirect_uri_hint')) ?></span>
        </label>

        <label class="field-inline">
          <input type="hidden" name="orders_fetch_enabled" value="0">
          <input type="checkbox" name="orders_fetch_enabled" value="1"<?= $ordersFetchEnabled ? ' checked' : '' ?>>
          <span><?= $e($t('settings.allegro.fields.orders_fetch_enabled')) ?></span>
        </label>

        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.fields.orders_fetch_start_date')) ?></span>
          <input class="form-control" type="date" name="orders_fetch_start_date" value="<?= $e($ordersFetchStartDate) ?>">
        </label>

        <div class="form-actions">
          <button type="submit" class="btn btn--primary"><?= $e($t('settings.allegro.actions.save')) ?></button>
        </div>
      </form>
    </section>

    <section class="mt-16">
      <h3 class="section-title"><?= $e($t('settings.allegro.oauth.title')) ?></h3>
      <p class="muted mt-12">
        <?= $e($isConnected ? $t('settings.allegro.oauth.connected') : $t('settings.allegro.oauth.not_connected')) ?>
      </p>
      <?php if ($connectedAt !== ''): ?>
        <p class="muted mt-12"><?= $e($t('settings.allegro.oauth.connected_at', ['date' => $connectedAt])) ?></p>
      <?php endif; ?>
      <?php if ($tokenExpiresAt !== ''): ?>
        <p class="muted mt-12"><?= $e($t('settings.allegro.oauth.token_expires_at', ['date' => $tokenExpiresAt])) ?></p>
      <?php endif; ?>
      <form class="mt-16" action="/settings/integrations/allegro/oauth/start" method="post">
        <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
        <button type="submit" class="btn btn--secondary"><?= $e($t('settings.allegro.actions.connect')) ?></button>
      </form>
    </section>

    <section class="mt-16">
      <h3 class="section-title"><?= $e($t('settings.allegro.import_single.title')) ?></h3>
      <p class="muted mt-12"><?= $e($t('settings.allegro.import_single.description')) ?></p>
      <form class="statuses-form mt-12" action="/settings/integrations/allegro/import-single" method="post" novalidate>
        <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.import_single.checkout_form_id')) ?></span>
          <input class="form-control" type="text" name="checkout_form_id" maxlength="128" required placeholder="<?= $e($t('settings.allegro.import_single.checkout_form_id_placeholder')) ?>">
        </label>
        <div class="form-actions">
          <button type="submit" class="btn btn--primary"><?= $e($t('settings.allegro.actions.import_single')) ?></button>
        </div>
      </form>
    </section>
  </div>

  <div class="content-tab-panel<?= $activeTab === 'statuses' ? ' is-active' : '' ?>" data-tab-panel="allegro-tab-statuses">
    <section class="mt-16">
      <h3 class="section-title"><?= $e($t('settings.allegro.statuses.title')) ?></h3>
      <p class="muted mt-12"><?= $e($t('settings.allegro.statuses.description')) ?></p>

      <form class="mt-12" action="/settings/integrations/allegro/statuses/sync" method="post">
        <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
        <button type="submit" class="btn btn--secondary"><?= $e($t('settings.allegro.statuses.actions.sync')) ?></button>
      </form>

      <form class="statuses-form mt-12" action="/settings/integrations/allegro/statuses/save" method="post" novalidate>
        <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.statuses.fields.allegro_status_code')) ?></span>
          <input class="form-control" type="text" name="allegro_status_code" maxlength="64" required placeholder="<?= $e($t('settings.allegro.statuses.fields.allegro_status_code_placeholder')) ?>">
        </label>
        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.statuses.fields.allegro_status_name')) ?></span>
          <input class="form-control" type="text" name="allegro_status_name" maxlength="120" placeholder="<?= $e($t('settings.allegro.statuses.fields.allegro_status_name_placeholder')) ?>">
        </label>
        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.statuses.fields.orderpro_status_code')) ?></span>
          <select class="form-control" name="orderpro_status_code" required>
            <option value=""><?= $e($t('settings.allegro.statuses.fields.orderpro_status_placeholder')) ?></option>
            <?php foreach ($orderproStatuses as $status): ?>
              <?php $statusCode = strtolower(trim((string) ($status['code'] ?? ''))); ?>
              <?php if ($statusCode === '') continue; ?>
              <option value="<?= $e($statusCode) ?>">
                <?= $e((string) ($status['name'] ?? $statusCode)) ?> (<?= $e($statusCode) ?>)
              </option>
            <?php endforeach; ?>
          </select>
        </label>
        <div class="form-actions">
          <button type="submit" class="btn btn--primary"><?= $e($t('settings.allegro.statuses.actions.save')) ?></button>
        </div>
      </form>
    </section>

    <section class="mt-16">
      <h3 class="section-title"><?= $e($t('settings.allegro.statuses.list_title')) ?></h3>
      <form action="/settings/integrations/allegro/statuses/save-bulk" method="post">
        <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
        <div class="table-wrap mt-12">
          <table class="table">
            <thead>
            <tr>
              <th><?= $e($t('settings.allegro.statuses.fields.allegro_status_code')) ?></th>
              <th><?= $e($t('settings.allegro.statuses.fields.allegro_status_name')) ?></th>
              <th><?= $e($t('settings.allegro.statuses.fields.orderpro_status_code')) ?></th>
            </tr>
            </thead>
            <tbody>
            <?php if ($statusMappings === []): ?>
              <tr>
                <td colspan="3" class="muted"><?= $e($t('settings.allegro.statuses.empty')) ?></td>
              </tr>
            <?php else: ?>
              <?php foreach ($statusMappings as $mapping): ?>
                <tr>
                  <td>
                    <code><?= $e((string) ($mapping['allegro_status_code'] ?? '')) ?></code>
                    <input type="hidden" name="allegro_status_code[]" value="<?= $e((string) ($mapping['allegro_status_code'] ?? '')) ?>">
                  </td>
                  <td>
                    <?= $e((string) ($mapping['allegro_status_name'] ?? '')) ?>
                    <input type="hidden" name="allegro_status_name[]" value="<?= $e((string) ($mapping['allegro_status_name'] ?? '')) ?>">
                  </td>
                  <td>
                    <select class="form-control" name="orderpro_status_code[]">
                      <option value=""><?= $e($t('settings.allegro.statuses.fields.orderpro_status_placeholder')) ?></option>
                      <?php foreach ($orderproStatuses as $status): ?>
                        <?php $statusCode = strtolower(trim((string) ($status['code'] ?? ''))); ?>
                        <?php if ($statusCode === '') continue; ?>
                        <option value="<?= $e($statusCode) ?>"<?= $statusCode === strtolower(trim((string) ($mapping['orderpro_status_code'] ?? ''))) ? ' selected' : '' ?>>
                          <?= $e((string) ($status['name'] ?? $statusCode)) ?> (<?= $e($statusCode) ?>)
                        </option>
                      <?php endforeach; ?>
                    </select>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
          </table>
        </div>
        <?php if ($statusMappings !== []): ?>
          <div class="form-actions mt-12">
            <button type="submit" class="btn btn--primary"><?= $e($t('settings.allegro.statuses.actions.save_bulk')) ?></button>
          </div>
        <?php endif; ?>
      </form>
    </section>
  </div>

  <div class="content-tab-panel<?= $activeTab === 'settings' ? ' is-active' : '' ?>" data-tab-panel="allegro-tab-settings">
    <section class="mt-16">
      <h3 class="section-title"><?= $e($t('settings.allegro.settings.title')) ?></h3>
      <p class="muted mt-12"><?= $e($t('settings.allegro.settings.description')) ?></p>
      <form class="statuses-form mt-12" action="/settings/integrations/allegro/settings/save" method="post" novalidate>
        <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.settings.orders_import_interval_minutes')) ?></span>
          <input
            class="form-control"
            type="number"
            name="orders_import_interval_minutes"
            min="1"
            max="1440"
            step="1"
            value="<?= $e((string) $importIntervalMinutes) ?>"
          >
          <span class="muted"><?= $e($t('settings.allegro.settings.orders_import_interval_hint')) ?></span>
        </label>

        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.settings.status_sync_direction')) ?></span>
          <select class="form-control" name="status_sync_direction">
            <option value="allegro_to_orderpro"<?= $statusSyncDirection === 'allegro_to_orderpro' ? ' selected' : '' ?>>
              <?= $e($t('settings.allegro.settings.status_sync_direction_allegro_to_orderpro')) ?>
            </option>
            <option value="orderpro_to_allegro"<?= $statusSyncDirection === 'orderpro_to_allegro' ? ' selected' : '' ?>>
              <?= $e($t('settings.allegro.settings.status_sync_direction_orderpro_to_allegro')) ?>
            </option>
          </select>
          <span class="muted"><?= $e($t('settings.allegro.settings.status_sync_direction_hint')) ?></span>
        </label>

        <label class="form-field">
          <span class="field-label"><?= $e($t('settings.allegro.settings.status_sync_interval_minutes')) ?></span>
          <input
            class="form-control"
            type="number"
            name="status_sync_interval_minutes"
            min="1"
            max="1440"
            step="1"
            value="<?= $e((string) $statusSyncIntervalMinutes) ?>"
          >
          <span class="muted"><?= $e($t('settings.allegro.settings.status_sync_interval_hint')) ?></span>
        </label>
        <div class="form-actions">
          <button type="submit" class="btn btn--primary"><?= $e($t('settings.allegro.settings.save')) ?></button>
        </div>
      </form>
    </section>
  </div>

  <?php
  $dmMappings = is_array($deliveryMappings ?? null) ? $deliveryMappings : [];
  $dmOrderMethods = is_array($orderDeliveryMethods ?? null) ? $orderDeliveryMethods : [];
  $dmAllegroServices = is_array($allegroDeliveryServices ?? null) ? $allegroDeliveryServices : [];
  $dmApaczkaServices = is_array($apaczkaDeliveryServices ?? null) ? $apaczkaDeliveryServices : [];
  $dmInpostServices = is_array($inpostDeliveryServices ?? null) ? $inpostDeliveryServices : [];
  $dmServicesError = (string) ($allegroDeliveryServicesError ?? '');
  $dmMappingsByMethod = [];
  foreach ($dmMappings as $dm) {
      $dmMappingsByMethod[trim((string) ($dm['order_delivery_method'] ?? ''))] = $dm;
  }
  ?>
  <div class="content-tab-panel<?= $activeTab === 'delivery' ? ' is-active' : '' ?>" data-tab-panel="allegro-tab-delivery">
    <section class="mt-16">
      <h3 class="section-title"><?= $e($t('settings.allegro.delivery.title')) ?></h3>
      <p class="muted mt-12"><?= $e($t('settings.allegro.delivery.description')) ?></p>

      <?php if ($dmServicesError !== ''): ?>
        <div class="alert alert--danger mt-12"><?= $e($dmServicesError) ?></div>
      <?php endif; ?>

      <?php if ($dmOrderMethods === []): ?>
        <p class="muted mt-12"><?= $e($t('settings.allegro.delivery.empty_orders')) ?></p>
      <?php else: ?>
        <form action="/settings/integrations/allegro/delivery/save" method="post">
          <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
          <div class="table-wrap table-wrap--visible mt-12">
            <table class="table">
              <thead>
                <tr>
                  <th><?= $e($t('settings.allegro.delivery.fields.order_method')) ?></th>
                  <th><?= $e($t('settings.allegro.delivery.fields.carrier')) ?></th>
                  <th><?= $e($t('settings.allegro.delivery.fields.allegro_service')) ?></th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($dmOrderMethods as $rowIdx => $orderMethod): ?>
                  <?php
                  $currentMapping = $dmMappingsByMethod[$orderMethod] ?? null;
                  $currentProvider = $currentMapping !== null ? trim((string) ($currentMapping['provider'] ?? 'allegro_wza')) : '';
                  $currentMethodId = $currentMapping !== null ? trim((string) ($currentMapping['provider_service_id'] ?? '')) : '';
                  $currentServiceName = $currentMapping !== null ? trim((string) ($currentMapping['provider_service_name'] ?? '')) : '';
                  $currentProviderCarrierId = $currentMapping !== null ? trim((string) ($currentMapping['provider_carrier_id'] ?? '')) : '';
                  $currentCarrier = '';
                  if ($currentProvider === 'apaczka') {
                    $currentCarrier = 'apaczka';
                  } elseif (stripos($currentProviderCarrierId, 'inpost') !== false) {
                    $currentCarrier = 'inpost';
                  } elseif ($currentMethodId !== '') {
                    $currentCarrier = 'allegro';
                  }
                  ?>
                  <tr data-dm-row="<?= $rowIdx ?>">
                    <td>
                      <strong><?= $e($orderMethod) ?></strong>
                      <input type="hidden" name="order_delivery_method[]" value="<?= $e($orderMethod) ?>">
                    </td>
                    <td>
                      <select class="form-control dm-carrier-select" name="carrier[]" data-row="<?= $rowIdx ?>">
                        <option value="">-- <?= $e($t('settings.allegro.delivery.fields.no_mapping')) ?> --</option>
                        <option value="allegro"<?= $currentCarrier === 'allegro' && $currentMethodId !== '' ? ' selected' : '' ?>>Allegro</option>
                        <option value="inpost"<?= $currentCarrier === 'inpost' ? ' selected' : '' ?>>InPost</option>
                        <option value="apaczka"<?= $currentCarrier === 'apaczka' ? ' selected' : '' ?>>Apaczka</option>
                      </select>
                    </td>
                    <td>
                      <div class="dm-service-wrap" data-row="<?= $rowIdx ?>">
                        <input type="hidden" name="allegro_delivery_method_id[]" class="dm-hidden-method-id" value="<?= $e($currentProvider !== 'apaczka' ? $currentMethodId : '') ?>">
                        <input type="hidden" name="apaczka_delivery_method_id[]" class="dm-hidden-apaczka-method-id" value="<?= $e($currentProvider === 'apaczka' ? $currentMethodId : '') ?>">
                        <input type="hidden" name="allegro_credentials_id[]" class="dm-hidden-credentials-id" value="<?= $e(trim((string) ($currentMapping['provider_account_id'] ?? ''))) ?>">
                        <input type="hidden" name="allegro_carrier_id[]" class="dm-hidden-carrier-id" value="<?= $e($currentProviderCarrierId) ?>">
                        <input type="hidden" name="allegro_service_name[]" class="dm-hidden-service-name" value="<?= $e($currentServiceName) ?>">

                        <?php // Allegro searchable select ?>
                        <div class="dm-allegro-panel dm-searchable-select" data-current-id="<?= $e($currentCarrier === 'allegro' ? $currentMethodId : '') ?>" data-current-name="<?= $e($currentCarrier === 'allegro' ? $currentServiceName : '') ?>" style="<?= $currentCarrier !== 'allegro' ? 'display:none' : '' ?>">
                          <input type="text" class="form-control dm-search-input" placeholder="<?= $e($t('settings.allegro.delivery.fields.search_placeholder')) ?>" value="<?= $e($currentCarrier === 'allegro' ? $currentServiceName : '') ?>" autocomplete="off">
                          <div class="searchable-select__dropdown dm-dropdown">
                            <div class="searchable-select__option dm-option-clear" data-value="" data-label="" data-credentials-id="" data-carrier-id="">
                              <em class="muted">-- <?= $e($t('settings.allegro.delivery.fields.no_mapping')) ?> --</em>
                            </div>
                            <?php foreach ($dmAllegroServices as $svc): ?>
                              <?php
                              $svcId = is_array($svc['id'] ?? null) ? $svc['id'] : [];
                              $svcMethodId = trim((string) ($svcId['deliveryMethodId'] ?? ''));
                              $svcCredentialsId = trim((string) ($svcId['credentialsId'] ?? ''));
                              $svcName = trim((string) ($svc['name'] ?? ''));
                              $svcCarrierId = trim((string) ($svc['carrierId'] ?? ''));
                              $svcOwner = trim((string) ($svc['owner'] ?? ''));
                              $svcLabel = $svcName . ' (' . $svcOwner . ')';
                              ?>
                              <div class="searchable-select__option"
                                data-value="<?= $e($svcMethodId) ?>"
                                data-label="<?= $e($svcLabel) ?>"
                                data-credentials-id="<?= $e($svcCredentialsId) ?>"
                                data-carrier-id="<?= $e($svcCarrierId) ?>"
                              ><?= $e($svcName) ?> <span class="muted">(<?= $e($svcOwner) ?>)</span></div>
                            <?php endforeach; ?>
                          </div>
                        </div>

                        <div class="dm-apaczka-panel" style="<?= $currentCarrier !== 'apaczka' ? 'display:none' : '' ?>">
                          <?php if ($dmApaczkaServices === []): ?>
                            <div class="muted">Brak uslug Apaczka (sprawdz konfiguracje App ID/App Secret).</div>
                          <?php else: ?>
                            <select class="form-control dm-apaczka-select">
                              <option value="">-- <?= $e($t('settings.allegro.delivery.fields.no_mapping')) ?> --</option>
                              <?php foreach ($dmApaczkaServices as $aSvc): ?>
                                <?php
                                $aSvcId = trim((string) ($aSvc['id'] ?? ''));
                                $aSvcName = trim((string) ($aSvc['name'] ?? ''));
                                $aSvcCarrier = trim((string) ($aSvc['carrier_code'] ?? ''));
                                ?>
                                <option
                                  value="<?= $e($aSvcId) ?>"
                                  data-carrier-id="<?= $e($aSvcCarrier) ?>"
                                  <?= $currentCarrier === 'apaczka' && $currentMethodId === $aSvcId ? 'selected' : '' ?>>
                                  <?= $e($aSvcName !== '' ? $aSvcName : ('ID ' . $aSvcId)) ?>
                                </option>
                              <?php endforeach; ?>
                            </select>
                          <?php endif; ?>
                        </div>

                        <?php // InPost simple select ?>
                        <div class="dm-inpost-panel" style="<?= $currentCarrier !== 'inpost' ? 'display:none' : '' ?>">
                          <?php if ($dmInpostServices === []): ?>
                            <div class="muted">Brak uslug InPost (sprawdz polaczenie z Allegro).</div>
                          <?php else: ?>
                            <select class="form-control dm-inpost-select">
                              <option value="">-- <?= $e($t('settings.allegro.delivery.fields.no_mapping')) ?> --</option>
                              <?php foreach ($dmInpostServices as $inSvc): ?>
                                <?php
                                $inSvcId = is_array($inSvc['id'] ?? null) ? $inSvc['id'] : [];
                                $inSvcMethodId = trim((string) ($inSvcId['deliveryMethodId'] ?? ''));
                                $inSvcCredentialsId = trim((string) ($inSvcId['credentialsId'] ?? ''));
                                $inSvcCarrierId = trim((string) ($inSvc['carrierId'] ?? ''));
                                $inSvcName = trim((string) ($inSvc['name'] ?? ''));
                                ?>
                                <option
                                  value="<?= $e($inSvcMethodId) ?>"
                                  data-credentials-id="<?= $e($inSvcCredentialsId) ?>"
                                  data-carrier-id="<?= $e($inSvcCarrierId) ?>"
                                  <?= $currentCarrier === 'inpost' && $currentMethodId === $inSvcMethodId ? 'selected' : '' ?>>
                                  <?= $e($inSvcName) ?>
                                </option>
                              <?php endforeach; ?>
                            </select>
                          <?php endif; ?>
                        </div>

                        <?php // Empty state ?>
                        <div class="dm-empty-panel muted" style="<?= $currentCarrier !== '' ? 'display:none' : ($currentMethodId !== '' ? 'display:none' : '') ?>">
                          <?= $e($t('settings.allegro.delivery.fields.select_carrier_first')) ?>
                        </div>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
          <div class="form-actions mt-12">
            <button type="submit" class="btn btn--primary"><?= $e($t('settings.allegro.delivery.actions.save')) ?></button>
          </div>
        </form>
      <?php endif; ?>
    </section>
  </div>
</section>

<script>
  (function () {
    var tabs = document.querySelectorAll('[data-tab-target]');
    var panels = document.querySelectorAll('[data-tab-panel]');
    if (tabs.length === 0 || panels.length === 0) {
      return;
    }

    var tabNameMap = {
      'allegro-tab-integration': 'integration',
      'allegro-tab-statuses': 'statuses',
      'allegro-tab-settings': 'settings',
      'allegro-tab-delivery': 'delivery'
    };

    tabs.forEach(function (tab) {
      tab.addEventListener('click', function () {
        var target = tab.getAttribute('data-tab-target');
        var tabName = tabNameMap[target] || 'integration';
        var url = new URL(window.location.href);
        var currentTab = url.searchParams.get('tab') || 'integration';
        url.searchParams.set('tab', tabName);

        // Tabs that need server data require a full reload
        if (tabName === 'delivery' && currentTab !== 'delivery') {
          window.location.href = url.toString();
          return;
        }

        window.history.replaceState(null, '', url.toString());

        tabs.forEach(function (node) { node.classList.remove('is-active'); });
        panels.forEach(function (panel) { panel.classList.remove('is-active'); });
        tab.classList.add('is-active');
        var panel = document.querySelector('[data-tab-panel=\"' + target + '\"]');
        if (panel) {
          panel.classList.add('is-active');
        }
      });
    });
  })();

  (function () {
    var envSelect = document.getElementById('allegro-env-select');
    if (!envSelect) return;
    envSelect.addEventListener('change', function () {
      window.location.href = '/settings/integrations/allegro?env=' + encodeURIComponent(envSelect.value);
    });
  })();

  (function () {
    function attachSelectFilter(selectEl) {
      if (!selectEl || selectEl.dataset.enhanced === '1') {
        return;
      }
      selectEl.dataset.enhanced = '1';

      var parent = selectEl.parentNode;
      if (!parent) {
        return;
      }

      var filterInput = document.createElement('input');
      filterInput.type = 'text';
      filterInput.className = 'form-control';
      filterInput.placeholder = 'Szukaj...';
      filterInput.autocomplete = 'off';
      filterInput.style.marginBottom = '8px';
      parent.insertBefore(filterInput, selectEl);

      function focusFirstMatch(term) {
        var query = term.toLowerCase().trim();
        if (query === '') {
          return;
        }

        var matchedIndex = -1;
        Array.prototype.forEach.call(selectEl.options, function (opt, idx) {
          if (matchedIndex >= 0) {
            return;
          }
          if (opt.textContent.toLowerCase().indexOf(query) !== -1) {
            matchedIndex = idx;
          }
        });

        if (matchedIndex >= 0 && selectEl.selectedIndex !== matchedIndex) {
          selectEl.selectedIndex = matchedIndex;
          selectEl.dispatchEvent(new Event('change', { bubbles: true }));
        }
      }

      filterInput.addEventListener('input', function () {
        focusFirstMatch(filterInput.value);
      });

      selectEl._syncTrigger = function () {
        // Keep select untouched; filter only suggests matching option.
      };
    }

    // Filter only for Apaczka (many services); InPost has few options
    document.querySelectorAll('.dm-apaczka-select').forEach(function (selectEl) {
      attachSelectFilter(selectEl);
    });

    // Carrier switching logic
    document.querySelectorAll('.dm-carrier-select').forEach(function (carrierSelect) {
      var rowIdx = carrierSelect.getAttribute('data-row');
      var serviceWrap = document.querySelector('.dm-service-wrap[data-row="' + rowIdx + '"]');
      if (!serviceWrap) return;

      var allegroPanel = serviceWrap.querySelector('.dm-allegro-panel');
      var inpostPanel = serviceWrap.querySelector('.dm-inpost-panel');
      var apaczkaPanel = serviceWrap.querySelector('.dm-apaczka-panel');
      var emptyPanel = serviceWrap.querySelector('.dm-empty-panel');
      var hiddenMethodId = serviceWrap.querySelector('.dm-hidden-method-id');
      var hiddenApaczkaMethodId = serviceWrap.querySelector('.dm-hidden-apaczka-method-id');
      var hiddenCredentialsId = serviceWrap.querySelector('.dm-hidden-credentials-id');
      var hiddenCarrierId = serviceWrap.querySelector('.dm-hidden-carrier-id');
      var hiddenServiceName = serviceWrap.querySelector('.dm-hidden-service-name');

      function showPanel(carrier) {
        if (allegroPanel) allegroPanel.style.display = carrier === 'allegro' ? '' : 'none';
        if (inpostPanel) inpostPanel.style.display = carrier === 'inpost' ? '' : 'none';
        if (apaczkaPanel) apaczkaPanel.style.display = carrier === 'apaczka' ? '' : 'none';
        if (emptyPanel) emptyPanel.style.display = carrier === '' ? '' : 'none';
      }

      showPanel(carrierSelect.value);

      carrierSelect.addEventListener('change', function () {
        var carrier = carrierSelect.value;
        showPanel(carrier);
        // Clear hidden values when switching carrier
        if (hiddenMethodId) hiddenMethodId.value = '';
        if (hiddenApaczkaMethodId) hiddenApaczkaMethodId.value = '';
        if (hiddenCredentialsId) hiddenCredentialsId.value = '';
        if (hiddenCarrierId) hiddenCarrierId.value = '';
        if (hiddenServiceName) hiddenServiceName.value = '';
        // Reset Allegro search input
        var allegroInput = allegroPanel ? allegroPanel.querySelector('.dm-search-input') : null;
        if (allegroInput) {
          allegroInput.value = '';
          allegroInput.blur();
        }
        var allegroDropdown = allegroPanel ? allegroPanel.querySelector('.dm-dropdown') : null;
        if (allegroDropdown) {
          allegroDropdown.classList.remove('is-open');
        }
        // Reset InPost select
        var inpostSelect = inpostPanel ? inpostPanel.querySelector('.dm-inpost-select') : null;
        if (inpostSelect) {
          inpostSelect.value = '';
          if (inpostSelect._syncTrigger) inpostSelect._syncTrigger();
        }
        var apaczkaSelect = apaczkaPanel ? apaczkaPanel.querySelector('.dm-apaczka-select') : null;
        if (apaczkaSelect) {
          apaczkaSelect.value = '';
          if (apaczkaSelect._syncTrigger) apaczkaSelect._syncTrigger();
        }
      });

      // InPost select change -> update hidden fields
      var inpostSelect = inpostPanel ? inpostPanel.querySelector('.dm-inpost-select') : null;
      if (inpostSelect) {
        inpostSelect.addEventListener('change', function () {
          var opt = inpostSelect.options[inpostSelect.selectedIndex];
          if (hiddenMethodId) hiddenMethodId.value = inpostSelect.value;
          if (hiddenApaczkaMethodId) hiddenApaczkaMethodId.value = '';
          if (hiddenCredentialsId) hiddenCredentialsId.value = opt ? (opt.getAttribute('data-credentials-id') || '') : '';
          if (hiddenCarrierId) hiddenCarrierId.value = opt ? (opt.getAttribute('data-carrier-id') || '') : '';
          if (hiddenServiceName) hiddenServiceName.value = opt ? opt.textContent.trim() : '';
        });
        if (inpostSelect.value !== '') {
          inpostSelect.dispatchEvent(new Event('change', { bubbles: true }));
        }
      }

      var apaczkaSelect = apaczkaPanel ? apaczkaPanel.querySelector('.dm-apaczka-select') : null;
      if (apaczkaSelect) {
        apaczkaSelect.addEventListener('change', function () {
          var opt = apaczkaSelect.options[apaczkaSelect.selectedIndex];
          if (hiddenMethodId) hiddenMethodId.value = '';
          if (hiddenApaczkaMethodId) hiddenApaczkaMethodId.value = apaczkaSelect.value;
          if (hiddenCredentialsId) hiddenCredentialsId.value = '';
          if (hiddenCarrierId) hiddenCarrierId.value = opt ? (opt.getAttribute('data-carrier-id') || '') : '';
          if (hiddenServiceName) hiddenServiceName.value = opt ? opt.textContent.trim() : '';
        });
        if (apaczkaSelect.value !== '') {
          apaczkaSelect.dispatchEvent(new Event('change', { bubbles: true }));
        }
      }
    });

    // Allegro searchable selects
    document.querySelectorAll('.dm-searchable-select').forEach(function (wrapper) {
      var searchInput = wrapper.querySelector('.dm-search-input');
      var dropdown = wrapper.querySelector('.dm-dropdown');
      var serviceWrap = wrapper.closest('.dm-service-wrap');
      if (!searchInput || !dropdown || !serviceWrap) return;

      var hiddenMethodId = serviceWrap.querySelector('.dm-hidden-method-id');
      var hiddenApaczkaMethodId = serviceWrap.querySelector('.dm-hidden-apaczka-method-id');
      var hiddenCredentialsId = serviceWrap.querySelector('.dm-hidden-credentials-id');
      var hiddenCarrierId = serviceWrap.querySelector('.dm-hidden-carrier-id');
      var hiddenServiceName = serviceWrap.querySelector('.dm-hidden-service-name');

      var options = dropdown.querySelectorAll('.searchable-select__option');
      wrapper.style.position = 'relative';

      function selectOption(opt) {
        hiddenMethodId.value = opt.getAttribute('data-value') || '';
        if (hiddenApaczkaMethodId) hiddenApaczkaMethodId.value = '';
        hiddenCredentialsId.value = opt.getAttribute('data-credentials-id') || '';
        hiddenCarrierId.value = opt.getAttribute('data-carrier-id') || '';
        hiddenServiceName.value = opt.getAttribute('data-label') || '';
        searchInput.value = opt.getAttribute('data-label') || '';
        dropdown.classList.remove('is-open');
        options.forEach(function (o) { o.classList.remove('is-selected'); });
        opt.classList.add('is-selected');
      }

      function filterOptions(query) {
        var q = query.toLowerCase().trim();
        options.forEach(function (opt) {
          var label = (opt.getAttribute('data-label') || '').toLowerCase();
          opt.style.display = (q === '' || label.indexOf(q) !== -1) ? '' : 'none';
        });
      }

      searchInput.addEventListener('focus', function () {
        filterOptions(searchInput.value);
        dropdown.classList.add('is-open');
      });

      searchInput.addEventListener('input', function () {
        filterOptions(searchInput.value);
        dropdown.classList.add('is-open');
      });

      options.forEach(function (opt) {
        opt.addEventListener('mousedown', function (e) {
          e.preventDefault();
          selectOption(opt);
        });
      });

      searchInput.addEventListener('blur', function () {
        setTimeout(function () { dropdown.classList.remove('is-open'); }, 150);
      });

      var currentId = wrapper.getAttribute('data-current-id') || '';
      if (currentId !== '') {
        options.forEach(function (opt) {
          if (opt.getAttribute('data-value') === currentId) {
            opt.classList.add('is-selected');
          }
        });
      }
    });
  })();
</script>
