<?php
/** @var array $customer; @var array $appointments; @var array $forms */
$totalVisits   = count(array_filter($appointments, fn($a) => in_array($a['status'] ?? '', ['COMPLETED'], true)));
$upcomingAppts = array_filter($appointments, fn($a) => in_array($a['status'] ?? '', ['PENDING','APPROVED','UPCOMING'], true));
$isDeleted     = !empty($customer['deleted_at']);
?>
<div class="p-5 md:p-8 max-w-4xl">
  <a href="<?= url('/hub/customers') ?>" class="text-xs text-bone/50 hover:text-bone flex items-center gap-1 mb-5">
    <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.customers.back')) ?>
  </a>

  <?php if ($isDeleted): ?>
    <div class="mb-4 rounded-xl px-4 py-3 text-sm bg-red-500/10 text-red-300 border border-red-500/20">
      <?= e(t('hub.customers.deleted_notice')) ?>
    </div>
  <?php endif; ?>

  <!-- Customer header -->
  <div class="flex items-start justify-between flex-wrap gap-4 mb-6">
    <div>
      <div class="text-xs uppercase tracking-[0.3em] text-gold"><?= e(t('hub.customers.kicker')) ?></div>
      <h1 class="mt-1 text-2xl md:text-3xl font-display"><?= e(trim(($customer['first_name'] ?? '') . ' ' . ($customer['last_name'] ?? ''))) ?></h1>
      <div class="mt-1 flex flex-wrap gap-3 text-sm text-bone/60">
        <?php if (!empty($customer['email'])): ?><span><?= e($customer['email']) ?></span><?php endif; ?>
        <?php if (!empty($customer['phone'])): ?><span><?= e($customer['phone']) ?></span><?php endif; ?>
      </div>
      <?php if (!empty($customer['address_line']) || !empty($customer['city'])): ?>
        <div class="mt-1 text-xs text-bone/40">
          <?= e(trim(($customer['address_line'] ?? '') . ', ' . ($customer['city'] ?? '') . ', ' . ($customer['state'] ?? '') . ' ' . ($customer['zip'] ?? ''), ' ,')) ?>
        </div>
      <?php endif; ?>
    </div>
    <!-- Visit counter badge -->
    <div class="bg-gold/10 border border-gold/30 rounded-2xl px-6 py-4 text-center shrink-0">
      <div class="text-3xl font-display text-gold"><?= $totalVisits ?></div>
      <div class="text-[10px] uppercase tracking-widest text-gold/60 mt-1"><?= e(t('hub.customer.total_visits')) ?></div>
    </div>
  </div>

  <!-- Upcoming / active appointments -->
  <?php if (!empty($upcomingAppts)): ?>
  <div class="mt-8">
    <h2 class="text-xs uppercase tracking-widest text-gold mb-3"><?= e(t('hub.customer.upcoming')) ?></h2>
    <div class="bg-ink/40 border border-gold/20 rounded-xl divide-y divide-white/5">
      <?php foreach ($upcomingAppts as $a):
        $artist = !empty($a['artist_id']) ? \App\Repositories\Container::artists()->find($a['artist_id']) : null;
      ?>
        <a href="<?= url('/hub/appointments/' . e($a['id'])) ?>" class="block p-4 hover:bg-white/5">
          <div class="flex items-center justify-between">
            <div>
              <div class="text-sm"><?= !empty($a['start_at']) ? e((new DateTimeImmutable($a['start_at']))->format('l, F j, Y · g:i A')) : '—' ?></div>
              <div class="text-xs text-bone/50 mt-0.5"><?= e($artist['display_name'] ?? t('booking.no_preference')) ?></div>
            </div>
            <span class="pill pill-<?= e(strtolower($a['status'] ?? 'pending')) ?>"><?= e(t('appt.status.' . strtolower($a['status'] ?? 'pending'))) ?></span>
          </div>
        </a>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- Past appointments with linked forms -->
  <div class="mt-8">
    <h2 class="text-xs uppercase tracking-widest text-gold mb-3"><?= e(t('hub.customer.visit_history')) ?></h2>
    <?php if (empty($appointments)): ?>
      <div class="bg-ink/40 border border-white/10 rounded-xl p-8 text-center text-bone/40 text-sm"><?= e(t('hub.customer.no_appointments')) ?></div>
    <?php else: ?>
      <div class="space-y-3">
        <?php foreach ($appointments as $a):
          $artist = !empty($a['artist_id']) ? \App\Repositories\Container::artists()->find($a['artist_id']) : null;
          // Find linked form
          $linkedForm = null;
          if (!empty($a['intake_form_id'])) {
              foreach ($forms as $f) {
                  if (($f['id'] ?? '') === $a['intake_form_id']) { $linkedForm = $f; break; }
              }
          }
        ?>
          <div class="bg-ink/40 border border-white/10 rounded-xl p-4">
            <div class="flex items-start justify-between gap-4">
              <div class="flex-1">
                <div class="flex items-center gap-3">
                  <span class="text-sm font-medium"><?= !empty($a['start_at']) ? e((new DateTimeImmutable($a['start_at']))->format('M j, Y · g:i A')) : '—' ?></span>
                  <span class="pill pill-<?= e(strtolower($a['status'] ?? 'pending')) ?> text-[10px]"><?= e(t('appt.status.' . strtolower($a['status'] ?? 'pending'))) ?></span>
                </div>
                <div class="text-xs text-bone/50 mt-1"><?= e($artist['display_name'] ?? t('booking.no_preference')) ?> · <?= e(strtoupper($a['source'] ?? '')) ?></div>
                <?php if (!empty($a['notes'])): ?>
                  <div class="mt-2 text-xs text-bone/60 italic">"<?= e($a['notes']) ?>"</div>
                <?php endif; ?>
              </div>
              <div class="flex items-center gap-2 shrink-0">
                <?php if ($linkedForm): ?>
                  <a href="<?= url('/hub/forms/' . e($linkedForm['id'])) ?>"
                     class="text-xs px-3 py-1 rounded border border-gold/30 text-gold hover:bg-gold/10">
                    <?= e(t('hub.customer.view_form')) ?> <span class="pill pill-<?= e(strtolower($linkedForm['status'] ?? 'draft')) ?> ml-1"><?= e($linkedForm['status'] ?? '') ?></span>
                  </a>
                <?php endif; ?>
                <a href="<?= url('/hub/appointments/' . e($a['id'])) ?>" class="text-xs text-bone/50 hover:text-bone"><?= e(t('common.open')) ?> →</a>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>

  <!-- Standalone forms (not linked to any appointment) -->
  <?php
  $linkedFormIds = array_filter(array_column($appointments, 'intake_form_id'));
  $standaloneForms = array_filter($forms, fn($f) => !in_array($f['id'] ?? '', $linkedFormIds, true));
  ?>
  <?php if (!empty($standaloneForms)): ?>
  <div class="mt-8">
    <h2 class="text-xs uppercase tracking-widest text-gold mb-3"><?= e(t('hub.customer.standalone_forms')) ?></h2>
    <div class="bg-ink/40 border border-white/10 rounded-xl divide-y divide-white/5">
      <?php foreach ($standaloneForms as $f): ?>
        <a href="<?= url('/hub/forms/' . e($f['id'])) ?>" class="block p-4 hover:bg-white/5">
          <div class="flex items-center justify-between">
            <div class="text-sm text-bone/80"><?= e($f['updated_at'] ?? $f['created_at'] ?? '') ?></div>
            <span class="pill pill-<?= e(strtolower($f['status'] ?? 'draft')) ?>"><?= e($f['status'] ?? '') ?></span>
          </div>
        </a>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- Delete customer (requires PIN) — admin only -->
  <?php if (!$isDeleted && (\App\Auth::role() === 'ADMIN')): ?>
  <div class="mt-10 border-t border-white/5 pt-6" x-data="{ open: false }">
    <button type="button" @click="open = !open"
            class="text-xs text-red-400/70 hover:text-red-400 flex items-center gap-1.5 transition-colors">
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4h6v2"/></svg>
      <?= e(t('hub.customers.delete_customer')) ?>
    </button>
    <div x-show="open" x-cloak class="mt-4 bg-red-500/5 border border-red-500/20 rounded-2xl p-5">
      <p class="text-sm text-bone/70 mb-4"><?= e(t('hub.customers.delete_warning')) ?></p>
      <form method="POST" action="<?= url('/hub/customers/' . e($customer['id']) . '/delete') ?>">
        <?= csrf_field() ?>
        <div class="grid grid-cols-2 gap-3 mb-3">
          <div><label class="label"><?= e(t('hub.pin.username')) ?></label>
            <input name="username" required class="input" autocomplete="off"></div>
          <div><label class="label"><?= e(t('hub.pin.pin')) ?></label>
            <input name="pin" type="password" inputmode="numeric" maxlength="20" required class="input text-center tracking-[0.5em]" autocomplete="off"></div>
        </div>
        <button class="btn-ghost text-xs border-red-500/40 text-red-400 hover:bg-red-500/10 px-5 py-2.5"><?= e(t('hub.customers.confirm_delete')) ?></button>
      </form>
    </div>
  </div>
  <?php endif; ?>
</div>
