<?php

declare(strict_types=1);

require_once __DIR__ . '/partials/forms-summary-widget.php';

$formsDesignSurface = (defined('MYRON_FORMS_DESIGN_SURFACE') && MYRON_FORMS_DESIGN_SURFACE === true) || !empty($myronFormsDesignSurface);
$currentUser = $formsDesignSurface ? myronRequireDesignAccess() : myronRequireContentAccess();
$writeUser = null;
$service = myronMicTableService();
$formsService = myronMicFormService();
$caller = myronActionCallerContextForUser($currentUser);
$bank = strtolower(trim((string) ($_GET['bank'] ?? $_POST['bank'] ?? 'tables')));
if ($bank === 'table') {
    $bank = 'tables';
} elseif ($bank === 'form') {
    $bank = 'forms';
}
if ($formsDesignSurface) {
    $bank = 'forms';
} elseif ($_SERVER['REQUEST_METHOD'] !== 'POST' && $bank === 'forms') {
    $redirectParams = [];
    foreach (['create', 'edit'] as $key) {
        if (isset($_GET[$key])) {
            $redirectParams[$key] = (string) $_GET[$key];
        }
    }
    myronRedirect(myronBuildAdminUrl('design.forms', $redirectParams));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $writeUser = $formsDesignSurface ? myronRequireDesignAccess(true) : myronRequireContentAccess(true);
    myronRequireCsrf($_POST['csrf_token'] ?? null);
    $caller = myronActionCallerContextForUser($writeUser);
    $action = (string) ($_POST['action'] ?? '');
    try {
        if ($action === 'tables.create') {
            $created = $service->create(myronMicTablePayloadFromPost($_POST), $caller);
            $table = is_array($created['table'] ?? null) ? $created['table'] : [];
            myronRedirectWithFlash(myronBuildAdminUrl('content.contentBanks', ['bank' => 'tables', 'edit' => (string) ($table['id'] ?? '')]), 'Table created.', 'success');
        } elseif ($action === 'tables.update') {
            $service->update((string) ($_POST['table_id'] ?? ''), myronMicTablePayloadFromPost($_POST), $caller);
            myronRedirectWithFlash(myronBuildAdminUrl('content.contentBanks', ['bank' => 'tables']), 'Table saved.', 'success');
        } elseif ($action === 'tables.delete') {
            $service->delete((string) ($_POST['table_id'] ?? ''));
            myronRedirectWithFlash(myronBuildAdminUrl('content.contentBanks', ['bank' => 'tables']), 'Table deleted.', 'success');
        } elseif ($action === 'tables.duplicate') {
            $duplicated = $service->duplicate((string) ($_POST['table_id'] ?? ''), $caller);
            $table = is_array($duplicated['table'] ?? null) ? $duplicated['table'] : [];
            myronRedirectWithFlash(myronBuildAdminUrl('content.contentBanks', ['bank' => 'tables', 'edit' => (string) ($table['id'] ?? '')]), 'Table duplicated.', 'success');
        } elseif ($action === 'forms.create') {
            $created = $formsService->create(myronMicFormPayloadFromPost($_POST), $caller);
            $form = is_array($created['form'] ?? null) ? $created['form'] : [];
            myronRedirectWithFlash(myronFormsSurfaceAdminUrl(['edit' => (string) ($form['id'] ?? '')]), 'Form created.', 'success');
        } elseif ($action === 'forms.update') {
            $formsService->update((string) ($_POST['form_id'] ?? ''), myronMicFormPayloadFromPost($_POST), $caller);
            myronRedirectWithFlash(myronFormsSurfaceAdminUrl(), 'Form saved.', 'success');
        } elseif ($action === 'forms.delete') {
            $formsService->delete((string) ($_POST['form_id'] ?? ''));
            myronRedirectWithFlash(myronFormsSurfaceAdminUrl(), 'Form deleted.', 'success');
        } elseif ($action === 'forms.duplicate') {
            $duplicated = $formsService->duplicate((string) ($_POST['form_id'] ?? ''), $caller);
            $form = is_array($duplicated['form'] ?? null) ? $duplicated['form'] : [];
            myronRedirectWithFlash(myronFormsSurfaceAdminUrl(['edit' => (string) ($form['id'] ?? '')]), 'Form duplicated.', 'success');
        } elseif ($action === 'forms.submission.delete') {
            $formsService->deleteSubmission((string) ($_POST['submission_id'] ?? ''));
            myronRedirectWithFlash(myronFormsSurfaceAdminUrl(['edit' => (string) ($_POST['form_id'] ?? '')]), 'Submission deleted.', 'success');
        }
    } catch (Throwable $exception) {
        myronRedirectWithFlash($formsDesignSurface || $bank === 'forms' ? myronFormsSurfaceAdminUrl() : myronBuildAdminUrl('content.contentBanks', ['bank' => $bank ?? 'tables']), $exception->getMessage(), 'error');
    }
}

$knownTypes = myronMicElementRegistry()->knownTypes();
$tables = $service->list(100, 0)['tables'] ?? [];
$forms = $formsService->list()['forms'] ?? [];
$notificationEmailOptions = myronNotificationEmailsRepository()->listAll(true);
$editId = trim((string) ($_GET['edit'] ?? ''));
$editing = $editId !== '' ? myronMicTableRepository()->findById($editId) : null;
$editingForm = $editId !== '' ? myronMicFormRepository()->findById($editId) : null;
$creating = (string) ($_GET['create'] ?? '') === '1';
$createFormTemplate = myronMicFormTemplateKeyFromRequest();

myronRenderAdminShellStart($currentUser, [
    'title' => $formsDesignSurface ? 'Forms' : 'Content Banks',
    'titleContext' => $formsDesignSurface ? 'Design' : 'Content',
    'activeItem' => $formsDesignSurface ? 'component-studio-forms' : 'content-banks',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      $formsDesignSurface
          ? ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')]
          : ['label' => 'Content', 'href' => myronBuildAdminUrl('content.pages')],
      $formsDesignSurface ? ['label' => 'Component Studio'] : ['label' => 'Content Banks'],
      ...($formsDesignSurface ? [['label' => 'Forms']] : []),
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title"><?= $formsDesignSurface ? 'Forms' : 'Content Banks' ?></h1>
    <?php if ($bank === 'forms'): ?>
    <a class="sg-button sg-button--primary" href="<?= myronEscape(myronFormsSurfaceAdminUrl(['create' => '1'])) ?>" data-mc-sidesheet-open="forms-edit-sheet">Create Form</a>
    <?php else: ?>
    <a class="sg-button sg-button--primary" href="<?= myronEscape(myronBuildAdminUrl('content.contentBanks', ['bank' => 'tables', 'create' => '1'])) ?>" data-mc-sidesheet-open="tables-edit-sheet">Create Table</a>
    <?php endif; ?>
  </div>
  <?php if ($formsDesignSurface): ?>
    <p class="mc-workspace__subtitle">Create and manage reusable Core forms for pages, sections, and public submission flows.</p>
  <?php endif; ?>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <?php if (!$formsDesignSurface): ?>
    <nav class="mc-content-banks__tabs" aria-label="Content bank tabs">
      <a class="sg-pill<?= $bank === 'tables' ? ' sg-pill--active' : '' ?>" href="<?= myronEscape(myronBuildAdminUrl('content.contentBanks', ['bank' => 'tables'])) ?>">Tables</a>
      <?php foreach ($knownTypes as $slug => $type): ?>
        <?php if (in_array($slug, ['table', 'form'], true) || ($type['bankSurface'] ?? 'none') === 'none') continue; ?>
        <a class="sg-pill<?= $bank === $slug ? ' sg-pill--active' : '' ?>" href="<?= myronEscape(myronBuildAdminUrl('content.contentBanks', ['bank' => $slug])) ?>"><?= myronEscape((string) ($type['label'] ?? $slug)) ?></a>
      <?php endforeach; ?>
    </nav>
    <?php endif; ?>

    <section class="sg-section mc-content-banks__tab-panel" id="bank-panel-forms"<?= $bank === 'forms' ? '' : ' hidden' ?>>
      <?php myronRenderFormsSummaryWidget(); ?>
      <?php if ($formsDesignSurface): ?>
      <section class="mc-forms-template-panel" aria-labelledby="mc-forms-template-title">
        <div>
          <h2 class="sg-section__title" id="mc-forms-template-title">Start with a form type</h2>
          <p class="sg-section__subtitle">Choose a safe starter shape, then tune fields, completion behavior, and notification routing.</p>
        </div>
        <div class="mc-forms-template-grid">
          <?php foreach (myronMicFormTemplateDefinitions() as $templateKey => $template): ?>
            <a class="mc-forms-template-card" href="<?= myronEscape(myronFormsSurfaceAdminUrl(['create' => '1', 'template' => $templateKey])) ?>">
              <span class="mc-forms-template-card__label"><?= myronEscape((string) $template['label']) ?></span>
              <span class="mc-forms-template-card__description"><?= myronEscape((string) $template['description']) ?></span>
              <span class="sg-pill"><?= count(is_array($template['fields'] ?? null) ? $template['fields'] : []) ?> fields</span>
            </a>
          <?php endforeach; ?>
        </div>
      </section>
      <?php endif; ?>
      <div class="mc-workspace__title-row">
        <h2 class="sg-section__title">Forms</h2>
        <span class="sg-pill"><?= myronEscape((string) count($forms)) ?> forms</span>
      </div>
      <table class="mc-tables-bank__grid">
        <thead><tr><th>Name</th><th>Type</th><th>Destination</th><th>Completion</th><th>Fields</th><th>Submissions</th><th>Usage</th><th>Actions</th></tr></thead>
        <tbody>
        <?php if ($forms === []): ?>
          <tr><td colspan="8">No reusable forms yet. Choose a form type above to create the first reusable form.</td></tr>
        <?php endif; ?>
        <?php foreach ($forms as $form): ?>
          <?php $formId = (string) ($form['id'] ?? ''); ?>
          <tr>
            <td>
              <strong><?= myronEscape((string) ($form['name'] ?? $formId)) ?></strong><br>
              <code>[mic-form-<?= myronEscape($formId) ?>]</code><br>
              <span class="myron-text myron-text--muted">Updated <?= myronEscape((string) ($form['updated_at'] ?? '')) ?></span>
            </td>
            <td><?= myronEscape(myronMicFormTemplateLabelForForm($form)) ?></td>
            <td><?= myronEscape(myronMicFormDestinationSummary($form, $notificationEmailOptions)) ?></td>
            <td><?= myronEscape(myronMicFormCompletionSummary($form)) ?></td>
            <td><?= count(is_array($form['fields'] ?? null) ? $form['fields'] : []) ?></td>
            <td><?= (int) ($form['submissionsCount'] ?? 0) ?></td>
            <td>Used on <?= (int) ($form['referencesCount'] ?? 0) ?> pages</td>
            <td>
              <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronFormsSurfaceAdminUrl(['edit' => $formId])) ?>" data-mc-sidesheet-open="forms-edit-sheet">Edit</a>
              <form method="post" action="<?= myronEscape(myronFormsSurfaceAdminUrl()) ?>" style="display:inline">
                <input type="hidden" name="csrf_token" value="<?= myronEscape(myronCsrfToken()) ?>">
                <input type="hidden" name="action" value="forms.duplicate">
                <input type="hidden" name="form_id" value="<?= myronEscape($formId) ?>">
                <button class="sg-button sg-button--secondary" type="submit">Duplicate</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </section>

    <?php if (!$formsDesignSurface): ?>
    <section class="sg-section mc-content-banks__tab-panel" id="bank-panel-tables"<?= $bank === 'tables' ? '' : ' hidden' ?>>
      <div class="mc-workspace__title-row">
        <h2 class="sg-section__title">Tables</h2>
        <span class="sg-pill"><?= myronEscape((string) count($tables)) ?> tables</span>
      </div>
      <table class="mc-tables-bank__grid">
        <thead><tr><th>Name</th><th>Updated</th><th>Usage</th><th>Actions</th></tr></thead>
        <tbody>
        <?php if ($tables === []): ?>
          <tr><td colspan="4">No reusable tables yet.</td></tr>
        <?php endif; ?>
        <?php foreach ($tables as $table): ?>
          <?php $tableId = (string) ($table['id'] ?? ''); ?>
          <tr>
            <td>
              <strong><?= myronEscape((string) ($table['name'] ?? $tableId)) ?></strong><br>
              <code>[mic-table-<?= myronEscape($tableId) ?>]</code>
            </td>
            <td><?= myronEscape((string) ($table['updated_at'] ?? '')) ?></td>
            <td>Used on <?= (int) ($table['referencesCount'] ?? 0) ?> pages</td>
            <td>
              <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('content.contentBanks', ['bank' => 'tables', 'edit' => $tableId])) ?>" data-mc-sidesheet-open="tables-edit-sheet">Edit</a>
              <form method="post" action="<?= myronEscape(myronBuildAdminUrl('content.contentBanks')) ?>" style="display:inline">
                <input type="hidden" name="csrf_token" value="<?= myronEscape(myronCsrfToken()) ?>">
                <input type="hidden" name="action" value="tables.duplicate">
                <input type="hidden" name="table_id" value="<?= myronEscape($tableId) ?>">
                <button class="sg-button sg-button--secondary" type="submit">Duplicate</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </section>
    <?php endif; ?>

    <?php if (!$formsDesignSurface): ?>
    <?php foreach ($knownTypes as $slug => $type): ?>
      <?php if ($slug === 'table' || ($type['bankSurface'] ?? 'none') !== 'picker') continue; ?>
      <section class="sg-section mc-content-banks__tab-panel" id="bank-panel-<?= myronEscape((string) $slug) ?>"<?= $bank === $slug ? '' : ' hidden' ?>>
        <h2 class="sg-section__title"><?= myronEscape((string) ($type['label'] ?? $slug)) ?></h2>
        <p class="sg-section__subtitle">Entries are managed in their parent surface.</p>
        <a class="sg-button sg-button--secondary" href="<?= myronEscape((string) ($type['parentSurfaceUrl'] ?? '#')) ?>">Manage in parent</a>
      </section>
    <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>

<?php
if (!$formsDesignSurface && ($creating || is_array($editing))) {
    $table = is_array($editing) ? $editing : [
        'id' => '',
        'name' => '',
        'description' => '',
        'caption' => '',
        'columns' => [['key' => 'column_1', 'label' => 'Column 1', 'alignment' => 'start']],
        'rows' => [['']],
        'header_style' => 'default',
        'responsive_strategy' => 'scroll',
    ];
    ob_start();
    myronRenderMicTableForm($table, $creating);
    myronRenderAdminSidesheet('tables-edit-sheet', $creating ? 'Create Table' : 'Edit Table', (string) ob_get_clean(), ['size' => 'lg']);
    echo '<button type="button" hidden data-mc-sidesheet-open="tables-edit-sheet" data-mc-content-bank-autopen>Open table editor</button>';
}
if ($bank === 'forms' && ($creating || is_array($editingForm))) {
    $form = is_array($editingForm) ? $editingForm : myronMicFormDefaultForTemplate($createFormTemplate);
    ob_start();
    myronRenderMicFormForm($form, $creating);
    myronRenderAdminSidesheet('forms-edit-sheet', $creating ? 'Create Form' : 'Edit Form', (string) ob_get_clean(), ['size' => 'lg']);
    echo '<button type="button" hidden data-mc-sidesheet-open="forms-edit-sheet" data-mc-content-bank-autopen>Open form editor</button>';
}
?>
<script>
document.addEventListener('DOMContentLoaded', function () {
  var trigger = document.querySelector('[data-mc-content-bank-autopen]');
  if (trigger) { trigger.click(); }
});
</script>
<?php myronRenderAdminShellEnd(); ?>

<?php
function myronMicTablePayloadFromPost(array $post): array
{
    return [
        'name' => (string) ($post['name'] ?? ''),
        'description' => (string) ($post['description'] ?? ''),
        'caption' => (string) ($post['caption'] ?? ''),
        'columns' => myronMicTableColumnsFromPost($post),
        'rows' => myronMicTableRowsFromPost($post),
        'header_style' => (string) ($post['header_style'] ?? 'default'),
        'responsive_strategy' => (string) ($post['responsive_strategy'] ?? 'scroll'),
    ];
}

function myronMicTableColumnsFromPost(array $post): array
{
    $labels = is_array($post['column_labels'] ?? null) ? $post['column_labels'] : [];
    $keys = is_array($post['column_keys'] ?? null) ? $post['column_keys'] : [];
    $alignments = is_array($post['column_alignments'] ?? null) ? $post['column_alignments'] : [];
    $columns = [];
    foreach ($labels as $index => $label) {
        if (trim((string) $label) === '') {
            continue;
        }
        $columns[] = [
            'key' => (string) ($keys[$index] ?? ''),
            'label' => (string) $label,
            'alignment' => (string) ($alignments[$index] ?? 'start'),
        ];
    }
    return $columns;
}

function myronMicTableRowsFromPost(array $post): array
{
    $rows = is_array($post['rows'] ?? null) ? $post['rows'] : [];
    return array_values(array_filter($rows, 'is_array'));
}

function myronRenderMicTableForm(array $table, bool $creating): void
{
    $columns = is_array($table['columns'] ?? null) ? $table['columns'] : [];
    $rows = is_array($table['rows'] ?? null) ? $table['rows'] : [];
    $references = (string) ($table['id'] ?? '') !== '' ? myronMicTableRepository()->findReferencingPages((string) $table['id']) : [];
    ?>
    <form method="post" action="<?= myronEscape(myronBuildAdminUrl('content.contentBanks')) ?>">
      <input type="hidden" name="csrf_token" value="<?= myronEscape(myronCsrfToken()) ?>">
      <input type="hidden" name="action" value="<?= $creating ? 'tables.create' : 'tables.update' ?>">
      <input type="hidden" name="table_id" value="<?= myronEscape((string) ($table['id'] ?? '')) ?>">
      <div class="sg-grid sg-grid--two">
        <label class="sg-field"><span class="sg-field__label">Name</span><input class="sg-field__control" name="name" required value="<?= myronEscape((string) ($table['name'] ?? '')) ?>"></label>
        <label class="sg-field"><span class="sg-field__label">Caption</span><input class="sg-field__control" name="caption" value="<?= myronEscape((string) ($table['caption'] ?? '')) ?>"></label>
        <label class="sg-field sg-field--full"><span class="sg-field__label">Description</span><textarea class="sg-field__control sg-field__control--textarea" name="description" rows="3"><?= myronEscape((string) ($table['description'] ?? '')) ?></textarea></label>
      </div>
      <h3 class="sg-section__title">Columns</h3>
      <?php if (count($columns) > 12): ?><p class="myron-text myron-text--muted">Soft warning: more than 12 columns.</p><?php endif; ?>
      <table class="mc-tables-bank__row-grid">
        <thead><tr><th>Label</th><th>Key</th><th>Alignment</th></tr></thead>
        <tbody>
        <?php for ($i = 0; $i < max(12, count($columns) + 2); $i++): $column = $columns[$i] ?? []; ?>
          <tr>
            <td><input class="sg-field__control" name="column_labels[]" value="<?= myronEscape((string) ($column['label'] ?? '')) ?>"></td>
            <td><input class="sg-field__control" name="column_keys[]" value="<?= myronEscape((string) ($column['key'] ?? '')) ?>"></td>
            <td><select class="sg-field__control" name="column_alignments[]"><?php foreach (['start','center','end'] as $align): ?><option value="<?= $align ?>"<?= ((string) ($column['alignment'] ?? 'start') === $align) ? ' selected' : '' ?>><?= $align ?></option><?php endforeach; ?></select></td>
          </tr>
        <?php endfor; ?>
        </tbody>
      </table>
      <h3 class="sg-section__title">Rows</h3>
      <?php if (count($rows) > 50): ?><p class="myron-text myron-text--muted">Soft warning: more than 50 rows.</p><?php endif; ?>
      <table class="mc-tables-bank__row-grid">
        <tbody>
        <?php for ($r = 0; $r < max(8, count($rows) + 2); $r++): ?>
          <tr>
          <?php for ($c = 0; $c < max(1, count($columns)); $c++): ?>
            <td class="mc-tables-bank__cell"><input class="sg-field__control" type="text" data-mc-richtext="true" data-mc-richtext-singleline="true" data-mc-richtext-mics="" name="rows[<?= $r ?>][]" value="<?= myronEscape((string) ($rows[$r][$c] ?? '')) ?>"></td>
          <?php endfor; ?>
          </tr>
        <?php endfor; ?>
        </tbody>
      </table>
      <div class="sg-grid sg-grid--two">
        <label class="sg-field"><span class="sg-field__label">Header style</span><select class="sg-field__control" name="header_style"><?php foreach (['default','emphatic','none'] as $style): ?><option value="<?= $style ?>"<?= ((string) ($table['header_style'] ?? 'default') === $style) ? ' selected' : '' ?>><?= $style ?></option><?php endforeach; ?></select></label>
        <label class="sg-field"><span class="sg-field__label">Responsive strategy</span><select class="sg-field__control" name="responsive_strategy"><?php foreach (['scroll','stack','auto'] as $strategy): ?><option value="<?= $strategy ?>"<?= ((string) ($table['responsive_strategy'] ?? 'scroll') === $strategy) ? ' selected' : '' ?>><?= $strategy ?></option><?php endforeach; ?></select></label>
      </div>
      <section class="sg-section">
        <h3 class="sg-section__title">Used on <?= count($references) ?> pages</h3>
        <?php foreach ($references as $reference): ?>
          <p><a href="<?= myronEscape(myronBuildAdminUrl('content.pageEditor', ['page' => (string) $reference['pageId']])) ?>"><?= myronEscape((string) $reference['pageTitle']) ?></a> <code><?= myronEscape((string) $reference['fieldPath']) ?></code></p>
        <?php endforeach; ?>
      </section>
      <div class="sg-card__actions">
        <button class="sg-button sg-button--primary" type="submit">Save</button>
      </div>
    </form>
    <?php if (!$creating): ?>
    <form method="post" action="<?= myronEscape(myronBuildAdminUrl('content.contentBanks')) ?>">
      <input type="hidden" name="csrf_token" value="<?= myronEscape(myronCsrfToken()) ?>">
      <input type="hidden" name="action" value="tables.delete">
      <input type="hidden" name="table_id" value="<?= myronEscape((string) ($table['id'] ?? '')) ?>">
      <button class="sg-button sg-button--danger" type="submit" onclick="return confirm('Delete this table? Referencing pages will show a missing marker.');">Delete</button>
    </form>
    <?php endif; ?>
    <?php
}

function myronMicFormPayloadFromPost(array $post): array
{
    return [
        'name' => (string) ($post['name'] ?? ''),
        'description' => (string) ($post['description'] ?? ''),
        'submit_button_label' => (string) ($post['submit_button_label'] ?? 'Submit'),
        'success_message' => (string) ($post['success_message'] ?? 'Thanks for submitting.'),
        'success_strategy' => (string) ($post['success_strategy'] ?? 'inline'),
        'success_redirect_url' => (string) ($post['success_redirect_url'] ?? ''),
        'notification_email_id' => (string) ($post['notification_email_id'] ?? ''),
        'embed_mode' => (string) ($post['embed_mode'] ?? 'inline'),
        'cta_label' => (string) ($post['cta_label'] ?? ''),
        'completion_routing' => [
            'template' => myronMicFormTemplateKey((string) ($post['form_template'] ?? 'generic')),
        ],
        'fields' => myronMicFormFieldsFromPost($post),
    ];
}

function myronMicFormFieldsFromPost(array $post): array
{
    $labels = is_array($post['field_labels'] ?? null) ? $post['field_labels'] : [];
    $keys = is_array($post['field_keys'] ?? null) ? $post['field_keys'] : [];
    $types = is_array($post['field_types'] ?? null) ? $post['field_types'] : [];
    $required = is_array($post['field_required'] ?? null) ? $post['field_required'] : [];
    $placeholders = is_array($post['field_placeholders'] ?? null) ? $post['field_placeholders'] : [];
    $helpText = is_array($post['field_help_text'] ?? null) ? $post['field_help_text'] : [];
    $options = is_array($post['field_options'] ?? null) ? $post['field_options'] : [];
    $fields = [];
    foreach ($labels as $index => $label) {
        if (trim((string) $label) === '') {
            continue;
        }
        $fieldOptions = [];
        foreach (preg_split('/\r\n|\r|\n/', (string) ($options[$index] ?? '')) ?: [] as $line) {
            $line = trim($line);
            if ($line !== '') {
                $fieldOptions[] = ['value' => myronNormalizeSlug($line), 'label' => $line];
            }
        }
        $fields[] = [
            'key' => (string) ($keys[$index] ?? ''),
            'label' => (string) $label,
            'type' => (string) ($types[$index] ?? 'text'),
            'required' => isset($required[$index]),
            'placeholder' => (string) ($placeholders[$index] ?? ''),
            'help_text' => (string) ($helpText[$index] ?? ''),
            'options' => $fieldOptions,
        ];
    }
    return $fields;
}

function myronRenderMicFormForm(array $form, bool $creating): void
{
    $fields = is_array($form['fields'] ?? null) ? $form['fields'] : [];
    $templateKey = myronMicFormTemplateKeyForForm($form);
    $notificationEmails = myronNotificationEmailsRepository()->listAll(true);
    $submissions = (string) ($form['id'] ?? '') !== '' ? myronMicFormSubmissionRepository()->listForForm((string) $form['id'], 50, 0) : [];
    $references = (string) ($form['id'] ?? '') !== '' ? myronMicFormRepository()->findReferencingPages((string) $form['id']) : [];
    ?>
    <form method="post" action="<?= myronEscape(myronFormsSurfaceAdminUrl()) ?>" class="mc-sidesheet-form mc-forms-editor">
      <input type="hidden" name="csrf_token" value="<?= myronEscape(myronCsrfToken()) ?>">
      <input type="hidden" name="bank" value="forms">
      <input type="hidden" name="action" value="<?= $creating ? 'forms.create' : 'forms.update' ?>">
      <input type="hidden" name="form_id" value="<?= myronEscape((string) ($form['id'] ?? '')) ?>">

      <section class="mc-sidesheet-form__section">
        <div class="mc-sidesheet-form__grid">
          <label class="sg-field">
            <span class="sg-field__label">Form Type</span>
            <select class="sg-field__control" name="form_template">
              <?php foreach (myronMicFormTemplateDefinitions() as $key => $template): ?>
                <option value="<?= myronEscape((string) $key) ?>"<?= $templateKey === (string) $key ? ' selected' : '' ?>><?= myronEscape((string) $template['label']) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
          <label class="sg-field">
            <span class="sg-field__label">Name</span>
            <input class="sg-field__control" name="name" required value="<?= myronEscape((string) ($form['name'] ?? '')) ?>">
          </label>
          <label class="sg-field">
            <span class="sg-field__label">Submit Button</span>
            <input class="sg-field__control" name="submit_button_label" value="<?= myronEscape((string) ($form['submit_button_label'] ?? 'Submit')) ?>">
          </label>
          <label class="sg-field">
            <span class="sg-field__label">Embed Mode</span>
            <select class="sg-field__control" name="embed_mode"><?php foreach (['inline','cta-modal'] as $mode): ?><option value="<?= $mode ?>"<?= ((string) ($form['embed_mode'] ?? 'inline') === $mode) ? ' selected' : '' ?>><?= $mode ?></option><?php endforeach; ?></select>
          </label>
          <label class="sg-field mc-sidesheet-form__span-full">
            <span class="sg-field__label">Description</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="description" rows="2"><?= myronEscape((string) ($form['description'] ?? '')) ?></textarea>
          </label>
        </div>
      </section>

      <section class="mc-sidesheet-form__section">
        <div class="mc-admin-form__section-header">
          <h3 class="mc-admin-form__section-title">Fields</h3>
          <p class="mc-admin-form__section-description">Blank rows are ignored. Keys may be left blank when a generated key is acceptable.</p>
        </div>
        <div class="mc-forms-field-list" data-mc-forms-builder>
          <?php for ($i = 0; $i < max(6, count($fields) + 2); $i++): $field = $fields[$i] ?? []; ?>
            <?php myronRenderMicFormFieldCard($field, $i); ?>
          <?php endfor; ?>
        </div>
      </section>

      <section class="mc-sidesheet-form__section">
        <div class="mc-admin-form__section-header">
          <h3 class="mc-admin-form__section-title">Completion and Routing</h3>
          <p class="mc-admin-form__section-description">Choose what the visitor sees after submission and which verified internal address receives the submission email.</p>
        </div>
        <div class="mc-forms-routing-summary" aria-label="Current completion and routing summary">
          <div class="mc-forms-routing-summary__item">
            <span class="mc-forms-routing-summary__label">Visitor Outcome</span>
            <strong><?= myronEscape(myronMicFormCompletionSummary($form)) ?></strong>
          </div>
          <div class="mc-forms-routing-summary__item">
            <span class="mc-forms-routing-summary__label">Email Destination</span>
            <strong><?= myronEscape(myronMicFormDestinationSummary($form, $notificationEmails)) ?></strong>
          </div>
          <div class="mc-forms-routing-summary__item">
            <span class="mc-forms-routing-summary__label">Submission Storage</span>
            <strong>Stored in MyronCMS</strong>
          </div>
        </div>
        <div class="mc-sidesheet-form__grid">
          <label class="sg-field">
            <span class="sg-field__label">Success Strategy</span>
            <select class="sg-field__control" name="success_strategy"><?php foreach (myronMicFormSuccessStrategyOptions() as $strategy => $label): ?><option value="<?= myronEscape($strategy) ?>"<?= ((string) ($form['success_strategy'] ?? 'inline') === $strategy) ? ' selected' : '' ?>><?= myronEscape($label) ?></option><?php endforeach; ?></select>
            <span class="sg-field__hint">Inline shows the success message. Redirect uses the URL below. Modal close is for CTA modal embeds.</span>
          </label>
          <label class="sg-field">
            <span class="sg-field__label">Redirect URL</span>
            <input class="sg-field__control" name="success_redirect_url" value="<?= myronEscape((string) ($form['success_redirect_url'] ?? '')) ?>">
            <span class="sg-field__hint">Only used when Success Strategy is redirect.</span>
          </label>
          <label class="sg-field">
            <span class="sg-field__label">CTA Label</span>
            <input class="sg-field__control" name="cta_label" value="<?= myronEscape((string) ($form['cta_label'] ?? '')) ?>">
            <span class="sg-field__hint">Used when this form is rendered as a button that opens a modal.</span>
          </label>
          <label class="sg-field">
            <span class="sg-field__label">Verified Destination</span>
            <select class="sg-field__control" name="notification_email_id"><option value="">Use default destination</option><option value="none">Store submission only</option><?php foreach ($notificationEmails as $email): ?><option value="<?= myronEscape((string) $email['id']) ?>"<?= ((string) ($form['notification_email_id'] ?? '') === (string) $email['id']) ? ' selected' : '' ?>><?= myronEscape((string) $email['label'] . ' <' . (string) $email['address'] . '>') ?></option><?php endforeach; ?></select>
            <span class="sg-field__hint">Specific destinations must be verified before forms can send submission emails to them.</span>
          </label>
          <label class="sg-field mc-sidesheet-form__span-full">
            <span class="sg-field__label">Success Message</span>
            <input class="sg-field__control" name="success_message" value="<?= myronEscape((string) ($form['success_message'] ?? 'Thanks for submitting.')) ?>">
          </label>
        </div>
        <?php if ($notificationEmails === []): ?><p class="sg-status sg-status--warning">No verified destinations yet. <a href="<?= myronEscape(myronBuildAdminUrl('administration.notificationEmails')) ?>">Add one in Administration</a> before routing submissions to a specific address.</p><?php endif; ?>
      </section>

      <div class="sg-card__actions"><button class="sg-button sg-button--primary" type="submit"><?= $creating ? 'Create Form' : 'Save Form' ?></button></div>
    </form>
    <?php if (!$creating): ?>
    <section class="sg-section">
      <div class="mc-workspace__title-row">
        <h3 class="sg-section__title">Submissions</h3>
        <span class="sg-pill"><?= count($submissions) ?> recent</span>
      </div>
      <?php myronRenderMicFormSubmissionsReview((string) ($form['id'] ?? ''), $submissions); ?>
    </section>
    <section class="sg-section">
      <h3 class="sg-section__title">Used on <?= count($references) ?> pages</h3>
      <?php foreach ($references as $reference): ?><p><a href="<?= myronEscape(myronBuildAdminUrl('content.pageEditor', ['page' => (string) $reference['pageId']])) ?>"><?= myronEscape((string) $reference['pageTitle']) ?></a> <code><?= myronEscape((string) $reference['fieldPath']) ?></code></p><?php endforeach; ?>
    </section>
    <form method="post" action="<?= myronEscape(myronFormsSurfaceAdminUrl()) ?>">
      <input type="hidden" name="csrf_token" value="<?= myronEscape(myronCsrfToken()) ?>">
      <input type="hidden" name="bank" value="forms">
      <input type="hidden" name="action" value="forms.delete">
      <input type="hidden" name="form_id" value="<?= myronEscape((string) ($form['id'] ?? '')) ?>">
      <button class="sg-button sg-button--danger" type="submit" onclick="return confirm('Delete this form? Referencing pages will show a missing marker.');">Delete</button>
    </form>
    <?php endif; ?>
    <?php
}

function myronRenderMicFormFieldCard(array $field, int $index): void
{
    $optionsText = '';
    foreach (is_array($field['options'] ?? null) ? $field['options'] : [] as $option) {
        $optionsText .= (string) ($option['label'] ?? $option['value'] ?? '') . "\n";
    }
    ?>
    <section class="mc-forms-field-card">
      <div class="mc-forms-field-card__header">
        <h4 class="mc-forms-field-card__title">Field <?= $index + 1 ?></h4>
        <label class="mc-forms-field-card__required"><input type="checkbox" name="field_required[<?= $index ?>]" value="1"<?= !empty($field['required']) ? ' checked' : '' ?>> Required</label>
      </div>
      <div class="mc-sidesheet-form__grid">
        <label class="sg-field">
          <span class="sg-field__label">Label</span>
          <input class="sg-field__control" name="field_labels[]" value="<?= myronEscape(strip_tags((string) ($field['label'] ?? ''))) ?>">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Key</span>
          <input class="sg-field__control" name="field_keys[]" value="<?= myronEscape((string) ($field['key'] ?? '')) ?>">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Type</span>
          <select class="sg-field__control" name="field_types[]"><?php foreach (['text','email','textarea','select','checkbox','radio','number','tel','url'] as $type): ?><option value="<?= $type ?>"<?= ((string) ($field['type'] ?? 'text') === $type) ? ' selected' : '' ?>><?= $type ?></option><?php endforeach; ?></select>
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Placeholder</span>
          <input class="sg-field__control" name="field_placeholders[]" value="<?= myronEscape((string) ($field['placeholder'] ?? '')) ?>">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Help Text</span>
          <input class="sg-field__control" name="field_help_text[]" value="<?= myronEscape((string) ($field['help_text'] ?? '')) ?>">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Options</span>
          <textarea class="sg-field__control" name="field_options[]" rows="2"><?= myronEscape(trim($optionsText)) ?></textarea>
        </label>
      </div>
    </section>
    <?php
}

function myronRenderMicFormSubmissionsReview(string $formId, array $submissions): void
{
    if ($submissions === []) {
        echo '<p class="sg-section__subtitle">No submissions yet.</p>';
        return;
    }
    ?>
    <table class="mc-tables-bank__grid mc-forms-submissions-table">
      <thead>
        <tr>
          <th>Submitted</th>
          <th>Preview</th>
          <th>Source</th>
          <th>Visitor</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($submissions as $submission): ?>
        <?php $fields = is_array($submission['fields'] ?? null) ? $submission['fields'] : []; ?>
        <tr>
          <td><?= myronEscape((string) ($submission['submitted_at'] ?? '')) ?></td>
          <td>
            <strong><?= myronEscape(myronFormSubmissionPreview($fields)) ?></strong>
            <details class="mc-forms-submission-detail">
              <summary>View fields</summary>
              <?php if ($fields === []): ?>
                <p class="sg-section__subtitle">No field values captured.</p>
              <?php else: ?>
                <dl class="mc-forms-submission-detail__fields">
                  <?php foreach ($fields as $key => $value): ?>
                    <div>
                      <dt><?= myronEscape((string) $key) ?></dt>
                      <dd><?= myronEscape(myronSubmissionFieldValuePreview($value)) ?></dd>
                    </div>
                  <?php endforeach; ?>
                </dl>
              <?php endif; ?>
            </details>
          </td>
          <td><?= myronEscape(myronSubmissionSourcePreview((string) ($submission['source_url'] ?? ''))) ?></td>
          <td><code><?= myronEscape(substr((string) ($submission['ip_hash'] ?? ''), 0, 12)) ?>...</code></td>
          <td>
            <form method="post" action="<?= myronEscape(myronFormsSurfaceAdminUrl(['edit' => $formId])) ?>" onsubmit="return confirm('Delete this submission?');">
              <input type="hidden" name="csrf_token" value="<?= myronEscape(myronCsrfToken()) ?>">
              <input type="hidden" name="bank" value="forms">
              <input type="hidden" name="action" value="forms.submission.delete">
              <input type="hidden" name="form_id" value="<?= myronEscape($formId) ?>">
              <input type="hidden" name="submission_id" value="<?= myronEscape((string) ($submission['id'] ?? '')) ?>">
              <button class="sg-button sg-button--secondary" type="submit">Delete</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
    <?php
}

function myronSubmissionFieldValuePreview(mixed $value): string
{
    if (is_array($value)) {
        return implode(', ', array_map(static fn (mixed $item): string => trim((string) $item), $value));
    }
    return trim((string) $value);
}

function myronSubmissionSourcePreview(string $sourceUrl): string
{
    $sourceUrl = trim($sourceUrl);
    if ($sourceUrl === '') {
        return '-';
    }
    $path = parse_url($sourceUrl, PHP_URL_PATH);
    $query = parse_url($sourceUrl, PHP_URL_QUERY);
    $preview = is_string($path) && $path !== '' ? $path : $sourceUrl;
    if (is_string($query) && $query !== '') {
        $preview .= '?' . $query;
    }
    return $preview;
}

function myronMicFormSuccessStrategyOptions(): array
{
    return [
        'inline' => 'Show inline success message',
        'redirect' => 'Redirect to another page',
        'modal-close' => 'Close modal after submit',
    ];
}

function myronMicFormTemplateKeyFromRequest(): string
{
    return myronMicFormTemplateKey((string) ($_GET['template'] ?? $_POST['form_template'] ?? 'generic'));
}

function myronMicFormTemplateKey(string $key): string
{
    $key = strtolower(trim($key));
    return array_key_exists($key, myronMicFormTemplateDefinitions()) ? $key : 'generic';
}

function myronMicFormTemplateDefinitions(): array
{
    return [
        'contact' => [
            'label' => 'Contact',
            'description' => 'Name, email, subject, and message for a general contact request.',
            'name' => 'Contact Form',
            'submit_button_label' => 'Send Message',
            'success_message' => 'Thanks. Your message has been sent.',
            'fields' => [
                ['key' => 'name', 'label' => 'Name', 'type' => 'text', 'required' => true, 'placeholder' => 'Your name', 'help_text' => '', 'options' => []],
                ['key' => 'email', 'label' => 'Email', 'type' => 'email', 'required' => true, 'placeholder' => 'you@example.com', 'help_text' => '', 'options' => []],
                ['key' => 'subject', 'label' => 'Subject', 'type' => 'text', 'required' => false, 'placeholder' => 'How can we help?', 'help_text' => '', 'options' => []],
                ['key' => 'message', 'label' => 'Message', 'type' => 'textarea', 'required' => true, 'placeholder' => 'Write your message', 'help_text' => '', 'options' => []],
            ],
        ],
        'subscribe' => [
            'label' => 'Subscribe',
            'description' => 'Email-first subscription capture with optional name.',
            'name' => 'Subscribe Form',
            'submit_button_label' => 'Subscribe',
            'success_message' => 'Thanks for subscribing.',
            'fields' => [
                ['key' => 'email', 'label' => 'Email', 'type' => 'email', 'required' => true, 'placeholder' => 'you@example.com', 'help_text' => '', 'options' => []],
                ['key' => 'name', 'label' => 'Name', 'type' => 'text', 'required' => false, 'placeholder' => 'Your name', 'help_text' => '', 'options' => []],
            ],
        ],
        'lead-inquiry' => [
            'label' => 'Lead / Inquiry',
            'description' => 'Qualification fields for sales, services, or intake requests.',
            'name' => 'Lead Inquiry Form',
            'submit_button_label' => 'Request Follow-up',
            'success_message' => 'Thanks. We will follow up soon.',
            'fields' => [
                ['key' => 'name', 'label' => 'Name', 'type' => 'text', 'required' => true, 'placeholder' => 'Your name', 'help_text' => '', 'options' => []],
                ['key' => 'email', 'label' => 'Email', 'type' => 'email', 'required' => true, 'placeholder' => 'you@example.com', 'help_text' => '', 'options' => []],
                ['key' => 'phone', 'label' => 'Phone', 'type' => 'tel', 'required' => false, 'placeholder' => '(555) 555-5555', 'help_text' => '', 'options' => []],
                ['key' => 'company', 'label' => 'Company', 'type' => 'text', 'required' => false, 'placeholder' => 'Organization name', 'help_text' => '', 'options' => []],
                ['key' => 'need', 'label' => 'What do you need?', 'type' => 'textarea', 'required' => true, 'placeholder' => 'Share the request or goal', 'help_text' => '', 'options' => []],
            ],
        ],
        'generic' => [
            'label' => 'Generic',
            'description' => 'A minimal flexible form for custom field composition.',
            'name' => 'Custom Form',
            'submit_button_label' => 'Submit',
            'success_message' => 'Thanks for submitting.',
            'fields' => [
                ['key' => 'email', 'label' => 'Email', 'type' => 'email', 'required' => true, 'placeholder' => 'you@example.com', 'help_text' => '', 'options' => []],
            ],
        ],
    ];
}

function myronMicFormDefaultForTemplate(string $templateKey): array
{
    $templateKey = myronMicFormTemplateKey($templateKey);
    $template = myronMicFormTemplateDefinitions()[$templateKey];
    return [
        'id' => '',
        'name' => (string) $template['name'],
        'description' => '',
        'submit_button_label' => (string) $template['submit_button_label'],
        'success_message' => (string) $template['success_message'],
        'fields' => is_array($template['fields'] ?? null) ? $template['fields'] : [],
        'success_strategy' => 'inline',
        'success_redirect_url' => '',
        'notification_email_id' => '',
        'embed_mode' => 'inline',
        'cta_label' => '',
        'completion_routing' => ['template' => $templateKey],
    ];
}

function myronMicFormTemplateKeyForForm(array $form): string
{
    $routing = is_array($form['completion_routing'] ?? null) ? $form['completion_routing'] : [];
    $key = myronMicFormTemplateKey((string) ($routing['template'] ?? ''));
    if (($routing['template'] ?? '') !== '') {
        return $key;
    }

    $fieldKeys = array_map(static fn (array $field): string => (string) ($field['key'] ?? ''), array_filter(is_array($form['fields'] ?? null) ? $form['fields'] : [], 'is_array'));
    if (in_array('company', $fieldKeys, true) || in_array('need', $fieldKeys, true)) {
        return 'lead-inquiry';
    }
    if (in_array('message', $fieldKeys, true)) {
        return 'contact';
    }
    if ($fieldKeys === ['email'] || $fieldKeys === ['email', 'name']) {
        return 'subscribe';
    }
    return 'generic';
}

function myronMicFormTemplateLabelForForm(array $form): string
{
    $key = myronMicFormTemplateKeyForForm($form);
    $definitions = myronMicFormTemplateDefinitions();
    return (string) ($definitions[$key]['label'] ?? 'Generic');
}

function myronMicFormDestinationSummary(array $form, array $notificationEmails): string
{
    $id = trim((string) ($form['notification_email_id'] ?? ''));
    if ($id === '') {
        return 'Default destination';
    }
    if ($id === 'none') {
        return 'Store only';
    }
    foreach ($notificationEmails as $email) {
        if ((string) ($email['id'] ?? '') === $id) {
            return (string) ($email['label'] ?? $email['address'] ?? 'Selected destination');
        }
    }
    return 'Specific destination';
}

function myronMicFormCompletionSummary(array $form): string
{
    $strategy = (string) ($form['success_strategy'] ?? 'inline');
    if ($strategy === 'redirect') {
        $url = trim((string) ($form['success_redirect_url'] ?? ''));
        return $url !== '' ? 'Redirect to ' . $url : 'Redirect';
    }
    if ($strategy === 'modal-close') {
        return 'Close modal';
    }
    return 'Inline message';
}

function myronFormsSurfaceAdminUrl(array $params = []): string
{
    if (defined('MYRON_FORMS_DESIGN_SURFACE') && MYRON_FORMS_DESIGN_SURFACE === true) {
        return myronBuildAdminUrl('design.forms', $params);
    }

    return myronBuildAdminUrl('content.contentBanks', array_merge(['bank' => 'forms'], $params));
}
