<?php /** @var array $form; @var ?array $customer; @var array $clauses; @var array $conditions */
$gi = (array)($form['general_info'] ?? []);
$med = (array)($form['medical_conditions'] ?? []);
$wi = (array)($form['waiver_initials'] ?? []);
$isSigned = ($form['status'] ?? '') === 'SIGNED';
?>
<?php /* All Alpine component functions must be defined BEFORE Alpine processes x-data */ ?>
<script>var BODY_IMG_BASE = '<?= asset('img/body/') ?>';</script>
<script src="<?= asset('js/body-diagram.js') ?>"></script>
<script src="<?= asset('js/signature-pad.js') ?>"></script>
<script>
function waiverInitials(initial) {
  return {
    values: Object.assign({}, initial || {}),
    // Called on @input of any field: propagates that value to every empty sibling
    propagate(key) {
      const val = (this.values[key] || '').trim();
      if (!val) return;
      for (const k in this.values) {
        if (k !== key && !this.values[k]) this.values[k] = val;
      }
    },
    // Called on @focus: auto-fills this field if another already has a value
    autofill(key) {
      if (this.values[key] && this.values[key].trim().length) return;
      const first = Object.values(this.values).find(v => v && v.trim().length);
      if (first) this.values[key] = first;
    },
  };
}
window.waiverInitials = waiverInitials;
</script>
<div class="p-8 max-w-5xl">
  <a href="<?= url('/hub/forms') ?>" class="text-xs text-bone/50 hover:text-bone">← <?= e(t('hub.back_to_list')) ?></a>
  <div class="mt-2 flex items-start justify-between">
    <div>
      <div class="text-xs uppercase tracking-[0.3em] text-gold"><?= e(t('hub.form.kicker')) ?></div>
      <h1 class="mt-2 text-3xl font-display"><?= e(t('hub.form.title')) ?></h1>
      <div class="mt-1 text-xs text-bone/50"><?= e(t('form.status')) ?>: <span class="pill pill-<?= e(strtolower($form['status'] ?? 'draft')) ?>"><?= e($form['status'] ?? '') ?></span></div>
    </div>
  </div>

  <!-- ONE unified form. The Save button posts to /save; the Sign button uses formaction to post the SAME fields to /sign, preserving all data. -->
  <form id="intake-form" method="POST" action="<?= url('/hub/forms/' . e($form['id']) . '/save') ?>" class="mt-8 space-y-12">
    <?= csrf_field() ?>

    <!-- General info -->
    <section>
      <h2 class="text-xl font-display text-gold mb-4"><?= e(t('intake.general.title')) ?></h2>
      <div class="grid grid-cols-2 md:grid-cols-3 gap-4">
        <div><label class="label"><?= e(t('form.first_name')) ?></label><input name="first_name" value="<?= e($gi['first_name'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.last_name')) ?></label><input name="last_name" value="<?= e($gi['last_name'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.gender')) ?></label>
          <select name="gender" class="input" <?= $isSigned ? 'disabled' : '' ?>>
            <option value=""></option>
            <option value="M" <?= ($gi['gender'] ?? '') === 'M' ? 'selected' : '' ?>>M</option>
            <option value="F" <?= ($gi['gender'] ?? '') === 'F' ? 'selected' : '' ?>>F</option>
            <option value="X" <?= ($gi['gender'] ?? '') === 'X' ? 'selected' : '' ?>>X</option>
          </select>
        </div>
        <div><label class="label"><?= e(t('form.dob')) ?></label><input type="date" name="date_of_birth" value="<?= e($gi['date_of_birth'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.email')) ?></label><input type="email" name="email" value="<?= e($gi['email'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.phone')) ?></label><input name="phone" value="<?= e($gi['phone'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div class="col-span-2 md:col-span-3"><label class="label"><?= e(t('form.address')) ?></label><input name="address" value="<?= e($gi['address'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.city')) ?></label><input name="city" value="<?= e($gi['city'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.state')) ?></label><input name="state" value="<?= e($gi['state'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.zip')) ?></label><input name="zip" value="<?= e($gi['zip'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.ethnicity')) ?></label><input name="ethnicity" value="<?= e($gi['ethnicity'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.occupation')) ?></label><input name="occupation" value="<?= e($gi['occupation'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.sessions_needed')) ?></label><input name="sessions_needed" type="number" min="1" value="<?= e($gi['sessions_needed'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.emergency_name')) ?></label><input name="emergency_contact_name" value="<?= e($gi['emergency_contact_name'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.emergency_phone')) ?></label><input name="emergency_contact_phone" value="<?= e($gi['emergency_contact_phone'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div><label class="label"><?= e(t('form.relationship')) ?></label><input name="relationship" value="<?= e($gi['relationship'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div class="col-span-2 md:col-span-3"><label class="label"><?= e(t('form.referral_source')) ?></label><input name="referral_source" value="<?= e($gi['referral_source'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
      </div>
    </section>

    <!-- Medical -->
    <section>
      <h2 class="text-xl font-display text-gold mb-4"><?= e(t('intake.medical.title')) ?></h2>
      <p class="text-bone/60 text-sm mb-4"><?= e(t('intake.medical.hint')) ?></p>
      <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
        <?php foreach ($conditions as $cond): ?>
          <label class="flex items-center gap-2 p-3 border border-white/10 rounded-md hover:bg-white/5">
            <input type="checkbox" name="medical_conditions[]" value="<?= e($cond) ?>" <?= in_array($cond, $med, true) ? 'checked' : '' ?> <?= $isSigned ? 'disabled' : '' ?>>
            <span class="text-sm"><?= e(t('intake.medical.' . $cond)) ?></span>
          </label>
        <?php endforeach; ?>
      </div>
      <div class="grid md:grid-cols-2 gap-4 mt-4">
        <div><label class="label"><?= e(t('intake.medical.other')) ?></label><input name="medical_other" value="<?= e($form['medical_other'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
        <div>
          <label class="label"><?= e(t('intake.medical.on_medication')) ?></label>
          <div class="flex items-center gap-4 pt-2">
            <label class="flex items-center gap-2"><input type="radio" name="on_medication" value="1" <?= !empty($form['on_medication']) ? 'checked' : '' ?> <?= $isSigned ? 'disabled' : '' ?>> <?= e(t('common.yes')) ?></label>
            <label class="flex items-center gap-2"><input type="radio" name="on_medication" value="" <?= empty($form['on_medication']) ? 'checked' : '' ?> <?= $isSigned ? 'disabled' : '' ?>> <?= e(t('common.no')) ?></label>
          </div>
        </div>
      </div>
      <div class="mt-4"><label class="label"><?= e(t('intake.medical.medication_notes')) ?></label><textarea name="medication_notes" rows="2" class="input" <?= $isSigned ? 'readonly' : '' ?>><?= e($form['medication_notes'] ?? '') ?></textarea></div>
    </section>

    <!-- Waiver -->
    <section x-data="waiverInitials(<?= htmlspecialchars(json_encode($wi), ENT_QUOTES) ?>)">
      <h2 class="text-xl font-display text-gold mb-4"><?= e(t('intake.waiver.title')) ?></h2>
      <p class="text-bone/60 text-sm mb-4"><?= e(t('intake.waiver.hint')) ?></p>
      <div class="space-y-3">
        <?php foreach ($clauses as $c): ?>
          <div class="flex items-start gap-4 p-4 border border-white/10 rounded-md hover:bg-white/5">
            <input name="waiver_initials[<?= e($c) ?>]"
                   x-model="values['<?= e($c) ?>']"
                   @focus="autofill('<?= e($c) ?>')"
                   @input="propagate('<?= e($c) ?>')"
                   maxlength="5" placeholder="___"
                   <?= $isSigned ? 'readonly' : '' ?>
                   class="w-16 bg-ink border border-gold/30 rounded px-2 py-1 text-center text-gold uppercase tracking-widest focus:border-gold focus:bg-gold/10 transition">
            <p class="text-sm text-bone/70 leading-relaxed"><?= e(t('intake.waiver.' . $c)) ?></p>
          </div>
        <?php endforeach; ?>
      </div>
      <p class="text-xs text-bone/40 mt-3">💡 <?= e(t('intake.waiver.autofill_hint')) ?></p>
    </section>

    <!-- Body diagram -->
    <section>
      <h2 class="text-xl font-display text-gold mb-4"><?= e(t('intake.body.title')) ?></h2>
      <div><label class="label"><?= e(t('intake.body.body_part')) ?></label><input name="body_part" value="<?= e($form['body_part'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
      <div class="mt-4 bg-ink/40 border border-white/10 rounded-xl p-4">
        <p class="text-xs text-bone/50 uppercase tracking-widest mb-1"><?= e(t('intake.body.hint')) ?></p>
        <p class="text-xs text-bone/40 mb-4"><?= e(t('intake.body.multi_hint')) ?></p>
        <div x-data="bodyDiagram(<?= htmlspecialchars(json_encode($form['body_diagram_marks'] ?? []), ENT_QUOTES) ?>)" x-init="init()">

          <!-- 4 figure columns -->
          <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
            <?php foreach (['male_front','male_back','female_front','female_back'] as $fig): ?>
              <div class="bg-white/5 rounded-lg p-2">
                <div class="text-[10px] uppercase tracking-widest text-bone/40 mb-1">
                  <?= e(['male_front'=>'Male · Front','male_back'=>'Male · Back','female_front'=>'Female · Front','female_back'=>'Female · Back'][$fig]) ?>
                </div>
                <div class="relative w-full" style="padding-bottom:250%">
                  <img src="<?= asset('img/body/' . $fig . '.png') ?>"
                       class="absolute inset-0 w-full h-full object-contain pointer-events-none select-none">
                  <canvas
                    x-init="registerCanvas('<?= $fig ?>', $el)"
                    @click="<?= $isSigned ? '' : "addMark('" . $fig . "', \$event)" ?>"
                    class="absolute inset-0 w-full h-full <?= $isSigned ? '' : 'cursor-crosshair' ?>"
                    style="touch-action:none"></canvas>
                </div>
              </div>
            <?php endforeach; ?>
          </div>

          <!-- Mark list + controls -->
          <div class="mt-4 flex flex-wrap items-start gap-4">
            <div class="flex-1">
              <template x-if="marks.length === 0">
                <p class="text-xs text-bone/40 italic"><?= e(t('intake.body.no_marks')) ?></p>
              </template>
              <template x-if="marks.length > 0">
                <ul class="space-y-1">
                  <template x-for="(m, i) in marks" :key="i">
                    <li class="flex items-center gap-2 text-xs text-bone/70">
                      <span class="w-5 h-5 rounded-full bg-gold text-ink flex items-center justify-center font-bold text-[10px]" x-text="i+1"></span>
                      <span x-text="{ male_front:'Male Front', male_back:'Male Back', female_front:'Female Front', female_back:'Female Back' }[m.figure] || m.figure"></span>
                      <?php if (!$isSigned): ?>
                        <button type="button" @click="removeMark(i)" class="ml-1 text-bone/30 hover:text-red-400 text-[11px]">✕</button>
                      <?php endif; ?>
                    </li>
                  </template>
                </ul>
              </template>
            </div>
            <?php if (!$isSigned): ?>
              <button type="button" @click="clear()" x-show="marks.length > 0"
                      class="text-xs text-bone/40 hover:text-red-400 transition"><?= e(t('intake.body.clear_all')) ?></button>
            <?php endif; ?>
          </div>

          <input type="hidden" name="body_diagram_marks" :value="JSON.stringify(marks)">
        </div>
      </div>
      <div class="mt-4"><label class="label"><?= e(t('intake.body.pigments')) ?></label><input name="pigments" value="<?= e($form['pigments'] ?? '') ?>" class="input" <?= $isSigned ? 'readonly' : '' ?>></div>
    </section>

    <!-- Aftercare acknowledgement -->
    <section class="bg-ink/40 border border-white/10 rounded-xl p-5">
      <label class="flex items-start gap-3">
        <input type="checkbox" name="aftercare_acknowledged" value="1" <?= !empty($form['aftercare_acknowledged']) ? 'checked' : '' ?> <?= $isSigned ? 'disabled' : '' ?>>
        <span class="text-sm"><?= e(t('intake.aftercare_ack')) ?></span>
      </label>
    </section>

    <!-- Signature section -->
    <?php if ($isSigned): ?>
    <section class="bg-ink/40 border border-white/10 rounded-xl p-6">
      <h2 class="text-xl font-display text-gold mb-4"><?= e(t('intake.signature.title')) ?></h2>
      <div class="text-sm text-gold mb-4">✓ <?= e(t('intake.signature.already')) ?></div>
      <?php if (!empty($form['customer_signature_url'])): ?>
        <img src="<?= e(url($form['customer_signature_url'])) ?>" alt="Customer signature" class="bg-bone rounded p-2 max-w-sm">
      <?php endif; ?>
      <div class="text-xs text-bone/40 mt-3">
        <?= e(t('hub.form.signed_at')) ?> <?= e($form['signed_at'] ?? '') ?>
      </div>
    </section>
    <?php else: ?>
    <section class="bg-ink/40 border border-white/10 rounded-xl p-6"
             x-data="signaturePad()"
             x-init="$nextTick(() => { const c = $refs.sigCanvas; if (c && c.getBoundingClientRect) init(c); })">
      <h2 class="text-xl font-display text-gold mb-4"><?= e(t('intake.signature.title')) ?></h2>
      <p class="text-bone/60 text-sm mb-3"><?= e(t('intake.signature.hint')) ?></p>
      <canvas x-ref="sigCanvas" class="w-full h-40 bg-bone rounded cursor-crosshair block"></canvas>
      <button type="button" @click="clear()" class="mt-2 text-xs text-bone/50 hover:text-bone"><?= e(t('intake.signature.clear')) ?></button>
      <input type="hidden" name="signature_data" :value="dataUrl">

      <div class="mt-6 border-t border-white/10 pt-4">
        <p class="text-xs uppercase tracking-widest text-gold mb-2"><?= e(t('hub.pin.staff_confirmation')) ?></p>
        <div class="grid grid-cols-2 gap-3">
          <div><label class="label"><?= e(t('hub.pin.username')) ?></label><input name="username" class="input" autocomplete="off"></div>
          <div><label class="label"><?= e(t('hub.pin.pin')) ?></label><input name="pin" type="password" inputmode="numeric" maxlength="20" class="input text-center tracking-[0.5em]" autocomplete="off"></div>
        </div>
        <p class="text-xs text-bone/40 mt-2"><?= e(t('hub.form.sign_creds_hint')) ?></p>
      </div>

      <!-- Sticky action bar lives inside the signaturePad scope so @click="commit()" works -->
      <div class="mt-6 flex flex-wrap items-center gap-3 justify-end">
        <p class="text-xs text-bone/50 flex-1"><?= e(t('hub.form.action_hint')) ?></p>
        <!-- Save button is outside signaturePad scope, so we use a separate form submit via id -->
        <button type="button" onclick="document.getElementById('form-save-btn').click()" class="btn-ghost">💾 <?= e(t('hub.form.save')) ?></button>
        <button type="button"
                @click="commit(); $nextTick(() => document.getElementById('form-sign-btn').click())"
                class="btn-gold">🔒 <?= e(t('intake.signature.submit')) ?></button>
      </div>
    </section>

    <!-- Hidden submit triggers outside signaturePad scope -->
    <div class="hidden">
      <button id="form-save-btn" type="submit" form="intake-form"></button>
      <button id="form-sign-btn" type="submit" form="intake-form" formaction="<?= url('/hub/forms/' . e($form['id']) . '/sign') ?>"></button>
    </div>
    <?php endif; ?>
  </form>
</div>
