<?php
/**
 * @var \App\Model\Entity\Participant $participant
 * @var array<int,string>             $clinicians
 */
$this->assign('title', 'Participant');

$fullName = trim(($participant->first_name ?? '') . ' ' . ($participant->last_name ?? ''));
$selectedLoginIds = [];
if (!empty($participant->login)) {
    foreach ($participant->login as $u) {
        $selectedLoginIds[] = (int)$u->id;
    }
}

$fmtAddr = function($a){
    if (!$a) return '—';
    $l1 = trim((string)($a->address_line1 ?? ''));
    $l2 = trim((string)($a->address_line2 ?? ''));
    $city = trim((string)($a->city ?? ''));
    $reg  = trim((string)($a->region ?? ''));
    $pc   = trim((string)($a->postcode ?? ''));
    $cty  = trim((string)($a->country ?? ''));
    $rows = [];
    if ($l1 !== '' || $l2 !== '') $rows[] = h(implode(', ', array_filter([$l1, $l2])));
    if ($city !== '' || $reg !== '' || $pc !== '') $rows[] = h(trim($city.' '.$reg.' '.$pc));
    if ($cty !== '') $rows[] = h($cty);
    return $rows ? implode('<br>', $rows) : '—';
};

$addrList = $participant->participant_addresses ?? [];
?>
<section class="section">
    <div class="section-body">
        <div class="row">
            <div class="col-12 col-lg-3 mb-3">
                <?= $this->element('participants/sidebar', [
                    'participant' => $participant,
                    'active'      => 'profile',
                ]) ?>
            </div>

            <div class="col-12 col-lg-9">
                <?= $this->Flash->render() ?>
                <?= $this->Form->create($participant, ['id' => 'pForm', 'novalidate' => true]) ?>
                <input type="hidden" name="_section" id="sectionFlag" value="">

                <div class="card editable-card mb-4" id="card-personal" data-card="personal">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Name</h4>
                        <div class="card-actions">
                            <a href="#" class="btn btn-link btn-sm js-edit">Edit</a>
                            <a href="#" class="btn btn-link btn-sm js-cancel d-none">Cancel</a>
                            <button type="submit" class="btn btn-primary btn-sm js-save d-none" data-section="personal">Save</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="form-group col-md-4">
                                <?= $this->Form->control('first_name', [
                                    'label'    => 'First Name',
                                    'class'    => 'form-control',
                                    'required' => true,
                                    'disabled' => true,
                                ]) ?>
                            </div>

                            <div class="form-group col-md-4">
                                <?= $this->Form->control('middle_name', [
                                    'label'    => 'Middle Name',
                                    'class'    => 'form-control',
                                    'disabled' => true,
                                ]) ?>
                            </div>

                            <div class="form-group col-md-4">
                                <?= $this->Form->control('last_name', [
                                    'label'    => 'Last Name',
                                    'class'    => 'form-control',
                                    'disabled' => true,
                                ]) ?>
                            </div>

                            <div class="form-group col-md-4">
                                <?= $this->Form->control('preferred_name', [
                                    'label'       => 'Preferred Name',
                                    'class'       => 'form-control',
                                    'placeholder' => 'What they like to be called',
                                    'disabled'    => true,
                                ]) ?>
                            </div>

                            <div class="form-group col-md-4 ro-view">
                                <label>Date of Birth</label>
                                <div class="form-control-plaintext">
                                    <?= $participant->dob ? h($participant->dob->i18nFormat('yyyy-MM-dd')) : '—' ?>
                                </div>
                            </div>
                            <div class="form-group col-md-4 ro-view">
                                <label>Gender</label>
                                <div class="form-control-plaintext">
                                    <?= $participant->gender !== null && $participant->gender !== '' ? h($participant->gender) : '—' ?>
                                </div>
                            </div>
                            <div class="form-group col-md-4 ro-view">
                                <label>Review Date</label>
                                <div class="form-control-plaintext">
                                    <?= $participant->review_date ? h($participant->review_date->i18nFormat('yyyy-MM-dd')) : '—' ?>
                                </div>
                            </div>

                            <div class="form-group col-md-4 edit-view d-none">
                                <?= $this->Form->control('dob', [
                                    'label' => 'Date of Birth',
                                    'type'  => 'date',
                                    'class' => 'form-control',
                                    'max'   => date('Y-m-d'),
                                    'disabled' => true,
                                    'placeholder' => 'DD-MM-YYYY',
                                ]) ?>
                            </div>

                            <div class="form-group col-md-4 edit-view d-none">
                                <?php
                                $genderOptions = [
                                    ''               => 'Prefer not to say',
                                    'woman'          => 'Woman',
                                    'man'            => 'Man',
                                    'non-binary'     => 'Non-binary',
                                    'transgender'    => 'Transgender',
                                    'intersex'       => 'Intersex',
                                    'self_described' => 'Other (self-described)',
                                ];
                                $isSelf = ($participant->gender && !isset($genderOptions[$participant->gender]));
                                ?>
                                <label class="d-block">Gender</label>
                                <?= $this->Form->select('gender_select', $genderOptions, [
                                    'class'    => 'form-control',
                                    'value'    => $isSelf ? 'self_described' : ($participant->gender ?? ''),
                                    'disabled' => true,
                                ]) ?>
                                <div class="mt-2" id="genderOtherWrap_edit" style="<?= $isSelf ? '' : 'display:none' ?>">
                                    <?= $this->Form->text('gender_other', [
                                        'class'       => 'form-control',
                                        'placeholder' => 'Enter self-described gender',
                                        'value'       => $isSelf ? $participant->gender : '',
                                        'disabled'    => true,
                                    ]) ?>
                                    <small class="text-muted">If selected “Other (self-described)”, this text will be saved.</small>
                                </div>
                                <?= $this->Form->hidden('gender', [
                                    'value'    => $isSelf ? $participant->gender : ($participant->gender ?? ''),
                                    'disabled' => false,
                                ]) ?>
                            </div>

                            <div class="form-group col-md-4 edit-view d-none">
                                <?= $this->Form->control('review_date', [
                                    'label'    => 'Review Date',
                                    'type'     => 'date',
                                    'class'    => 'form-control',
                                    'disabled' => true,
                                    'placeholder' => 'DD-MM-YYYY',
                                ]) ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card editable-card mb-4" id="card-contact" data-card="contact">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Contact Detail</h4>
                        <div class="card-actions">
                            <a href="#" class="btn btn-link btn-sm js-edit">Edit</a>
                            <a href="#" class="btn btn-link btn-sm js-cancel d-none">Cancel</a>
                            <button type="submit" class="btn btn-primary btn-sm js-save d-none" data-section="contact">Save</button>
                        </div>
                    </div>

                    <div class="card-body">
                        <div class="ro-view">
                            <?php
                            $contacts = $participant->contacts ?? [];
                            if (!$contacts && ($participant->phone || $participant->email)) {
                                $contacts = [];
                                if ($participant->phone) $contacts[] = (object)['type'=>'phone','label'=>'self|mobile','value'=>$participant->phone,'is_primary'=>0,'is_emergency'=>0];
                                if ($participant->email) $contacts[] = (object)['type'=>'email','label'=>'self|personal','value'=>$participant->email,'is_primary'=>1,'is_emergency'=>0];
                            }

                            $relNames = [
                                'self'=>'Self','parent'=>'Parent','spouse'=>'Spouse/Partner','sibling'=>'Sibling',
                                'child'=>'Child','relative'=>'Relative','friend'=>'Friend','guardian'=>'Guardian',
                                'caregiver'=>'Caregiver','other'=>'Other'
                            ];
                            $tagNames = ['mobile'=>'Mobile','home'=>'Home','work'=>'Work','personal'=>'Personal','other'=>'Other'];

                            $groups = [];
                            foreach ($contacts as $c) {
                                $label = (string)($c->label ?? '');
                                [$relKey, $tagKey] = array_pad(explode('|', $label, 2), 2, '');
                                $relKey = $relKey ?: 'self';
                                $tagTxt = $tagNames[$tagKey] ?? ucfirst($tagKey);

                                $row = [
                                    'tag'      => $tagTxt,
                                    'value'    => (string)($c->value ?? ''),
                                    'primary'  => !empty($c->is_primary),
                                    'emergency'=> !empty($c->is_emergency),
                                ];

                                if (!isset($groups[$relKey])) {
                                    $groups[$relKey] = ['phones'=>[], 'emails'=>[], 'has_primary'=>false, 'has_emergency'=>false];
                                }
                                if (($c->type ?? '') === 'email') $groups[$relKey]['emails'][] = $row; else $groups[$relKey]['phones'][] = $row;

                                if ($row['primary'])   $groups[$relKey]['has_primary']   = true;
                                if ($row['emergency']) $groups[$relKey]['has_emergency'] = true;
                            }

                            if (!$groups):?>
                                <span class="text-muted">No contact info</span>
                            <?php else:
                                $i = 0;
                                foreach ($groups as $relKey => $bucket):
                                    $i++;
                                    $relTitle = $relKey === 'self' ? 'Self' : ($relNames[$relKey] ?? ucfirst($relKey));
                                    ?>
                                    <div class="contact-display-card mb-3">
                                        <div class="cdc-head">
                                            <div class="cdc-left">
                                                <div class="cdc-title">Contact <?= (int)$i ?></div>
                                                <div class="cdc-sub"><?= h($relTitle) ?></div>
                                            </div>
                                            <div>
                                                <?php if ($bucket['has_primary']): ?>
                                                    <span class="badge badge-primary">Primary</span>
                                                <?php endif; ?>
                                                <?php if ($bucket['has_emergency']): ?>
                                                    <span class="badge badge-danger ml-1">Emergency</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>

                                        <div class="cdc-body">
                                            <div class="cdc-block">
                                                <div class="cdc-block-title">Phone</div>
                                                <?php if (!empty($bucket['phones'])): ?>
                                                    <ul class="cdc-list">
                                                        <?php foreach ($bucket['phones'] as $row): ?>
                                                            <li>
                                                                <span class="chip chip-dark"><?= h($row['tag']) ?></span>
                                                                <span class="cdc-value text-monospace"><?= h($row['value']) ?></span>
                                                                <?php if (!empty($row['primary'])): ?>
                                                                    <span class="badge badge-primary ml-1">Primary</span>
                                                                <?php endif; ?>
                                                                <?php if (!empty($row['emergency'])): ?>
                                                                    <span class="badge badge-danger ml-1">Emergency</span>
                                                                <?php endif; ?>
                                                            </li>
                                                        <?php endforeach; ?>
                                                    </ul>
                                                <?php else: ?>
                                                    <div class="text-muted">—</div>
                                                <?php endif; ?>
                                            </div>

                                            <div class="cdc-block">
                                                <div class="cdc-block-title">Email</div>
                                                <?php if (!empty($bucket['emails'])): ?>
                                                    <ul class="cdc-list">
                                                        <?php foreach ($bucket['emails'] as $row): ?>
                                                            <li>
                                                                <span class="chip chip-dark"><?= h($row['tag']) ?></span>
                                                                <span class="cdc-value text-monospace"><?= h($row['value']) ?></span>
                                                                <?php if (!empty($row['primary'])): ?>
                                                                    <span class="badge badge-primary ml-1">Primary</span>
                                                                <?php endif; ?>
                                                                <?php if (!empty($row['emergency'])): ?>
                                                                    <span class="badge badge-danger ml-1">Emergency</span>
                                                                <?php endif; ?>
                                                            </li>
                                                        <?php endforeach; ?>
                                                    </ul>
                                                <?php else: ?>
                                                    <div class="text-muted">—</div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach;
                            endif; ?>
                        </div>

                        <div class="edit-view d-none">
                            <?php
                            $relOptions      = [
                                'self'=>'Self','parent'=>'Parent','spouse'=>'Spouse/Partner','sibling'=>'Sibling',
                                'child'=>'Child','relative'=>'Relative','friend'=>'Friend','guardian'=>'Guardian',
                                'caregiver'=>'Caregiver','other'=>'Other',
                            ];
                            $phoneTagOptions = ['mobile'=>'Mobile','home'=>'Home','work'=>'Work','personal'=>'Personal','other'=>'Other'];
                            $emailTagOptions = ['personal'=>'Personal','work'=>'Work','other'=>'Other'];

                            $rows = $participant->contacts ?? [];
                            if (!$rows) {
                                $rows = [(object)['id'=>null,'type'=>'email','label'=>'self|personal','value'=>'','is_primary'=>1,'is_emergency'=>0,'sort'=>10]];
                            }
                            ?>

                            <div id="contactsWrap">
                                <?php
                                $idx = 0;
                                $cardNo = 0;
                                foreach ($rows as $r):
                                    $rid   = $r->id ?? null;
                                    $type  = $r->type ?? 'phone';
                                    $label = (string)($r->label ?? 'self|mobile');
                                    [$rel,$tag] = array_pad(explode('|', $label, 2), 2, '');
                                    $rel      = $rel ?: 'self';
                                    $phoneTag = ($type==='phone') ? ($tag ?: 'mobile')   : 'mobile';
                                    $emailTag = ($type==='email') ? ($tag ?: 'personal') : 'personal';
                                    $valPhone = ($type==='phone') ? trim((string)($r->value ?? '')) : '';
                                    $valEmail = ($type==='email') ? trim((string)($r->value ?? '')) : '';
                                    $isPri    = (int)($r->is_primary ?? 0);
                                    $isEmerg  = (int)($r->is_emergency ?? 0);

                                    $idxPhone = $idx;
                                    $idxEmail = $idx + 1;
                                    $cardNo++;
                                    ?>
                                    <div class="contact-card border rounded p-2 mb-2" data-start="<?= $idxPhone ?>">
                                        <div class="card-mini-title js-card-title">Contact <?= (int)$cardNo ?></div>

                                        <div class="row-head">
                                            <div class="head-selects">
                                                <select class="form-control js-rel" style="min-width:150px">
                                                    <?php foreach ($relOptions as $rk=>$rv): ?>
                                                        <option value="<?= h($rk) ?>" <?= $rel===$rk?'selected':'' ?>><?= h($rv) ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>

                                            <div class="spacer"></div>

                                            <div class="row-primary">
                                                <input class="flag-control js-card-primary" type="radio" name="contacts[_primary_index]"
                                                       value="<?= $valEmail!=='' ? $idxEmail : $idxPhone ?>" <?= $isPri?'checked':'' ?>>
                                                <span class="flag-label">Primary</span>

                                                <label class="flag form-check ml-3 mb-0">
                                                    <input type="checkbox" class="flag-control js-emergency-toggle" id="c<?= $idxPhone ?>_emg" <?= $isEmerg?'checked':'' ?>>
                                                    <span class="flag-label">Emergency</span>
                                                </label>
                                            </div>

                                            <button type="button" class="btn btn-outline-danger btn-sm ml-2 js-card-del">Remove</button>
                                        </div>

                                        <input type="hidden" name="contacts[<?= $idxPhone ?>][type]" value="phone">
                                        <input type="hidden" name="contacts[<?= $idxPhone ?>][sort]"  value="<?= $idxPhone*10 ?>">
                                        <input type="hidden" name="contacts[<?= $idxPhone ?>][label]" class="js-hidden-label-phone" value="<?= h($rel.'|'.$phoneTag) ?>">
                                        <input type="hidden" name="contacts[<?= $idxPhone ?>][_delete]" value="0">
                                        <input type="hidden" name="contacts[<?= $idxPhone ?>][is_emergency]" class="js-emergency-hidden" value="<?= (int)$isEmerg ?>">
                                        <?php if ($type==='phone' && $rid): ?>
                                            <input type="hidden" name="contacts[<?= $idxPhone ?>][id]" value="<?= (int)$rid ?>">
                                        <?php endif; ?>

                                        <input type="hidden" name="contacts[<?= $idxEmail ?>][type]" value="email">
                                        <input type="hidden" name="contacts[<?= $idxEmail ?>][sort]"  value="<?= $idxEmail*10 ?>">
                                        <input type="hidden" name="contacts[<?= $idxEmail ?>][label]" class="js-hidden-label-email" value="<?= h($rel.'|'.$emailTag) ?>">
                                        <input type="hidden" name="contacts[<?= $idxEmail ?>][_delete]" value="0">
                                        <input type="hidden" name="contacts[<?= $idxEmail ?>][is_emergency]" class="js-emergency-hidden" value="<?= (int)$isEmerg ?>">
                                        <?php if ($type==='email' && $rid): ?>
                                            <input type="hidden" name="contacts[<?= $idxEmail ?>][id]" value="<?= (int)$rid ?>">
                                        <?php endif; ?>

                                        <div class="row-body">
                                            <div class="body-block mb-3">
                                                <label class="small text-muted d-block mb-1">Phone label</label>
                                                <select class="form-control js-tag-phone" style="min-width:140px">
                                                    <?php foreach ($phoneTagOptions as $tk=>$tv): ?>
                                                        <option value="<?= h($tk) ?>" <?= $phoneTag===$tk?'selected':'' ?>><?= h($tv) ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                                <div class="mt-2">
                                                    <input type="tel" class="form-control js-phone" placeholder="XXX XXX XXX"
                                                           value="<?= h(preg_replace('/^\+\d+\s*/','', $valPhone)) ?>">
                                                    <input type="hidden" class="js-phone-hidden" name="contacts[<?= $idxPhone ?>][value]" value="<?= h($valPhone) ?>">
                                                </div>
                                            </div>

                                            <div class="body-block">
                                                <label class="small text-muted d-block mb-1">Email label</label>
                                                <select class="form-control js-tag-email" style="min-width:140px">
                                                    <?php foreach ($emailTagOptions as $ek=>$ev): ?>
                                                        <option value="<?= h($ek) ?>" <?= $emailTag===$ek?'selected':'' ?>><?= h($ev) ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                                <div class="mt-2">
                                                    <input class="form-control js-email" type="email" name="contacts[<?= $idxEmail ?>][value]"
                                                           value="<?= h($valEmail) ?>" placeholder="name@example.com">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php
                                    $idx += 2;
                                endforeach; ?>
                            </div>

                            <div class="mt-2">
                                <button type="button" class="btn btn-soft btn-sm js-add-contact">+ Add contact</button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card editable-card mb-4" id="card-addresses" data-card="addresses">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Addresses</h4>
                        <div class="card-actions">
                            <a href="#" class="btn btn-link btn-sm js-edit">Edit</a>
                            <a href="#" class="btn btn-link btn-sm js-cancel d-none">Cancel</a>
                            <button type="submit" class="btn btn-primary btn-sm js-save d-none" data-section="addresses">Save</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="ro-view">
                            <?php if (!empty($addrList)): ?>
                                <div class="table-responsive">
                                    <table class="table table-sm mb-0">
                                        <thead><tr><th style="width:120px;">Type</th><th>Address</th><th style="width:180px;">Time Zone</th></tr></thead>
                                        <tbody>
                                        <?php foreach ($addrList as $a): ?>
                                            <tr>
                                                <td><span class="badge badge-light text-uppercase"><?= h($a->address_type ?? 'other') ?></span></td>
                                                <td><?= $this->Html->tag('div', $fmtAddr($a), ['escape'=>false]) ?></td>
                                                <td><?= h($a->time_zone ?? '') ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php else: ?>
                                <div class="text-muted">No addresses.</div>
                            <?php endif; ?>
                        </div>

                        <div class="edit-view d-none">
                            <?php
                            $auStates = ['ACT'=>'ACT','NSW'=>'NSW','NT'=>'NT','QLD'=>'QLD','SA'=>'SA','TAS'=>'TAS','VIC'=>'VIC','WA'=>'WA'];
                            $tz = [
                                'Australia/Melbourne'=>'Australia/Melbourne',
                                'Australia/Sydney'=>'Australia/Sydney',
                                'Australia/Brisbane'=>'Australia/Brisbane',
                                'Australia/Perth'=>'Australia/Perth',
                                'Australia/Adelaide'=>'Australia/Adelaide',
                                'Australia/Hobart'=>'Australia/Hobart',
                            ];
                            ?>
                            <div id="addrWrap">
                                <?php
                                $i = 0;
                                if (!empty($addrList)):
                                    foreach ($addrList as $a): ?>
                                        <div class="addr-card border rounded p-2 mb-2" data-index="<?= $i ?>">
                                            <?= $this->Form->hidden("participant_addresses.$i.id", ['value'=>$a->id]) ?>
                                            <div class="row align-items-center mb-2">
                                                <div class="col-md-4">
                                                    <?= $this->Form->control("participant_addresses.$i.address_type", [
                                                        'label'=>'Type','type'=>'select','class'=>'form-control',
                                                        'options'=>['home'=>'Home','work'=>'Work','other'=>'Other'],
                                                        'default'=>$a->address_type ?? 'home','disabled'=>true
                                                    ]) ?>
                                                </div>
                                                <div class="col text-right">
                                                    <button type="button" class="btn btn-outline-danger btn-sm js-del-addr">Remove</button>
                                                </div>
                                            </div>

                                            <?= $this->Form->control("participant_addresses.$i.address_line1", [
                                                'label'=>'Street Address','class'=>'form-control','value'=>$a->address_line1,'disabled'=>true
                                            ]) ?>
                                            <div class="mt-2">
                                                <?= $this->Form->control("participant_addresses.$i.address_line2", [
                                                    'label'=>'Address Line 2','class'=>'form-control','value'=>$a->address_line2,'disabled'=>true
                                                ]) ?>
                                            </div>

                                            <div class="form-row mt-2">
                                                <div class="col-md-4">
                                                    <?= $this->Form->control("participant_addresses.$i.city", [
                                                        'label'=>'City','class'=>'form-control','value'=>$a->city,'disabled'=>true
                                                    ]) ?>
                                                </div>
                                                <div class="col-md-4">
                                                    <?= $this->Form->control("participant_addresses.$i.region", [
                                                        'label'=>'State / Region','type'=>'select','options'=>$auStates,'empty'=>'Select State',
                                                        'class'=>'form-control','value'=>$a->region,'disabled'=>true
                                                    ]) ?>
                                                </div>
                                                <div class="col-md-4">
                                                    <?= $this->Form->control("participant_addresses.$i.postcode", [
                                                        'label'=>'Postcode','class'=>'form-control','value'=>$a->postcode,'disabled'=>true
                                                    ]) ?>
                                                </div>
                                            </div>

                                            <div class="form-row mt-2">
                                                <div class="col-md-6">
                                                    <?= $this->Form->control("participant_addresses.$i.country", [
                                                        'label'=>'Country','class'=>'form-control','value'=>$a->country ?: 'Australia','disabled'=>true
                                                    ]) ?>
                                                </div>
                                                <div class="col-md-6">
                                                    <?= $this->Form->control("participant_addresses.$i.time_zone", [
                                                        'label'=>'Time Zone','type'=>'select','options'=>$tz,'empty'=>'Select a time zone',
                                                        'class'=>'form-control','value'=>$a->time_zone,'disabled'=>true
                                                    ]) ?>
                                                </div>
                                            </div>
                                        </div>
                                        <?php $i++; endforeach;
                                else: ?>
                                    <div class="addr-card border rounded p-2 mb-2" data-index="0">
                                        <div class="row align-items-center mb-2">
                                            <div class="col-md-4">
                                                <?= $this->Form->control("participant_addresses.0.address_type", [
                                                    'label'=>'Type','type'=>'select','class'=>'form-control',
                                                    'options'=>['home'=>'Home','work'=>'Work','other'=>'Other'],
                                                    'default'=>'home','disabled'=>true
                                                ]) ?>
                                            </div>
                                            <div class="col text-right">
                                                <button type="button" class="btn btn-outline-danger btn-sm js-del-addr">Remove</button>
                                            </div>
                                        </div>

                                        <?= $this->Form->control("participant_addresses.0.address_line1", [
                                            'label'=>'Street Address','class'=>'form-control','disabled'=>true
                                        ]) ?>
                                        <div class="mt-2">
                                            <?= $this->Form->control("participant_addresses.0.address_line2", [
                                                'label'=>'Address Line 2','class'=>'form-control','disabled'=>true
                                            ]) ?>
                                        </div>

                                        <div class="form-row mt-2">
                                            <div class="col-md-4">
                                                <?= $this->Form->control("participant_addresses.0.city", [
                                                    'label'=>'City','class'=>'form-control','disabled'=>true
                                                ]) ?>
                                            </div>
                                            <div class="col-md-4">
                                                <?= $this->Form->control("participant_addresses.0.region", [
                                                    'label'=>'State / Region','type'=>'select','options'=>$auStates,'empty'=>'Select State',
                                                    'class'=>'form-control','disabled'=>true
                                                ]) ?>
                                            </div>
                                            <div class="col-md-4">
                                                <?= $this->Form->control("participant_addresses.0.postcode", [
                                                    'label'=>'Postcode','class'=>'form-control','disabled'=>true
                                                ]) ?>
                                            </div>
                                        </div>

                                        <div class="form-row mt-2">
                                            <div class="col-md-6">
                                                <?= $this->Form->control("participant_addresses.0.country", [
                                                    'label'=>'Country','class'=>'form-control','value'=>'Australia','disabled'=>true
                                                ]) ?>
                                            </div>
                                            <div class="col-md-6">
                                                <?= $this->Form->control("participant_addresses.0.time_zone", [
                                                    'label'=>'Time Zone','type'=>'select','options'=>$tz,'empty'=>'Select a time zone',
                                                    'class'=>'form-control','disabled'=>true
                                                ]) ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="mt-2">
                                <button type="button" class="btn btn-soft btn-sm js-add-addr">+ Add address</button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card editable-card mb-4" id="card-misc" data-card="misc">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Other Info</h4>
                        <div class="card-actions">
                            <a href="#" class="btn btn-link btn-sm js-edit">Edit</a>
                            <a href="#" class="btn btn-link btn-sm js-cancel d-none">Cancel</a>
                            <button type="submit" class="btn btn-primary btn-sm js-save d-none" data-section="misc">Save</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="form-group col-md-6">
                                <?= $this->Form->control('allergies', [
                                    'type'        => 'textarea',
                                    'label'       => 'Allergies (optional)',
                                    'class'       => 'form-control',
                                    'rows'        => 2,
                                    'placeholder' => 'e.g., Penicillin, peanuts',
                                    'disabled'    => true,
                                ]) ?>
                            </div>
                            <div class="form-group col-md-6">
                                <?= $this->Form->control('medicare_number', [
                                    'label'       => 'Medicare Number (optional)',
                                    'class'       => 'form-control',
                                    'placeholder' => 'e.g., 1234 56789 1',
                                    'pattern'     => '^[0-9 ]{4,20}$',
                                    'disabled'    => true,
                                ]) ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card editable-card mb-4" id="card-notes" data-card="notes">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Notes</h4>
                        <div class="card-actions">
                            <a href="#" class="btn btn-link btn-sm js-edit">Edit</a>
                            <a href="#" class="btn btn-link btn-sm js-cancel d-none">Cancel</a>
                            <button type="submit" class="btn btn-primary btn-sm js-save d-none" data-section="notes">Save</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="ro-view">
                            <?php if (!empty($participant->note)): ?>
                                <div class="small text-muted mb-1">Private note</div>
                                <div><?= nl2br(h($participant->note)) ?></div>
                            <?php else: ?>
                                <span class="text-muted">No notes.</span>
                            <?php endif; ?>
                        </div>

                        <div class="edit-view d-none">
                            <?= $this->Form->control('note', [
                                'type'  => 'textarea',
                                'rows'  => 5,
                                'label' => false,
                                'class' => 'form-control',
                                'disabled' => true,
                                'placeholder' => 'Add private notes about this participant…',
                            ]) ?>
                            <small class="form-text text-muted">Visible to staff only.</small>
                        </div>
                    </div>
                </div>

                <div class="card editable-card mb-4" id="card-clinicians" data-card="clinicians">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Assigned Clinicians</h4>
                        <div class="card-actions">
                            <a href="#" class="btn btn-link btn-sm js-edit">Edit</a>
                            <a href="#" class="btn btn-link btn-sm js-cancel d-none">Cancel</a>
                            <button type="submit" class="btn btn-primary btn-sm js-save d-none" data-section="clinicians">Save</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label>Select clinicians (multiple)</label>

                            <div class="ro-view">
                                <?php if (!empty($participant->login)): ?>
                                    <div class="token-list">
                                        <?php foreach ($participant->login as $u):
                                            $name  = trim(($u->first_name ?? '') . ' ' . ($u->last_name ?? ''));
                                            $label = $name !== '' ? $name : (string)$u->email;
                                            ?>
                                            <span class="token"><?= h($label) ?></span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <span class="text-muted">None assigned</span>
                                <?php endif; ?>
                            </div>

                            <div class="edit-view d-none">
                                <?= $this->Form->select('login._ids', $clinicians, [
                                    'multiple'         => true,
                                    'class'            => 'form-control select2',
                                    'data-placeholder' => 'Select clinicians',
                                    'value'            => $selectedLoginIds,
                                ]) ?>
                                <small class="form-text text-muted">Changes apply after saving.</small>
                            </div>
                        </div>
                    </div>
                </div>

                <?= $this->Form->end() ?>
            </div>
        </div>
    </div>
</section>

<style>
    .editable-card .card-header { background:#fff; }
    .editable-card.editing { border-color:#6c5ce7; box-shadow:0 0 0 3px rgba(108,92,231,.15); }
    .editable-card.editing .card-header { background:#f8f7ff; }

    .token-list .token{
        display:inline-block;
        background:#eef2ff;
        color:#3730a3;
        padding:4px 10px;
        border-radius:9999px;
        margin:0 6px 6px 0;
        font-size:12px;
    }

    .select2-container{ width:100% !important; }
    .select2-container .select2-dropdown{ z-index: 2050; }

    .btn-soft{ background:#eef2ff; color:#4f46e5; border:0; }
    .btn-soft:hover{ background:#e0e7ff; color:#4338ca; }

    .phone-input .iti{ width:100%; }
    .iti__country-list{ max-width:360px; }
    .phone-input .iti, .js-val-phone .iti{ width:100%; }

    .contact-card { padding:12px; }
    .contact-card .row-head{
        display:flex; align-items:center; gap:10px;
        padding-bottom:8px; margin-bottom:10px;
        border-bottom:1px dashed #e5e7eb;
    }
    .contact-card .head-selects{ display:flex; gap:8px; flex-wrap:wrap; }
    .contact-card .spacer{ flex:1; }
    .contact-card .row-primary{ display:flex; align-items:center; gap:12px; white-space:nowrap; }

    .card-mini-title{
        font-weight: 600;
        font-size: 13px;
        color: #6b7280;
        margin: 2px 0 8px;
    }

    .contact-display-card{
        border:1px solid #e5e7eb; border-radius:10px; background:#fafbff; padding:14px 14px 10px;
    }
    .contact-display-card + .contact-display-card{ margin-top:14px; }

    .cdc-head{
        display:flex; align-items:center; justify-content:space-between;
        border-bottom:1px dashed #e5e7eb; padding-bottom:10px; margin-bottom:10px;
    }
    .cdc-title{ font-weight:600; color:#374151; }
    .cdc-sub{ font-size:12px; color:#6b7280; margin-top:2px; }

    .cdc-body{ display:grid; grid-template-columns: 1fr 1fr; gap:14px; }
    @media (max-width: 768px){ .cdc-body{ grid-template-columns:1fr; } }

    .cdc-block-title{ font-size:12px; color:#6b7280; margin-bottom:6px; }
    .cdc-list{ list-style:none; padding:0; margin:0; }
    .cdc-list li{ padding:6px 8px; background:#fff; border:1px solid #eef0f6; border-radius:8px; display:flex; align-items:center; gap:8px; }
    .cdc-list li + li{ margin-top:6px; }
    .cdc-value{ word-break: break-all; }

    .chip{ display:inline-block; padding:3px 8px; border-radius:9999px; font-size:12px; line-height:1; }
    .chip-dark{ background:#2a2f45; color:#fff; }

    .addr-card .form-control[disabled], .addr-card select[disabled] { background:#fff; }

    .row-primary{
        display:flex; align-items:center; gap:18px;
    }

    .flag-control{
        width:18px; height:18px;
        accent-color:#4f46e5;
    }

    .row-primary .form-check .flag-control{
        accent-color:#ef4444;
    }

    .flag-label{
        margin-left:8px;
        font-size:14px;
        color:#6b7280;
        line-height:1;
        user-select:none;
    }

    .flag{
        display:inline-flex; align-items:center; gap:8px;
    }

    @supports not (accent-color: auto){
        .flag-control{ transform: translateY(1px); }
    }

</style>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<?php $this->start('scriptBottom'); ?>
<?= $this->Html->css('https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css') ?>
<?= $this->Html->script('https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.full.min.js') ?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@18.5.3/build/css/intlTelInput.css">
<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@18.5.3/build/js/intlTelInput.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@18.5.3/build/js/utils.js"></script>

<script>
    (function(){
        var $ = window.jQuery || null;

        function takeSnapshot(card){
            const data = {};
            card.querySelectorAll('[name]').forEach(function(el){
                if (el.type === 'checkbox' || el.type === 'radio') data[el.name] = el.checked ? '1':'0';
                else data[el.name] = el.value;
            });
            card.dataset.snapshot = JSON.stringify(data);
        }

        function restoreSnapshot(card){
            try{
                const data = JSON.parse(card.dataset.snapshot||'{}');
                card.querySelectorAll('[name]').forEach(function(el){
                    if (data.hasOwnProperty(el.name)){
                        if (el.type === 'checkbox' || el.type === 'radio') el.checked = (data[el.name] === '1');
                        else el.value = data[el.name];
                        el.dispatchEvent(new Event('change', {bubbles:true}));
                    }
                });
            }catch(e){}
        }

        function initSelect2In(card){
            if (!$ || !$.fn || !$.fn.select2) return;
            var $card = $(card);
            $card.find('select.select2').each(function(){
                var $el = $(this);
                if ($el.prop('disabled')) $el.prop('disabled', false);
                if ($el.data('select2')) $el.select2('destroy');
                $el.select2({
                    width:'100%', closeOnSelect:false, allowClear:true,
                    dropdownAutoWidth:true, dropdownParent:$card
                });
            });
        }

        function destroySelect2In(card){
            if (!$ || !$.fn || !$.fn.select2) return;
            $(card).find('select.select2').each(function(){
                if ($(this).data('select2')) $(this).select2('destroy');
                $(this).prop('disabled', true);
            });
        }

        function setEditing(card, on){
            var editBtn   = card.querySelector('.js-edit');
            var cancelBtn = card.querySelector('.js-cancel');
            var saveBtn   = card.querySelector('.js-save');

            card.classList.toggle('editing', on);
            if (editBtn)   editBtn.classList.toggle('d-none', on);
            if (cancelBtn) cancelBtn.classList.toggle('d-none', !on);
            if (saveBtn)   saveBtn.classList.toggle('d-none', !on);

            card.querySelectorAll('.ro-view').forEach(function(el){ el.classList.toggle('d-none', on); });
            card.querySelectorAll('.edit-view').forEach(function(el){ el.classList.toggle('d-none', !on); });

            card.querySelectorAll('input,select,textarea').forEach(function(el){
                if (on) el.removeAttribute('disabled'); else el.setAttribute('disabled','disabled');
            });

            if (on){
                takeSnapshot(card);
                requestAnimationFrame(function(){ initSelect2In(card); });
                var first = card.querySelector('input:not([type=hidden]), select, textarea');
                if (first) first.focus();
            } else {
                destroySelect2In(card);
            }
        }

        document.addEventListener('click', function(e){
            var btn;
            btn = e.target.closest('.js-edit');
            if (btn){ e.preventDefault(); setEditing(btn.closest('.editable-card'), true); return; }

            btn = e.target.closest('.js-cancel');
            if (btn){ e.preventDefault(); var card = btn.closest('.editable-card'); restoreSnapshot(card); setEditing(card, false); return; }

            btn = e.target.closest('.js-save');
            if (btn){
                var card = btn.closest('.editable-card');
                document.getElementById('sectionFlag').value = btn.getAttribute('data-section') || '';
                var inputs = card.querySelectorAll('input,select,textarea');
                for (var i=0;i<inputs.length;i++){
                    if (typeof inputs[i].reportValidity === 'function' && !inputs[i].reportValidity()) return;
                }
                if ((btn.getAttribute('data-section')||'') === 'addresses') {
                    renumberAddressInputs();
                }
                return;
            }
        });

        document.querySelectorAll('.editable-card').forEach(function(card){ setEditing(card, false); });

        var wrap = document.getElementById('contactsWrap');
        if(wrap){
            var PHONE_TAGS = {mobile:'Mobile',home:'Home',work:'Work',personal:'Personal',other:'Other'};
            var EMAIL_TAGS = {personal:'Personal',work:'Work',other:'Other'};

            function nextStart(){
                var cards = wrap.querySelectorAll('.contact-card');
                if (!cards.length) return 0;
                var last = cards[cards.length-1];
                return parseInt(last.dataset.start, 10) + 2;
            }

            function optionsHtml(map, selectedKey){
                var html = '';
                for (var k in map){ if (!map.hasOwnProperty(k)) continue;
                    html += '<option value="'+k+'"'+(k===selectedKey?' selected':'')+'>'+map[k]+'</option>';
                }
                return html;
            }

            function cardTpl(start){
                var idxPhone = start, idxEmail = start + 1;
                return (
                    '<div class="contact-card border rounded p-2 mb-2" data-start="'+start+'">'+
                    '<div class="card-mini-title js-card-title"></div>'+
                    '<div class="row-head">'+
                    '<div class="head-selects">'+
                    '<select class="form-control js-rel" style="min-width:150px">'+
                    '<option value="self" selected>Self</option>'+
                    '<option value="parent">Parent</option>'+
                    '<option value="spouse">Spouse/Partner</option>'+
                    '<option value="sibling">Sibling</option>'+
                    '<option value="child">Child</option>'+
                    '<option value="relative">Relative</option>'+
                    '<option value="friend">Friend</option>'+
                    '<option value="guardian">Guardian</option>'+
                    '<option value="caregiver">Caregiver</option>'+
                    '<option value="other">Other</option>'+
                    '</select>'+
                    '</div>'+
                    '<div class="spacer"></div>'+
                    '<div class="row-primary">'+
                    '<input class="flag-control js-card-primary" type="radio" name="contacts[_primary_index]" value="'+idxPhone+'">'+
                    '<span class="flag-label">Primary</span>'+
                    '<label class="flag form-check ml-3 mb-0">'+
                    '<input type="checkbox" class="flag-control js-emergency-toggle" id="c'+idxPhone+'_emg">'+
                    '<span class="flag-label">Emergency</span>'+
                    '</label>'+
                    '</div>'+
                    '</div>'+
                    '<button type="button" class="btn btn-outline-danger btn-sm ml-2 js-card-del">Remove</button>'+
                    '</div>'+

                    '<input type="hidden" name="contacts['+idxPhone+'][type]" value="phone">'+
                    '<input type="hidden" name="contacts['+idxPhone+'][sort]" value="'+(idxPhone*10)+'">'+
                    '<input type="hidden" name="contacts['+idxPhone+'][label]" class="js-hidden-label-phone" value="self|mobile">'+
                    '<input type="hidden" name="contacts['+idxPhone+'][_delete]" value="0">'+
                    '<input type="hidden" name="contacts['+idxPhone+'][is_emergency]" class="js-emergency-hidden" value="0">'+

                    '<input type="hidden" name="contacts['+idxEmail+'][type]" value="email">'+
                    '<input type="hidden" name="contacts['+idxEmail+'][sort]" value="'+(idxEmail*10)+'">'+
                    '<input type="hidden" name="contacts['+idxEmail+'][label]" class="js-hidden-label-email" value="self|personal">'+
                    '<input type="hidden" name="contacts['+idxEmail+'][_delete]" value="0">'+
                    '<input type="hidden" name="contacts['+idxEmail+'][is_emergency]" class="js-emergency-hidden" value="0">'+

                    '<div class="row-body">'+
                    '<div class="body-block mb-3">'+
                    '<label class="small text-muted d-block mb-1">Phone label</label>'+
                    '<select class="form-control js-tag-phone" style="min-width:140px">'+ optionsHtml(PHONE_TAGS, 'mobile') +'</select>'+
                    '<div class="mt-2">'+
                    '<input type="tel" class="form-control js-phone" placeholder="XXX XXX XXX">'+
                    '<input type="hidden" class="js-phone-hidden" name="contacts['+idxPhone+'][value]" value="">'+
                    '</div>'+
                    '</div>'+
                    '<div class="body-block">'+
                    '<label class="small text-muted d-block mb-1">Email label</label>'+
                    '<select class="form-control js-tag-email" style="min-width:140px">'+ optionsHtml(EMAIL_TAGS, 'personal') +'</select>'+
                    '<div class="mt-2">'+
                    '<input class="form-control js-email" type="email" name="contacts['+idxEmail+'][value]" placeholder="name@example.com">'+
                    '</div>'+
                    '</div>'+
                    '</div>'+
                    '</div>'
                );
            }

            function initPhonePicker(card){
                var input  = card.querySelector('.js-phone');
                var hidden = card.querySelector('.js-phone-hidden');
                if(!input || !hidden || !window.intlTelInput) return;

                var iti = window.intlTelInput(input, {
                    initialCountry: 'au',
                    separateDialCode: true,
                    nationalMode: false,
                    utilsScript: 'https://cdn.jsdelivr.net/npm/intl-tel-input@18.5.3/build/js/utils.js'
                });
                input._iti = iti;

                function sync(){
                    var e164 = iti.getNumber();
                    if(!e164){
                        var raw = (input.value||'').trim();
                        var dc  = '+' + (iti.getSelectedCountryData().dialCode||'');
                        e164 = raw ? (raw[0]==='+' ? raw : (dc+' '+raw)) : '';
                    }
                    hidden.value = e164;
                    updatePrimaryValue(card);
                }
                input.addEventListener('change', sync);
                input.addEventListener('blur',   sync);
            }

            function updatePrimaryValue(card){
                var start    = parseInt(card.dataset.start,10);
                var idxPhone = start;
                var idxEmail = start+1;
                var emailVal = (card.querySelector('.js-email')?.value||'').trim();
                var phoneVal = (card.querySelector('.js-phone-hidden')?.value||'').trim();
                var radio    = card.querySelector('.js-card-primary');
                if(!radio) return;
                if(emailVal){ radio.value = idxEmail; }
                else if(phoneVal){ radio.value = idxPhone; }
                else { radio.value = idxPhone; }
            }

            function syncLabels(card){
                var rel   = (card.querySelector('.js-rel')||{}).value || 'self';
                var pTag  = (card.querySelector('.js-tag-phone')||{}).value || 'mobile';
                var eTag  = (card.querySelector('.js-tag-email')||{}).value || 'personal';
                var hp    = card.querySelector('.js-hidden-label-phone');
                var he    = card.querySelector('.js-hidden-label-email');
                if(hp) hp.value = rel+'|'+pTag;
                if(he) he.value = rel+'|'+eTag;
            }

            function syncEmergency(card){
                var toggled = !!card.querySelector('.js-emergency-toggle')?.checked;
                card.querySelectorAll('.js-emergency-hidden').forEach(function(h){
                    h.value = toggled ? '1' : '0';
                });
            }

            function renumberCards(){
                var cards = Array.prototype.slice.call(wrap.querySelectorAll('.contact-card'))
                    .filter(function(c){ return c.style.display !== 'none' && !c.dataset.deleted; });
                cards.forEach(function(card, i){
                    var t = card.querySelector('.js-card-title');
                    if (t) t.textContent = 'Contact ' + (i + 1);
                });
            }

            function initCard(card){
                initPhonePicker(card);
                syncLabels(card);
                updatePrimaryValue(card);
                syncEmergency(card);

                ['change','input','blur'].forEach(function(ev){
                    card.addEventListener(ev, function(e){
                        if(e.target.matches('.js-rel, .js-tag-phone, .js-tag-email')) syncLabels(card);
                        if(e.target.matches('.js-email')) updatePrimaryValue(card);
                        if(e.target.matches('.js-emergency-toggle')) syncEmergency(card);
                    });
                });
            }

            wrap.querySelectorAll('.contact-card').forEach(initCard);
            renumberCards();

            document.addEventListener('click', function(e){
                var addBtn = e.target.closest('.js-add-contact');
                if(addBtn){
                    var start = nextStart();
                    wrap.insertAdjacentHTML('beforeend', cardTpl(start));
                    initCard(wrap.lastElementChild);
                    renumberCards();
                    return;
                }

                var delBtn = e.target.closest('.js-card-del');
                if(delBtn){
                    var card  = delBtn.closest('.contact-card');
                    if(!card) return;
                    var start = parseInt(card.dataset.start,10);
                    var hpId  = card.querySelector('input[name="contacts['+(start)+'][id]"]');
                    var heId  = card.querySelector('input[name="contacts['+(start+1)+'][id]"]');
                    if(hpId || heId){ card.style.display='none'; card.dataset.deleted='1'; }
                    else { card.remove(); }
                    renumberCards();
                }
            });

            var form = document.getElementById('pForm');
            if(form){
                form.addEventListener('submit', function(){
                    document.querySelectorAll('#card-contact .edit-view input, #card-contact .edit-view select')
                        .forEach(function(el){ el.removeAttribute('disabled'); });

                    wrap.querySelectorAll('.contact-card').forEach(function(card){
                        var phone = card.querySelector('.js-phone');
                        if (phone && phone._iti) phone.dispatchEvent(new Event('change', {bubbles:true}));
                        syncLabels(card);
                        updatePrimaryValue(card);
                        syncEmergency(card);
                    });
                });
            }
        }

        (function(){
            var wrap = document.getElementById('addrWrap');
            if (!wrap) return;

            var addrCardRoot = document.getElementById('card-addresses');

            function firstFreeType() {
                var used = {};
                document.querySelectorAll('#addrWrap select[name*="participant_addresses"][name$="[address_type]"]')
                    .forEach(function(sel){ used[sel.value] = true; });
                if (!used['home']) return 'home';
                if (!used['work']) return 'work';
                return 'other';
            }

            function enableAddrCardInputs(container){
                container.querySelectorAll('input,select,textarea')
                    .forEach(function(el){ el.removeAttribute('disabled'); });
            }

            function nextIndex(){
                var cards = wrap.querySelectorAll('.addr-card');
                if (!cards.length) return 0;
                var max = -1;
                cards.forEach(function(c){
                    var v = parseInt(c.dataset.index, 10);
                    if (!isNaN(v) && v > max) max = v;
                });
                return max + 1;
            }

            function tpl(i){
                var defType = firstFreeType();
                return ''+
                    '<div class="addr-card border rounded p-2 mb-2" data-index="'+i+'">'+
                    '<div class="row align-items-center mb-2">'+
                    '<div class="col-md-4">'+
                    '<div class="form-group">'+
                    '<label for="pa_'+i+'_type">Type</label>'+
                    '<select name="participant_addresses['+i+'][address_type]" id="pa_'+i+'_type" class="form-control" disabled>'+
                    '<option value="">Select type…</option>'+
                    '<option value="home"'+(defType==='home'?' selected':'')+'>Home</option>'+
                    '<option value="work"'+(defType==='work'?' selected':'')+'>Work</option>'+
                    '<option value="other"'+(defType==='other'?' selected':'')+'>Other</option>'+
                    '</select>'+
                    '</div>'+
                    '</div>'+
                    '<div class="col text-right">'+
                    '<button type="button" class="btn btn-outline-danger btn-sm js-del-addr">Remove</button>'+
                    '</div>'+
                    '</div>'+

                    '<div class="form-group">'+
                    '<label for="pa_'+i+'_l1">Street Address</label>'+
                    '<input name="participant_addresses['+i+'][address_line1]" id="pa_'+i+'_l1" class="form-control" disabled>'+
                    '</div>'+

                    '<div class="form-group mt-2">'+
                    '<label for="pa_'+i+'_l2">Address Line 2</label>'+
                    '<input name="participant_addresses['+i+'][address_line2]" id="pa_'+i+'_l2" class="form-control" disabled>'+
                    '</div>'+

                    '<div class="form-row mt-2">'+
                    '<div class="form-group col-md-4">'+
                    '<label for="pa_'+i+'_city">City</label>'+
                    '<input name="participant_addresses['+i+'][city]" id="pa_'+i+'_city" class="form-control" disabled>'+
                    '</div>'+
                    '<div class="form-group col-md-4">'+
                    '<label for="pa_'+i+'_region">State / Region</label>'+
                    '<select name="participant_addresses['+i+'][region]" id="pa_'+i+'_region" class="form-control" disabled>'+
                    '<option value="">Select State</option>'+
                    '<option value="ACT">ACT</option><option value="NSW">NSW</option><option value="NT">NT</option>'+
                    '<option value="QLD">QLD</option><option value="SA">SA</option><option value="TAS">TAS</option>'+
                    '<option value="VIC">VIC</option><option value="WA">WA</option>'+
                    '</select>'+
                    '</div>'+
                    '<div class="form-group col-md-4">'+
                    '<label for="pa_'+i+'_pc">Postcode</label>'+
                    '<input name="participant_addresses['+i+'][postcode]" id="pa_'+i+'_pc" class="form-control" disabled>'+
                    '</div>'+
                    '</div>'+

                    '<div class="form-row mt-2">'+
                    '<div class="form-group col-md-6">'+
                    '<label for="pa_'+i+'_country">Country</label>'+
                    '<input name="participant_addresses['+i+'][country]" id="pa_'+i+'_country" class="form-control" value="Australia" disabled>'+
                    '</div>'+
                    '<div class="form-group col-md-6">'+
                    '<label for="pa_'+i+'_tz">Time Zone</label>'+
                    '<select name="participant_addresses['+i+'][time_zone]" id="pa_'+i+'_tz" class="form-control" disabled>'+
                    '<option value="">Select a time zone</option>'+
                    '<option value="Australia/Melbourne">Australia/Melbourne</option>'+
                    '<option value="Australia/Sydney">Australia/Sydney</option>'+
                    '<option value="Australia/Brisbane">Australia/Brisbane</option>'+
                    '<option value="Australia/Perth">Australia/Perth</option>'+
                    '<option value="Australia/Adelaide">Australia/Adelaide</option>'+
                    '<option value="Australia/Hobart">Australia/Hobart</option>'+
                    '</select>'+
                    '</div>'+
                    '</div>'+
                    '</div>';
            }

            document.addEventListener('click', function(e){
                var add = e.target.closest('.js-add-addr');
                if (add){
                    wrap.insertAdjacentHTML('beforeend', tpl(nextIndex()));
                    var newCard = wrap.lastElementChild;
                    if (addrCardRoot && addrCardRoot.classList.contains('editing')) {
                        (function(container){
                            container.querySelectorAll('input,select,textarea')
                                .forEach(function(el){ el.removeAttribute('disabled'); });
                        })(newCard);
                    }
                    return;
                }
                var del = e.target.closest('.js-del-addr');
                if (del){
                    var card = del.closest('.addr-card');
                    if (!card) return;

                    var hid = card.querySelector('input[name^="participant_addresses["][name$="[id]"]');
                    if (hid && hid.value) {
                        var delInput = card.querySelector('input[name^="participant_addresses."][name$="[_delete]"]');
                        if (!delInput) {
                            delInput = document.createElement('input');
                            delInput.type = 'hidden';
                            delInput.name = hid.name.replace(/\[id\]$/, '[_delete]');
                            card.appendChild(delInput);
                        }
                        delInput.value = '1';
                        card.style.display = 'none';
                    } else {
                        card.remove();
                    }
                    return;
                }
            });

            function renumber(){
                var cards = wrap.querySelectorAll('.addr-card');
                var i = 0;
                cards.forEach(function(card){
                    var old = parseInt(card.dataset.index,10);
                    if (old === i){ i++; return; }
                    card.querySelectorAll('input,select,textarea,label').forEach(function(el){
                        if (el.name) el.name = el.name.replace(/participant_addresses\[\d+\]/, 'participant_addresses['+i+']');
                        if (el.id)   el.id   = el.id.replace(/pa_\d+_/g, 'pa_'+i+'_');
                        if (el.htmlFor) el.htmlFor = el.htmlFor.replace(/pa_\d+_/g, 'pa_'+i+'_');
                    });
                    card.dataset.index = i;
                    i++;
                });
            }
            window.renumberAddressInputs = renumber;

            var form = document.getElementById('pForm');
            if(form){
                form.addEventListener('submit', function(){
                    var contactCard = document.getElementById('card-contact');
                    if (contactCard && contactCard.classList.contains('editing')) {
                        document.querySelectorAll('#card-contact .edit-view input, #card-contact .edit-view select')
                            .forEach(function(el){ el.removeAttribute('disabled'); });

                        wrap.querySelectorAll('.contact-card').forEach(function(card){
                            var phone = card.querySelector('.js-phone');
                            if (phone && phone._iti) phone.dispatchEvent(new Event('change', {bubbles:true}));
                        });
                    }
                });
            }

        })();
    })();
    (function(){
        var dob2 = document.querySelector('#card-personal input[name="dob"]');
        if (dob2) {
            var today = new Date().toISOString().slice(0,10);
            dob2.setAttribute('max', today);
        }

        (function bindGenderEdit(){
            var root = document.getElementById('card-personal');
            if (!root) return;
            var sel  = root.querySelector('select[name="gender_select"]');
            var hid  = root.querySelector('input[name="gender"]');
            var wrap = root.querySelector('#genderOtherWrap_edit');
            var txt  = root.querySelector('input[name="gender_other"]');

            if (!sel || !hid) return;

            function sync(){
                if (sel.value === 'self_described') {
                    wrap && (wrap.style.display = '');
                    if (txt) hid.value = txt.value.trim();
                } else {
                    wrap && (wrap.style.display = 'none');
                    hid.value = sel.value;
                }
            }
            sel.addEventListener('change', sync);
            if (txt) txt.addEventListener('input', sync);

            var form = document.getElementById('pForm');
            if (form) {
                form.addEventListener('submit', sync);
            }
            sync();
        })();
    })();
    (function(){
        if (!window.flatpickr) return;

        flatpickr.localize(flatpickr.l10ns.en);

        flatpickr('input[name="dob"]', {
            dateFormat: "Y-m-d",
            altInput: true,
            altFormat: "d-m-Y",
            allowInput: true,
            maxDate: "today"
        });

        flatpickr('input[name="review_date"]', {
            dateFormat: "Y-m-d",
            altInput: true,
            altFormat: "d-m-Y",
            allowInput: true
        });
    })();
</script>
<?php $this->end(); ?>
