<?php
$l = $lead;
$name = trim($l['first_name'] . ' ' . $l['last_name']);
$st = (string) ($l['status'] ?? 'new');
$labels = \App\Models\Lead::statusLabels();
$statusHistory = $statusHistory ?? [];
$owner = trim((string) ($l['owner_name'] ?? ''));
$company = trim((string) ($l['company'] ?? ''));
$source = trim((string) ($l['source'] ?? ''));
$territory = trim((string) ($l['territory_name'] ?? ''));
$notes = trim((string) ($l['notes'] ?? ''));
$seen = array_column($statusHistory, 'status');
$path = $st === 'unqualified'
    ? [
        ['new', 'New', 'bi-sparkles'],
        ['unqualified', 'Not a fit', 'bi-x-circle-fill'],
    ]
    : [
        ['new', 'New', 'bi-sparkles'],
        ['qualified', 'Qualified', 'bi-star-fill'],
        ['converted', 'Converted', 'bi-arrow-left-right'],
    ];
$feed = [];
foreach ($timeline as $t) {
    $type = (string) ($t['type'] ?? '');
    $sub = (string) ($t['subject'] ?? '');
    if ($type === 'stage') {
        continue;
    }
    if (preg_match('/^Lead marked /', $sub)) {
        continue;
    }
    if (preg_match('/^(New|Qualified|Not a fit|Converted)\s*→/', $sub)) {
        continue;
    }
    $feed[] = $t;
}
?>
<div class="rec-page lead-show">
  <a class="rec-back" href="<?= e(url('leads')) ?>"><i class="bi bi-arrow-left"></i> All leads</a>

  <div class="rec-hero lead-tone-<?= e($st) ?>">
    <div class="rec-hero-main">
      <div class="rec-hero-avatar"><?= e(name_initials($name !== '' ? $name : 'Lead')) ?></div>
      <div class="min-w-0">
        <p class="rec-kicker">Lead · a person to qualify</p>
        <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
          <h1 class="page-title mb-0"><?= e($name !== '' ? $name : 'Untitled lead') ?></h1>
          <span class="lead-status lead-status-<?= e($st) ?>"><?= e($labels[$st] ?? $st) ?></span>
        </div>
        <div class="rec-hero-sub">
          <?php if ($company !== ''): ?><span><i class="bi bi-buildings"></i> <?= e($company) ?></span><?php endif; ?>
          <?php if ($owner !== ''): ?>
            <span class="task-owner-chip" title="<?= e($owner) ?>">
              <span class="task-avatar"><?= e(name_initials($owner)) ?></span>
              <span class="task-owner text-truncate"><?= e($owner) ?></span>
            </span>
          <?php else: ?>
            <span class="text-muted">No owner yet</span>
          <?php endif; ?>
          <span class="text-muted">Added <?= e(dt_fmt($l['created_at'], 'M j, Y')) ?></span>
        </div>
        <div class="rec-hero-contact">
          <?php if (!empty($l['email'])): ?>
            <a href="mailto:<?= e($l['email']) ?>"><i class="bi bi-envelope"></i> <?= e($l['email']) ?></a>
          <?php endif; ?>
          <?php if (!empty($l['phone'])): ?>
            <a href="tel:<?= e($l['phone']) ?>"><i class="bi bi-telephone"></i> <?= e($l['phone']) ?></a>
          <?php endif; ?>
          <?php if ($source !== ''): ?><span><i class="bi bi-broadcast"></i> <?= e($source) ?></span><?php endif; ?>
          <?php if ($territory !== ''): ?><span><i class="bi bi-geo-alt"></i> <?= e($territory) ?></span><?php endif; ?>
        </div>
      </div>
    </div>

    <?php if ($st !== 'converted'): ?>
      <div class="rec-hero-actions">
        <p class="rec-action-hint">Choose what this lead is: worth pursuing, not a fit, or ready to become a customer.</p>
        <?php if ($st !== 'qualified'): ?>
          <form class="ajax-form" action="<?= e(url('leads/'.$l['id'].'/qualify')) ?>" method="post">
            <?= csrf_field() ?><input type="hidden" name="status" value="qualified">
            <button class="btn btn-success" type="submit" title="This person is worth pursuing"><i class="bi bi-star-fill"></i> Qualify</button>
          </form>
        <?php endif; ?>
        <?php if ($st !== 'unqualified'): ?>
          <form class="ajax-form" action="<?= e(url('leads/'.$l['id'].'/qualify')) ?>" method="post">
            <?= csrf_field() ?><input type="hidden" name="status" value="unqualified">
            <button class="btn btn-outline-danger" type="submit" title="This person is not a fit"><i class="bi bi-x-circle"></i> Not a fit</button>
          </form>
        <?php endif; ?>
        <form class="ajax-form" action="<?= e(url('leads/'.$l['id'].'/convert')) ?>" method="post">
          <?= csrf_field() ?><input type="hidden" name="create_deal" value="1">
          <button class="btn btn-primary" type="submit" title="Create an account and a deal from this lead"><i class="bi bi-arrow-left-right"></i> Convert to account + deal</button>
        </form>
      </div>
    <?php else: ?>
      <div class="rec-banner is-won">
        <i class="bi bi-check-circle-fill"></i>
        <div>
          <strong>Converted into a customer</strong>
          <div>
            <?php if (!empty($l['converted_account_id'])): ?>
              Account: <a href="<?= e(url('accounts/'.$l['converted_account_id'])) ?>"><?= e($l['converted_account_name'] ?: 'Open account') ?></a>
            <?php endif; ?>
            <?php if (!empty($l['converted_opportunity_id'])): ?>
              · Deal: <a href="<?= e(url('opportunities/'.$l['converted_opportunity_id'])) ?>"><?= e($l['converted_opportunity_name'] ?: 'Open deal') ?></a>
            <?php endif; ?>
          </div>
          <?php if (!empty($l['converted_at'])): ?>
            <div class="small text-muted"><?= e(dt_fmt($l['converted_at'], 'M j, Y g:i A')) ?></div>
          <?php endif; ?>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <div class="row g-3">
    <div class="col-lg-8">
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-signpost-split',
            'title' => 'Status path',
            'hint' => 'Where this lead is. New → Qualified → Converted, or Not a fit if they drop out.',
        ]); ?>
        <div class="rec-stepper">
          <?php foreach ($path as $i => $step):
              $code = $step[0];
              $isCurrent = $code === $st;
              $isDone = !$isCurrent && in_array($code, $seen, true);
              $isSkipped = $code === 'qualified' && $st === 'converted' && !in_array('qualified', $seen, true);
              if ($isSkipped) {
                  $isDone = false;
              }
          ?>
            <?php if ($i > 0): ?><div class="rec-step-line <?= $isDone || $isCurrent || $isSkipped ? 'is-on' : '' ?>"></div><?php endif; ?>
            <div class="rec-step <?= $isCurrent ? 'is-current' : '' ?> <?= $isDone ? 'is-done' : '' ?> <?= $isSkipped ? 'is-skipped' : '' ?> rec-step-<?= e($code) ?>">
              <span class="rec-step-dot"><i class="bi <?= e($step[2]) ?>"></i></span>
              <span class="rec-step-label"><?= e($step[1]) ?></span>
              <?php if ($isSkipped): ?><span class="rec-step-hint">Skipped</span><?php endif; ?>
              <?php if ($isCurrent): ?><span class="rec-step-hint">Now</span><?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-clock-history',
            'title' => 'Status changes',
            'hint' => 'Who moved this lead and when.',
        ]); ?>
        <div class="rec-status-tl">
          <?php foreach ($statusHistory as $h):
            $isNow = ($h['status'] ?? '') === $st;
          ?>
            <div class="rec-status-tl-item lead-tone-<?= e($h['status']) ?> <?= $isNow ? 'is-current' : '' ?>">
              <span class="rec-status-tl-dot"></span>
              <div class="min-w-0">
                <div class="d-flex flex-wrap align-items-center gap-2">
                  <strong><?= e($h['label']) ?></strong>
                  <?php if (!empty($h['from_label'])): ?>
                    <span class="rec-status-tl-from"><?= e($h['from_label']) ?> → <?= e($h['label']) ?></span>
                  <?php endif; ?>
                  <?php if ($isNow): ?><span class="rec-status-tl-now">Now</span><?php endif; ?>
                </div>
                <?php
                  $hNote = (string) ($h['note'] ?? '');
                  $hideNote = $hNote === '' || $hNote === ($h['label'] ?? '') || $hNote === 'Lead created' || str_starts_with($hNote, 'Status set to');
                ?>
                <?php if (!$hideNote): ?>
                  <div class="small"><?= e($hNote) ?></div>
                <?php endif; ?>
                <div class="small text-muted">
                  <?= e($h['who'] !== '' ? $h['who'] : 'System') ?>
                  · <?= e(dt_fmt($h['at'] ?? null, 'M j, Y g:i A')) ?>
                  · <?= e(relative_when($h['at'] ?? null)) ?>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <?php \App\Core\View::partial('record_activity_block', [
          'relatedType' => 'lead',
          'relatedId' => (int) $l['id'],
          'feed' => $feed,
          'formClass' => 'lead-note-form',
          'emptyHint' => 'Calls, emails, and notes for this lead will show up here.',
      ]); ?>
    </div>

    <div class="col-lg-4">
      <?php \App\Core\View::partial('record_facts', [
          'title' => 'About this lead',
          'hint' => 'Who they are and how they reached you.',
          'icon' => 'bi-person-vcard',
          'facts' => [
              ['label' => 'Company', 'value' => $company],
              ['label' => 'Email', 'value' => $l['email'] ?? '', 'href' => !empty($l['email']) ? 'mailto:' . $l['email'] : ''],
              ['label' => 'Phone', 'value' => $l['phone'] ?? '', 'href' => !empty($l['phone']) ? 'tel:' . $l['phone'] : ''],
              ['label' => 'Source', 'value' => $source],
              ['label' => 'Territory', 'value' => $territory],
              ['label' => 'Owner', 'value' => $owner !== '' ? $owner : 'Unassigned'],
              ['label' => 'Added', 'value' => dt_fmt($l['created_at'], 'M j, Y g:i A')],
          ],
      ]); ?>
      <?php \App\Core\View::partial('related_task_box', [
          'relatedType' => 'lead',
          'relatedId' => (int) $l['id'],
          'tasks' => $tasks ?? [],
          'ownerId' => (int) ($l['owner_id'] ?? 0),
          'empty' => 'No tasks on this lead yet.',
          'boxId' => 'lead-tasks',
          'hint' => 'Follow-ups and to-dos for this person.',
      ]); ?>
      <?php if ($notes !== ''): ?>
        <div class="card-soft rec-card p-3">
          <?php \App\Core\View::partial('record_section_head', [
              'icon' => 'bi-sticky',
              'title' => 'Notes',
              'hint' => 'A longer note saved on this lead.',
          ]); ?>
          <p class="mb-0 rec-notes"><?= nl2br(e($notes)) ?></p>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>
