<script lang="ts">
  import { onMount } from 'svelte';
  import type { PicletInstance } from '$lib/db/schema';
  import { deletePicletInstance } from '$lib/db/piclets';
  import { uiStore } from '$lib/stores/ui';
  import { TYPE_DATA } from '$lib/types/picletTypes';

  interface Props {
    instance: PicletInstance;
    onClose: () => void;
    onDeleted?: () => void;
  }

  let { instance, onClose, onDeleted }: Props = $props();

  const typeColor = $derived(TYPE_DATA[instance.primaryType]?.color || '#007bff');
  const typeLogoPath = $derived(`/classes/${instance.primaryType}.png`);

  onMount(() => {
    uiStore.openDetailPage();
    return () => {
      uiStore.closeDetailPage();
    };
  });

  async function handleDelete() {
    if (confirm(`Are you sure you want to delete ${instance.typeId}?`)) {
      try {
        await deletePicletInstance(instance.id!);
        onDeleted?.();
        onClose();
      } catch (error) {
        console.error('Failed to delete piclet:', error);
        alert('Failed to delete piclet');
      }
    }
  }
</script>

<div class="detail-page">
  <div class="content-scroll">
    <!-- Header Card -->
    <div class="header-card">
      <div class="card-background" style="--type-color: {typeColor}; --type-logo: url('{typeLogoPath}')">
        <!-- Faded Logo Background -->
        <div class="logo-background"></div>

        <!-- Card Header -->
        <div class="card-header">
          <button
            class="back-btn-card"
            onclick={onClose}
            aria-label="Go back"
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M19 12H5m0 0l7 7m-7-7l7-7"></path>
            </svg>
          </button>
          <h1 class="card-title">{instance.nickname || instance.objectName}</h1>
          <div class="tier-badge tier-{instance.tier}">{instance.tier}</div>
        </div>

        <!-- Large Image Section -->
        <div class="large-image-section">
          <div class="large-image-container">
            <img
              src={instance.imageData || instance.imageUrl}
              alt={instance.typeId}
              class="large-piclet-image"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- Info Section -->
    <div class="info-card">
      <div class="type-badge" style="background-color: {typeColor}">
        {instance.primaryType}
      </div>

      <div class="description">
        <p>{instance.description}</p>
      </div>

      <div class="divider"></div>

      <h3 class="section-heading">Discovery Info</h3>
      <div class="metadata-list">
        <div class="meta-row">
          <span class="meta-label">Object</span>
          <span class="meta-value">{instance.objectName}</span>
        </div>

        {#if instance.isCanonical}
          <div class="meta-row">
            <span class="meta-label">Status</span>
            <span class="canonical-badge">Canonical</span>
          </div>
        {/if}

        {#if instance.variationAttributes && instance.variationAttributes.length > 0}
          <div class="meta-row">
            <span class="meta-label">Variation</span>
            <span class="meta-value">{instance.variationAttributes.join(', ')}</span>
          </div>
        {/if}

        {#if instance.discoveredAt}
          <div class="meta-row">
            <span class="meta-label">Discovered</span>
            <span class="meta-value">{new Date(instance.discoveredAt).toLocaleDateString()}</span>
          </div>
        {/if}

        <div class="meta-row">
          <span class="meta-label">Scan Count</span>
          <span class="meta-value">{instance.scanCount || 1}</span>
        </div>

        <div class="meta-row">
          <span class="meta-label">Rarity</span>
          <span class="rarity-badge tier-{instance.tier}">{instance.tier}</span>
        </div>
      </div>
    </div>

    <!-- Discoverer Info -->
    {#if instance.discovererSub || instance.discoveredBy}
      <div class="discoverer-card">
        <h3 class="section-heading">Discoverer</h3>
        <div class="discoverer-info">
          {#if instance.discovererPicture}
            <img
              src={instance.discovererPicture}
              alt={instance.discovererName || instance.discovererUsername}
              class="discoverer-avatar"
            />
          {:else}
            <div class="discoverer-avatar-placeholder">
              {(instance.discovererName || instance.discovererUsername || instance.discoveredBy || 'A')[0].toUpperCase()}
            </div>
          {/if}
          <div class="discoverer-details">
            <span class="discoverer-name">
              {instance.discovererName || instance.discovererUsername || instance.discoveredBy || 'Anonymous'}
            </span>
            <span class="discoverer-label">First to discover this Piclet</span>
          </div>
        </div>
      </div>
    {/if}

    <!-- Actions -->
    <div class="bottom-actions">
      <button class="btn btn-danger" onclick={handleDelete}>Delete Piclet</button>
    </div>
  </div>
</div>

<style>
  .detail-page {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #f2f2f7;
    z-index: 1000;
    display: flex;
    flex-direction: column;
  }

  /* Content Scroll */
  .content-scroll {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  /* Header Card */
  .header-card {
    margin-bottom: 16px;
    overflow: hidden;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    position: relative;
  }

  .card-background {
    background: linear-gradient(135deg, var(--type-color, #4CAF50) 0%, color-mix(in srgb, var(--type-color, #4CAF50) 80%, white) 100%);
    padding: 24px;
    padding-top: calc(24px + env(safe-area-inset-top, 0));
    position: relative;
    overflow: hidden;
  }

  .logo-background {
    position: absolute;
    bottom: 5px;
    right: 5px;
    width: 120px;
    height: 120px;
    background-image: var(--type-logo);
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
    opacity: 0.15;
    pointer-events: none;
    z-index: 1;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    position: relative;
    z-index: 2;
  }

  .card-title {
    margin: 0;
    font-size: 24px;
    font-weight: bold;
    color: white;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    flex: 1;
    text-align: center;
  }

  .back-btn-card {
    background: rgba(255, 255, 255, 0.2);
    border: none;
    color: white;
    cursor: pointer;
    padding: 8px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
  }

  .back-btn-card:hover {
    background: rgba(255, 255, 255, 0.3);
  }

  .tier-badge {
    background: rgba(255, 255, 255, 0.3);
    padding: 6px 12px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: bold;
    text-transform: uppercase;
    color: white;
    backdrop-filter: blur(10px);
  }

  .large-image-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    z-index: 2;
  }

  .large-image-container {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 360px;
    height: 360px;
  }

  .large-piclet-image {
    width: 360px;
    height: 360px;
    object-fit: contain;
    filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
  }

  /* Info Card */
  .info-card {
    background: white;
    margin: 0 16px 16px;
    border-radius: 12px;
    padding: 16px;
    border: 0.5px solid #c6c6c8;
  }

  .type-badge {
    display: inline-block;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 600;
    text-transform: uppercase;
    color: white;
    margin-bottom: 16px;
  }

  .description {
    margin-bottom: 16px;
  }

  .description p {
    margin: 0;
    font-size: 16px;
    line-height: 1.5;
    color: #333;
  }

  .divider {
    height: 1px;
    background: #e5e5ea;
    margin: 16px 0;
  }

  .section-heading {
    font-size: 18px;
    font-weight: 600;
    color: #495057;
    margin: 0 0 12px 0;
  }

  .metadata-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .meta-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 15px;
  }

  .meta-label {
    font-weight: 500;
    color: #666;
  }

  .meta-value {
    font-weight: 600;
    color: #000;
  }

  .canonical-badge {
    background: #4CAF50;
    color: white;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
  }

  .rarity-badge {
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
    color: white;
  }

  .rarity-badge.tier-low { background: #6c757d; }
  .rarity-badge.tier-medium { background: #28a745; }
  .rarity-badge.tier-high { background: #fd7e14; }
  .rarity-badge.tier-legendary { background: #dc3545; }

  /* Discoverer Card */
  .discoverer-card {
    background: white;
    margin: 0 16px 16px;
    border-radius: 12px;
    padding: 16px;
    border: 0.5px solid #c6c6c8;
  }

  .discoverer-info {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .discoverer-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    border: 2px solid var(--type-color, #007bff);
    object-fit: cover;
    flex-shrink: 0;
  }

  .discoverer-avatar-placeholder {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    border: 2px solid var(--type-color, #007bff);
    background: var(--type-color, #007bff);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    font-weight: bold;
    flex-shrink: 0;
  }

  .discoverer-details {
    display: flex;
    flex-direction: column;
    gap: 4px;
    min-width: 0;
  }

  .discoverer-name {
    font-size: 16px;
    font-weight: 600;
    color: #1a1a1a;
  }

  .discoverer-label {
    font-size: 12px;
    color: #666;
  }

  /* Bottom Actions */
  .bottom-actions {
    padding: 16px;
    background: white;
    border-top: 0.5px solid #c6c6c8;
    text-align: center;
  }

  .btn {
    padding: 0.75rem 1.5rem;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: transform 0.2s;
  }

  .btn:active {
    transform: scale(0.95);
  }

  .btn-danger {
    background: #ff3b30;
    color: white;
    width: 100%;
  }

  @media (min-width: 768px) {
    .detail-page {
      position: relative;
      max-width: 600px;
      margin: 0 auto;
      box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    }
  }
</style>
