<?php
/** @var array $appt; @var ?array $customer; @var ?array $artist; @var ?array $form; @var array $artists */
$status   = $appt['status'] ?? 'PENDING';
$done     = in_array($status, ['COMPLETED', 'CANCELED'], true);
$custName = trim(($customer['first_name'] ?? '') . ' ' . ($customer['last_name'] ?? ''));
$when     = !empty($appt['start_at']) ? new DateTimeImmutable($appt['start_at']) : null;
?>
<div class="p-5 md:p-8 max-w-5xl">
  <a href="<?= url('/hub/appointments') ?>" class="text-xs text-bone/40 hover:text-bone flex items-center gap-1 mb-6">
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 18l-6-6 6-6"/></svg>
    <?= e(t('hub.back_to_list')) ?>
  </a>

  <!-- ════════════════════════════════════════════════════════════════
       TOP BANNER — status + key info at a glance
       ════════════════════════════════════════════════════════════════ -->
  <div class="bg-gradient-to-r from-white/[0.03] to-transparent border border-white/5 rounded-2xl p-6 mb-6">
    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
      <div>
        <div class="flex items-center gap-3 mb-2">
          <span class="pill pill-<?= e(strtolower($status)) ?>"><?= e(t('appt.status.' . strtolower($status))) ?></span>
          <span class="text-bone/30 text-[10px] uppercase tracking-widest"><?= e($appt['source'] ?? '') ?></span>
        </div>
        <h1 class="text-2xl md:text-3xl font-display"><?= e($custName ?: t('hub.appointment.no_customer')) ?></h1>
      </div>
      <?php if ($when): ?>
        <div class="text-right shrink-0">
          <div class="text-2xl font-display text-gold"><?= e($when->format('g:i A')) ?></div>
          <div class="text-sm text-bone/50"><?= e($when->format('l, F j, Y')) ?></div>
        </div>
      <?php endif; ?>
    </div>

    <!-- Status trail — approved by / canceled by / completed by -->
    <?php if ($status === 'APPROVED' && !empty($appt['approved_by_name'])): ?>
      <div class="mt-4 pt-3 border-t border-white/5 flex items-center gap-2 text-xs text-bone/40">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#4ade80" stroke-width="2"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
        <span><?= e(t('hub.appointment.approved_by')) ?>: <span class="text-bone/60 font-medium"><?= e($appt['approved_by_name']) ?></span></span>
        <?php if (!empty($appt['approved_at'])): ?>
          <span class="text-bone/20">·</span>
          <span><?= e((new DateTimeImmutable($appt['approved_at']))->format('M j, Y · g:i A')) ?></span>
        <?php endif; ?>
      </div>
    <?php endif; ?>
    <?php if ($status === 'COMPLETED' && !empty($appt['completed_by_name'])): ?>
      <div class="mt-4 pt-3 border-t border-white/5 flex items-center gap-2 text-xs text-bone/40">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#4ade80" stroke-width="2"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
        <span><?= e(t('hub.appointment.completed_by')) ?>: <span class="text-bone/60 font-medium"><?= e($appt['completed_by_name']) ?></span></span>
        <?php if (!empty($appt['completed_at'])): ?>
          <span class="text-bone/20">·</span>
          <span><?= e((new DateTimeImmutable($appt['completed_at']))->format('M j, Y · g:i A')) ?></span>
        <?php endif; ?>
      </div>
    <?php endif; ?>
    <?php if ($status === 'CANCELED' && !empty($appt['canceled_by_name'])): ?>
      <div class="mt-4 pt-3 border-t border-white/5 space-y-1">
        <div class="flex items-center gap-2 text-xs text-red-400/70">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#f87171" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
          <span><?= e(t('hub.appointment.canceled_by')) ?>: <span class="font-medium"><?= e($appt['canceled_by_name']) ?></span></span>
          <?php if (!empty($appt['canceled_at'])): ?>
            <span class="text-bone/20">·</span>
            <span class="text-bone/30"><?= e((new DateTimeImmutable($appt['canceled_at']))->format('M j, Y · g:i A')) ?></span>
          <?php endif; ?>
        </div>
        <?php if (!empty($appt['cancel_reason'])): ?>
          <div class="text-xs text-bone/40 italic pl-5">"<?= e($appt['cancel_reason']) ?>"</div>
        <?php endif; ?>
      </div>
    <?php endif; ?>
  </div>

  <!-- ════════════════════════════════════════════════════════════════
       MAIN GRID — all info organized in one view
       ════════════════════════════════════════════════════════════════ -->
  <div class="grid md:grid-cols-3 gap-4 mb-6">

    <!-- Col 1: Appointment details -->
    <div class="bg-white/[0.02] border border-white/5 rounded-2xl p-5 space-y-4">
      <div class="text-[10px] uppercase tracking-[0.2em] text-gold font-medium"><?= e(t('hub.appointment.details')) ?></div>

      <div>
        <div class="text-[10px] uppercase tracking-wider text-bone/30 mb-0.5"><?= e(t('hub.appointment.when')) ?></div>
        <?php if ($when): ?>
          <div class="text-base font-medium"><?= e($when->format('l, F j')) ?></div>
          <div class="text-sm text-bone/50"><?= e($when->format('g:i A')) ?></div>
        <?php else: ?>
          <div class="text-bone/30">—</div>
        <?php endif; ?>
      </div>

      <div>
        <div class="text-[10px] uppercase tracking-wider text-bone/30 mb-0.5"><?= e(t('hub.appointment.artist')) ?></div>
        <div class="text-sm"><?= e($artist['display_name'] ?? t('booking.no_preference')) ?></div>
      </div>

      <div>
        <div class="text-[10px] uppercase tracking-wider text-bone/30 mb-0.5"><?= e(t('hub.appointment.booked_on')) ?></div>
        <div class="text-sm text-bone/50"><?= !empty($appt['created_at']) ? e((new DateTimeImmutable($appt['created_at']))->format('M j, Y · g:i A')) : '—' ?></div>
      </div>

      <div>
        <div class="text-[10px] uppercase tracking-wider text-bone/30 mb-0.5"><?= e(t('hub.table.source')) ?></div>
        <div class="text-sm text-bone/50 uppercase tracking-wider"><?= e($appt['source'] ?? '—') ?></div>
      </div>
    </div>

    <!-- Col 2: Customer info -->
    <div class="bg-white/[0.02] border border-white/5 rounded-2xl p-5 space-y-3">
      <div class="text-[10px] uppercase tracking-[0.2em] text-gold font-medium"><?= e(t('hub.appointment.customer')) ?></div>
      <?php if ($customer): ?>
        <div class="flex items-center gap-3">
          <div class="w-10 h-10 rounded-full bg-gold/15 border border-gold/25 flex items-center justify-center text-gold font-semibold text-sm shrink-0">
            <?= strtoupper(substr($customer['first_name'] ?? '?', 0, 1)) ?>
          </div>
          <div>
            <div class="font-medium"><?= e($custName) ?></div>
            <?php if (!empty($customer['email'])): ?>
              <a href="mailto:<?= e($customer['email']) ?>" class="text-xs text-bone/40 hover:text-gold transition-colors"><?= e($customer['email']) ?></a>
            <?php endif; ?>
          </div>
        </div>
        <?php if (!empty($customer['phone'])): ?>
          <div>
            <div class="text-[10px] uppercase tracking-wider text-bone/30 mb-0.5"><?= e(t('form.phone')) ?></div>
            <a href="tel:<?= e($customer['phone']) ?>" class="text-sm text-bone/60 hover:text-gold transition-colors"><?= e($customer['phone']) ?></a>
          </div>
        <?php endif; ?>
        <?php if (!empty($customer['address_line']) || !empty($customer['city'])): ?>
          <div>
            <div class="text-[10px] uppercase tracking-wider text-bone/30 mb-0.5"><?= e(t('form.address')) ?></div>
            <div class="text-xs text-bone/40"><?= e(trim(($customer['address_line'] ?? '') . ', ' . ($customer['city'] ?? '') . ' ' . ($customer['state'] ?? '') . ' ' . ($customer['zip'] ?? ''), ' ,')) ?></div>
          </div>
        <?php endif; ?>
        <a href="<?= url('/hub/customers/' . e($customer['id'])) ?>" class="text-gold text-xs hover:underline inline-flex items-center gap-1 pt-1">
          <?= e(t('hub.appointment.view_profile')) ?>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
        </a>
      <?php else: ?>
        <div class="text-bone/30 text-sm"><?= e(t('hub.appointment.no_customer')) ?></div>
      <?php endif; ?>
    </div>

    <!-- Col 3: Intake form + notes -->
    <div class="space-y-4">
      <!-- Intake form -->
      <div class="bg-white/[0.02] border border-white/5 rounded-2xl p-5">
        <div class="text-[10px] uppercase tracking-[0.2em] text-gold font-medium mb-3"><?= e(t('hub.appointment.intake_form')) ?></div>
        <?php if ($form): ?>
          <div class="flex items-center justify-between gap-3">
            <span class="pill pill-<?= e(strtolower($form['status'] ?? 'draft')) ?>"><?= e($form['status'] ?? '') ?></span>
            <a href="<?= url('/hub/forms/' . e($form['id'])) ?>" class="text-xs text-gold hover:underline"><?= e(t('hub.appointment.open_form')) ?> →</a>
          </div>
          <div class="text-[10px] text-bone/30 mt-2"><?= e(t('form.updated')) ?> <?= e(!empty($form['updated_at']) ? (new DateTimeImmutable($form['updated_at']))->format('M j · g:i A') : '') ?></div>
        <?php else: ?>
          <div class="text-bone/30 text-sm"><?= e(t('hub.appointment.no_form')) ?></div>
        <?php endif; ?>
      </div>

      <!-- Notes -->
      <div class="bg-white/[0.02] border border-white/5 rounded-2xl p-5">
        <div class="text-[10px] uppercase tracking-[0.2em] text-gold font-medium mb-3"><?= e(t('hub.appointment.notes')) ?></div>
        <?php if (!$done): ?>
          <form method="POST" action="<?= url('/hub/appointments/' . e($appt['id']) . '/notes') ?>">
            <?= csrf_field() ?>
            <textarea name="notes" rows="2" placeholder="<?= e(t('hub.appointment.notes_placeholder')) ?>"
                      class="input w-full resize-none text-sm"><?= e($appt['notes'] ?? '') ?></textarea>
            <button type="submit" class="mt-2 text-[10px] text-gold hover:underline uppercase tracking-wider"><?= e(t('hub.appointment.save_notes')) ?></button>
          </form>
        <?php elseif (!empty($appt['notes'])): ?>
          <p class="text-sm text-bone/60 italic">"<?= e($appt['notes']) ?>"</p>
        <?php else: ?>
          <p class="text-sm text-bone/30"><?= e(t('hub.appointment.no_notes')) ?></p>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- ════════════════════════════════════════════════════════════════
       RESCHEDULE BANNER (if pending)
       ════════════════════════════════════════════════════════════════ -->
  <?php if (!empty($appt['proposed_start_at'])): ?>
    <div class="bg-gold/5 border border-gold/20 rounded-2xl p-5 mb-4">
      <div class="flex items-start gap-3">
        <div class="w-8 h-8 rounded-full bg-gold/10 flex items-center justify-center shrink-0 mt-0.5">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#d4af37" stroke-width="2"><path d="M1 4v6h6M23 20v-6h-6"/><path d="M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15"/></svg>
        </div>
        <div>
          <div class="text-xs uppercase tracking-widest text-gold font-medium"><?= e(t('hub.appointment.reschedule_pending')) ?></div>
          <p class="text-sm text-bone/60 mt-1">
            <?= e(t('hub.appointment.reschedule_pending_desc')) ?>
            <strong class="text-bone"><?= e((new DateTimeImmutable($appt['proposed_start_at']))->format('l, F j · g:i A')) ?></strong>
          </p>
          <?php if (!empty($appt['reschedule_reason'])): ?>
            <p class="text-xs text-bone/40 italic mt-1">"<?= e($appt['reschedule_reason']) ?>"</p>
          <?php endif; ?>
        </div>
      </div>
    </div>
  <?php endif; ?>

  <!-- ════════════════════════════════════════════════════════════════
       ACTIONS BAR
       ════════════════════════════════════════════════════════════════ -->
  <?php if (!$done): ?>
    <div class="bg-white/[0.02] border border-white/5 rounded-2xl p-5 mb-4">
      <div class="text-[10px] uppercase tracking-[0.2em] text-gold font-medium mb-4"><?= e(t('hub.appointment.actions')) ?></div>
      <div class="flex flex-wrap gap-3">
        <?php if ($status === 'PENDING'): ?>
          <?php
          $formAction   = url('/hub/appointments/' . $appt['id'] . '/approve');
          $triggerLabel = t('hub.appointment.approve');
          $modalTitle   = t('hub.appointment.approve_title');
          $triggerClass = 'btn-gold';
          include MAT_ROOT . '/src/Views/partials/pin-modal.php';
          ?>
        <?php endif; ?>

        <?php
        $formAction   = url('/hub/appointments/' . $appt['id'] . '/complete');
        $triggerLabel = t('hub.appointment.mark_complete');
        $modalTitle   = t('hub.appointment.complete_title');
        $triggerClass = 'btn-ghost';
        include MAT_ROOT . '/src/Views/partials/pin-modal.php';
        ?>

        <!-- Cancel — custom modal with reason + share toggle -->
        <div x-data="{ open:false, username:'', pin:'', reason:'', shareWithCustomer:true }">
          <button type="button" @click="open=true"
                  class="inline-flex items-center gap-2 px-4 py-3 rounded-lg border border-red-500/20 text-red-400/70 text-xs uppercase tracking-wider hover:bg-red-500/5 transition-colors">
            <?= e(t('hub.appointment.cancel')) ?>
          </button>
          <div x-show="open" x-transition style="display:none" class="fixed inset-0 z-50 bg-black/80 backdrop-blur flex items-center justify-center p-4">
            <div class="bg-slate border border-white/10 rounded-2xl w-full max-w-md p-6" @click.outside="open=false">
              <h3 class="text-xl font-display text-red-400"><?= e(t('hub.appointment.cancel_title')) ?></h3>
              <p class="text-sm text-bone/50 mt-1"><?= e(t('hub.appointment.cancel_confirm_text')) ?></p>

              <form method="POST" action="<?= url('/hub/appointments/' . e($appt['id']) . '/cancel') ?>" class="mt-5 space-y-4">
                <?= csrf_field() ?>

                <!-- Reason -->
                <div>
                  <label class="label"><?= e(t('hub.appointment.cancel_reason')) ?></label>
                  <textarea name="cancel_reason" x-model="reason" rows="2"
                            placeholder="<?= e(t('hub.appointment.cancel_reason_placeholder')) ?>"
                            class="input w-full resize-none"></textarea>
                </div>

                <!-- Share reason with customer toggle -->
                <label class="flex items-center gap-3 cursor-pointer">
                  <input type="checkbox" name="share_reason_with_customer" value="1" x-model="shareWithCustomer"
                         class="accent-gold w-4 h-4">
                  <span class="text-sm text-bone/60"><?= e(t('hub.appointment.share_reason_customer')) ?></span>
                </label>
                <p class="text-[10px] text-bone/30"><?= e(t('hub.appointment.share_reason_hint')) ?></p>

                <!-- Staff credentials -->
                <div class="pt-3 border-t border-white/10">
                  <p class="text-[10px] text-bone/30 uppercase tracking-wider 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" x-model="username" required autocomplete="off" class="input">
                    </div>
                    <div>
                      <label class="label"><?= e(t('hub.pin.pin')) ?></label>
                      <input name="pin" type="password" x-model="pin" inputmode="numeric" maxlength="6" required autocomplete="off"
                             class="input text-center text-xl tracking-[0.5em]">
                    </div>
                  </div>
                </div>

                <div class="flex justify-end gap-2 pt-2">
                  <button type="button" @click="open=false" class="px-4 py-2 text-sm text-bone/50 hover:text-bone"><?= e(t('common.cancel')) ?></button>
                  <button type="submit" class="px-5 py-2.5 rounded-lg bg-red-500/20 text-red-400 text-xs uppercase tracking-wider font-semibold hover:bg-red-500/30 transition-colors">
                    <?= e(t('hub.appointment.confirm_cancel')) ?>
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Reschedule (collapsible) -->
    <div class="bg-white/[0.02] border border-white/5 rounded-2xl p-5"
         x-data="{
           open: false,
           year: new Date().getFullYear(), month: new Date().getMonth(),
           pickedDate: '', pickedTime: '',
           get monthLabel() { return new Date(this.year, this.month, 1).toLocaleDateString(undefined, { month:'long', year:'numeric' }); },
           get cells() {
             const f = new Date(this.year, this.month, 1), dim = new Date(this.year, this.month+1, 0).getDate(), sw = f.getDay();
             const today = new Date(); today.setHours(0,0,0,0);
             let c = []; for (let i=0;i<sw;i++) c.push({d:'',date:'',past:true});
             for (let d=1;d<=dim;d++) { const dt=this.year+'-'+String(this.month+1).padStart(2,'0')+'-'+String(d).padStart(2,'0'); c.push({d,date:dt,past:new Date(this.year,this.month,d)<today}); }
             return c;
           },
           prevM() { this.month--; if(this.month<0){this.month=11;this.year--;} },
           nextM() { this.month++; if(this.month>11){this.month=0;this.year++;} },
           get times() { let t=[]; for(let h=9;h<=21;h++) for(let m=0;m<60;m+=30){ const hh=String(h).padStart(2,'0'),mm=String(m).padStart(2,'0'),ap=h>=12?'PM':'AM',h12=h>12?h-12:(h===0?12:h); t.push({val:hh+':'+mm,label:h12+':'+mm+' '+ap}); } return t; }
         }">
      <button type="button" @click="open = !open"
              class="text-xs text-bone/50 hover:text-gold flex items-center gap-2 transition-colors font-medium uppercase tracking-wider">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 4v6h6M23 20v-6h-6"/><path d="M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15"/></svg>
        <?= e(t('hub.appointment.reschedule')) ?>
      </button>
      <div x-show="open" x-cloak class="mt-4 pt-4 border-t border-white/5">
        <form method="POST" action="<?= url('/hub/appointments/' . e($appt['id']) . '/reschedule') ?>">
          <?= csrf_field() ?>
          <input type="hidden" name="new_date" :value="pickedDate">
          <input type="hidden" name="new_time" :value="pickedTime">
          <div class="grid md:grid-cols-2 gap-6">
            <!-- Calendar -->
            <div>
              <label class="label mb-2"><?= e(t('hub.appointment.new_date')) ?></label>
              <div class="bg-ink/60 border border-white/10 rounded-xl p-4">
                <div class="flex items-center justify-between mb-3">
                  <button type="button" @click="prevM()" class="text-gold/60 hover:text-gold p-1"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 18l-6-6 6-6"/></svg></button>
                  <span class="text-sm font-medium" x-text="monthLabel"></span>
                  <button type="button" @click="nextM()" class="text-gold/60 hover:text-gold p-1"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18l6-6-6-6"/></svg></button>
                </div>
                <div class="grid grid-cols-7 gap-0.5 text-center text-[9px] uppercase tracking-widest text-bone/30 mb-1"><div>S</div><div>M</div><div>T</div><div>W</div><div>T</div><div>F</div><div>S</div></div>
                <div class="grid grid-cols-7 gap-0.5">
                  <template x-for="c in cells" :key="c.date||Math.random()">
                    <button type="button" :disabled="!c.date||c.past" @click="c.date&&!c.past&&(pickedDate=c.date)"
                            :class="{'bg-gold text-ink font-semibold':c.date===pickedDate,'hover:bg-gold/10 text-bone':c.date&&c.date!==pickedDate&&!c.past,'text-bone/15':c.past||!c.date}"
                            class="aspect-square rounded-lg text-xs flex items-center justify-center transition-all disabled:cursor-not-allowed" x-text="c.d"></button>
                  </template>
                </div>
              </div>
              <div class="text-xs text-gold/70 mt-2" x-show="pickedDate" x-text="pickedDate?new Date(pickedDate+'T12:00').toLocaleDateString(undefined,{weekday:'long',month:'long',day:'numeric'}):''"></div>
            </div>
            <!-- Time + reason + PIN -->
            <div class="space-y-4">
              <div>
                <label class="label mb-2"><?= e(t('hub.appointment.new_time')) ?></label>
                <div class="grid grid-cols-3 gap-1.5 max-h-40 overflow-y-auto pr-1">
                  <template x-for="t in times" :key="t.val">
                    <button type="button" @click="pickedTime=t.val" :class="pickedTime===t.val?'bg-gold text-ink border-gold font-semibold':'bg-ink/60 border-white/10 text-bone/70 hover:border-gold/30 hover:bg-gold/5'" class="border rounded-lg px-2 py-2 text-xs text-center transition-all" x-text="t.label"></button>
                  </template>
                </div>
              </div>
              <div><label class="label"><?= e(t('hub.appointment.reason')) ?></label><input name="reason" placeholder="<?= e(t('hub.appointment.reason_placeholder')) ?>" class="input"></div>
              <div class="pt-3 border-t border-white/5">
                <p class="text-[10px] text-bone/30 uppercase tracking-wider mb-2"><?= e(t('hub.pin.staff_confirmation')) ?></p>
                <div class="grid grid-cols-2 gap-2">
                  <input name="username" required placeholder="<?= e(t('hub.pin.username')) ?>" class="input text-xs" autocomplete="off">
                  <input name="pin" type="password" inputmode="numeric" maxlength="20" required placeholder="PIN" class="input text-xs text-center tracking-[0.3em]" autocomplete="off">
                </div>
              </div>
              <button class="btn-gold text-xs w-full" :disabled="!pickedDate||!pickedTime" :class="!pickedDate||!pickedTime?'opacity-40 cursor-not-allowed':''"><?= e(t('hub.appointment.send_proposal')) ?></button>
            </div>
          </div>
        </form>
      </div>
    </div>
  <?php endif; ?>
</div>
