<script>
  import { createEventDispatcher } from 'svelte';

  export let certifications = [];
  export let shiftHistory = [];
  export let currentShiftStats = null;
  export let playerPortrait = 'player-silhouette';

  const dispatch = createEventDispatcher();

  const PORTRAITS = [
    'player-silhouette',
    'player-01',
    'player-02',
    'player-03',
    'player-04',
    'player-05'
  ];

  const PORTRAIT_LABELS = {
    'player-silhouette': 'Default',
    'player-01': 'Option 1',
    'player-02': 'Option 2',
    'player-03': 'Option 3',
    'player-04': 'Option 4',
    'player-05': 'Option 5'
  };

  function selectPortrait(id) {
    dispatch('portrait', id);
  }

  function formatDuration(seconds) {
    const safe = Number(seconds);
    if (!Number.isFinite(safe) || safe < 0) {
      return 'n/a';
    }

    const minutes = Math.floor(safe / 60);
    const remainder = safe % 60;
    return `${minutes}m ${String(remainder).padStart(2, '0')}s`;
  }

  function prettyTier(tier) {
    if (tier === 'excellent') return 'Excellent';
    if (tier === 'ok') return 'Solid';
    if (tier === 'poor') return 'Needs Work';
    return 'Unknown';
  }
</script>

<section class="portrait-section">
  <div class="portrait-current">
    <img
      class="portrait-large"
      src={`/public/portraits/${playerPortrait}.png`}
      alt="Your portrait"
      onerror={(e) => { e.currentTarget.src = '/public/portraits/player-silhouette.png'; }}
    >
    <div>
      <p class="portrait-heading">Your Portrait</p>
      <p class="portrait-sub">Select a portrait to use in the HUD header.</p>
    </div>
  </div>

  <div class="portrait-grid">
    {#each PORTRAITS as id}
      <button
        class={`portrait-option ${playerPortrait === id ? 'selected' : ''}`}
        onclick={() => selectPortrait(id)}
        title={PORTRAIT_LABELS[id]}
      >
        <img
          src={`/public/portraits/${id}.png`}
          alt={PORTRAIT_LABELS[id]}
          onerror={(e) => { e.currentTarget.src = '/public/portraits/player-silhouette.png'; }}
        >
        {#if playerPortrait === id}
          <span class="portrait-check">✓</span>
        {/if}
      </button>
    {/each}
  </div>
</section>

<section class="panel-grid">
  <article class="panel">
    <header>
      <h2>Certifications</h2>
      <span>{certifications.length} earned</span>
    </header>

    {#if certifications.length === 0}
      <p class="empty">No internal certifications awarded yet.</p>
    {:else}
      <div class="stack">
        {#each certifications as certification}
          <article class="card">
            <strong>{certification.title}</strong>
            <p>{certification.description}</p>
            <small>{new Date(certification.awarded_at).toLocaleString()}</small>
          </article>
        {/each}
      </div>
    {/if}
  </article>

  <article class="panel">
    <header>
      <h2>Shift Reviews</h2>
      <span>{shiftHistory.length} archived</span>
    </header>

    {#if currentShiftStats}
      <section class="current">
        <h3>Current Shift</h3>
        <div class="current-stats">
          <article class="stat">
            <span>Assigned</span>
            <strong>{(currentShiftStats.assigned_ticket_ids ?? []).length}</strong>
          </article>
          <article class="stat">
            <span>Resolved</span>
            <strong>{(currentShiftStats.resolved_tickets ?? []).length}</strong>
          </article>
          <article class="stat">
            <span>Flagged</span>
            <strong>{(currentShiftStats.flagged_issues ?? []).length}</strong>
          </article>
        </div>
      </section>
    {/if}

    {#if shiftHistory.length === 0}
      <p class="empty">No reviews yet. Finish a shift to see Priya's assessment.</p>
    {:else}
      <div class="stack">
        {#each [...shiftHistory].reverse() as review}
          <article class="card">
            <div class="topline">
              <strong>Shift {review.shift_number}</strong>
              <span class={`tier ${review.performance_tier ?? 'ok'}`}>{prettyTier(review.performance_tier)}</span>
            </div>
            <p>Resolved {review.tickets_resolved}/{review.tickets_assigned}</p>
            <p>Average resolution: {formatDuration(review.average_resolution_seconds)}</p>
            <p>Flagged issues: {(review.flagged_issues ?? []).length}</p>
            <small>{new Date(review.ended_at).toLocaleString()}</small>
          </article>
        {/each}
      </div>
    {/if}
  </article>
</section>

<style>
  .portrait-section {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 24px;
    padding: 1.25rem;
    box-shadow: var(--shadow);
    margin-bottom: 1rem;
  }

  .portrait-current {
    display: flex;
    align-items: center;
    gap: 1.25rem;
    margin-bottom: 1.25rem;
  }

  .portrait-large {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid var(--border);
    flex-shrink: 0;
  }

  .portrait-heading {
    font-weight: 600;
    font-size: 1rem;
    color: #f4eee4;
    margin-bottom: 0.25rem;
  }

  .portrait-sub {
    font-size: 0.83rem;
    color: var(--text-muted);
  }

  .portrait-grid {
    display: flex;
    gap: 0.75rem;
    flex-wrap: wrap;
  }

  .portrait-option {
    position: relative;
    background: none;
    border: 2px solid var(--border);
    border-radius: 50%;
    padding: 0;
    cursor: pointer;
    width: 58px;
    height: 58px;
    overflow: visible;
    transition: border-color 0.15s;
  }

  .portrait-option img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
    display: block;
  }

  .portrait-option.selected {
    border-color: var(--accent);
  }

  .portrait-option:hover:not(.selected) {
    border-color: rgba(255,255,255,0.35);
  }

  .portrait-check {
    position: absolute;
    bottom: -2px;
    right: -2px;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    background: var(--accent);
    color: #fff;
    font-size: 0.65rem;
    font-weight: 700;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .panel-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 1rem;
  }

  .panel {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 24px;
    padding: 1rem;
    box-shadow: var(--shadow);
  }

  .stack {
    display: grid;
    gap: 0.8rem;
    margin-top: 0.9rem;
  }

  .card,
  .current {
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 0.9rem;
    background: rgba(255, 255, 255, 0.03);
  }

  .topline,
  header {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    align-items: center;
  }

  .current-stats {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 0.8rem;
    margin-top: 0.9rem;
  }

  .stat {
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 0.85rem;
    background: rgba(255, 255, 255, 0.02);
  }

  .stat strong {
    display: block;
    margin-top: 0.35rem;
    color: #f4eee4;
    font-size: 1.4rem;
  }

  h2,
  h3 {
    margin: 0;
  }

  p,
  small,
  span {
    color: var(--text-muted);
  }

  .tier {
    text-transform: uppercase;
    letter-spacing: 0.08em;
    font-size: 0.72rem;
    padding: 0.18rem 0.5rem;
    border-radius: 999px;
  }

  .tier.excellent {
    background: rgba(99, 182, 122, 0.16);
    color: #dfeedd;
  }

  .tier.poor {
    background: rgba(200, 101, 101, 0.16);
    color: #ffd9d4;
  }

  .tier.ok {
    background: rgba(214, 104, 56, 0.14);
    color: #f5ddcf;
  }

  @media (max-width: 960px) {
    .panel-grid {
      grid-template-columns: 1fr;
    }

    .current-stats {
      grid-template-columns: 1fr;
    }
  }
</style>
