<?php /** @var array $form; @var ?array $customer; @var ?array $appointment; @var ?array $artist; @var array $clauses; @var array $conditions */
/* 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>
function waiverInitials(initial) {
  return {
    values: Object.assign({}, initial || {}),
    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;
      }
    },
    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>
<?php
$gi = (array)($form['general_info'] ?? []);
$med = (array)($form['medical_conditions'] ?? []);
$wi  = (array)($form['waiver_initials'] ?? []);
$locked = ($form['status'] ?? '') === 'SIGNED';
$saved  = isset($_GET['saved']);
$lockedFlash = isset($_GET['locked']);
$when = !empty($appointment['start_at'])
    ? (new DateTimeImmutable($appointment['start_at']))->format('l, F j · g:i A')
    : '';
?>
<section class="pt-32 pb-10 max-w-4xl mx-auto px-6">
  <div class="text-xs uppercase tracking-[0.3em] text-gold"><?= e(t('intake.public.kicker')) ?></div>
  <h1 class="mt-4 text-4xl md:text-5xl font-display"><?= e(t('intake.public.title')) ?></h1>
  <p class="mt-4 text-bone/60"><?= e(t('intake.public.subtitle')) ?></p>

  <?php if ($when): ?>
    <div class="mt-6 bg-ink/40 border border-gold/30 rounded-xl p-5 flex items-center gap-4">
      <div class="text-gold text-3xl">📅</div>
      <div class="flex-1">
        <div class="text-xs uppercase tracking-widest text-gold"><?= e(t('intake.public.your_appt')) ?></div>
        <div class="text-xl mt-1"><?= e($when) ?></div>
        <?php if ($artist): ?>
          <div class="text-sm text-bone/60 mt-1"><?= e(t('intake.public.with_artist')) ?> <span class="text-bone"><?= e($artist['display_name'] ?? '') ?></span></div>
        <?php endif; ?>
      </div>
    </div>
  <?php endif; ?>

  <?php if ($saved): ?>
    <div class="mt-4 rounded-md px-4 py-3 text-sm bg-gold/10 text-gold border border-gold/30">
      ✓ <?= e(t('intake.public.saved_flash')) ?>
    </div>
  <?php endif; ?>
  <?php if ($locked || $lockedFlash): ?>
    <div class="mt-4 rounded-md px-4 py-3 text-sm bg-gold/10 text-gold border border-gold/30">
      🔒 <?= e(t('intake.public.locked_flash')) ?>
    </div>
  <?php endif; ?>
</section>

<form method="POST" action="<?= url('/intake/' . e($form['resume_token'] ?? '')) ?>" class="max-w-4xl mx-auto px-6 pb-28 space-y-12">
  <?= csrf_field() ?>

  <!-- General info (customer can edit/confirm) -->
  <section>
    <h2 class="text-2xl font-display text-gold mb-1"><?= e(t('intake.general.title')) ?></h2>
    <p class="text-bone/60 text-sm mb-5"><?= e(t('intake.public.general_hint')) ?></p>
    <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" <?= $locked ? 'readonly' : 'required' ?>></div>
      <div><label class="label"><?= e(t('form.last_name')) ?> *</label><input name="last_name" value="<?= e($gi['last_name'] ?? '') ?>" class="input" <?= $locked ? 'readonly' : 'required' ?>></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" <?= $locked ? 'readonly' : '' ?>></div>
      <div><label class="label"><?= e(t('form.email')) ?> *</label><input type="email" name="email" value="<?= e($gi['email'] ?? '') ?>" class="input" <?= $locked ? 'readonly' : 'required' ?>></div>
      <div><label class="label"><?= e(t('form.phone')) ?> *</label><input name="phone" value="<?= e($gi['phone'] ?? '') ?>" class="input" <?= $locked ? 'readonly' : 'required' ?>></div>
      <div>
        <label class="label"><?= e(t('form.gender')) ?></label>
        <select name="gender" class="input" <?= $locked ? '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 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" <?= $locked ? 'readonly' : '' ?>></div>
      <div><label class="label"><?= e(t('form.city')) ?></label><input name="city" value="<?= e($gi['city'] ?? '') ?>" class="input" <?= $locked ? 'readonly' : '' ?>></div>
      <div><label class="label"><?= e(t('form.state')) ?></label><input name="state" value="<?= e($gi['state'] ?? '') ?>" class="input" <?= $locked ? 'readonly' : '' ?>></div>
      <div><label class="label"><?= e(t('form.zip')) ?></label><input name="zip" value="<?= e($gi['zip'] ?? '') ?>" class="input" <?= $locked ? 'readonly' : '' ?>></div>
      <div><label class="label"><?= e(t('form.ethnicity')) ?></label><input name="ethnicity" value="<?= e($gi['ethnicity'] ?? '') ?>" class="input" <?= $locked ? 'readonly' : '' ?>></div>
      <div><label class="label"><?= e(t('form.occupation')) ?></label><input name="occupation" value="<?= e($gi['occupation'] ?? '') ?>" class="input" <?= $locked ? '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" <?= $locked ? '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" <?= $locked ? 'readonly' : '' ?>></div>
      <div><label class="label"><?= e(t('form.relationship')) ?></label><input name="relationship" value="<?= e($gi['relationship'] ?? '') ?>" class="input" <?= $locked ? 'readonly' : '' ?>></div>
    </div>
  </section>

  <!-- Medical -->
  <section>
    <h2 class="text-2xl font-display text-gold mb-1"><?= e(t('intake.medical.title')) ?></h2>
    <p class="text-bone/60 text-sm mb-5"><?= 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 cursor-pointer">
          <input type="checkbox" name="medical_conditions[]" value="<?= e($cond) ?>" <?= in_array($cond, $med, true) ? 'checked' : '' ?> <?= $locked ? '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" <?= $locked ? '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' : '' ?> <?= $locked ? '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' : '' ?> <?= $locked ? '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" <?= $locked ? 'readonly' : '' ?>><?= e($form['medication_notes'] ?? '') ?></textarea></div>
  </section>

  <!-- Waiver -->
  <section x-data="waiverInitials(<?= htmlspecialchars(json_encode($wi), ENT_QUOTES) ?>)">
    <h2 class="text-2xl font-display text-gold mb-1"><?= e(t('intake.waiver.title')) ?></h2>
    <p class="text-bone/60 text-sm mb-5"><?= 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="___"
                 <?= $locked ? '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-2xl font-display text-gold mb-1"><?= e(t('intake.body.title')) ?></h2>
    <p class="text-bone/60 text-sm mb-5"><?= e(t('intake.public.body_hint')) ?></p>
    <div><label class="label"><?= e(t('intake.body.body_part')) ?></label><input name="body_part" value="<?= e($form['body_part'] ?? '') ?>" class="input" <?= $locked ? '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>
              <!-- img + canvas overlay stacked -->
              <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="<?= $locked ? '' : "addMark('" . $fig . "', \$event)" ?>"
                  class="absolute inset-0 w-full h-full <?= $locked ? '' : '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 (!$locked): ?>
                      <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 (!$locked): ?>
            <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>
  </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' : '' ?> <?= $locked ? 'disabled' : '' ?>>
      <span class="text-sm"><?= e(t('intake.aftercare_ack')) ?></span>
    </label>
  </section>

  <!-- Info box about in-person signing -->
  <div class="bg-gold/5 border border-gold/30 rounded-xl p-5 text-sm text-bone/80 leading-relaxed">
    <strong class="text-gold">✍️ <?= e(t('intake.public.sign_at_shop_title')) ?></strong><br>
    <?= e(t('intake.public.sign_at_shop_body')) ?>
  </div>

  <?php if (!$locked): ?>
    <div class="flex justify-end">
      <button type="submit" class="btn-gold text-base px-8 py-4"><?= e(t('intake.public.save_submit')) ?></button>
    </div>
  <?php endif; ?>
</form>
