---
import type { RoadmapItemWithAttribution, RoadmapStatus } from '../lib/db';

interface Props {
  items: RoadmapItemWithAttribution[];
}

const { items } = Astro.props;

const STATUS_LABEL: Record<RoadmapStatus, string> = {
  shipping:    'SHIPPING',
  in_beta:     'IN BETA',
  planned:     'PLANNED',
  exploring:   'EXPLORING',
  considering: 'CONSIDERING',
};

const STATUS_LABEL_COLOR: Record<RoadmapStatus, string> = {
  shipping:    'var(--pigment-copper)',
  in_beta:     'var(--pigment-terracotta)',
  planned:     'var(--pigment-indigo)',
  exploring:   '#b4b2a9',
  considering: '#b4b2a9',
};

const STATUS_DOT_COLOR: Record<RoadmapStatus, string> = {
  shipping:    'var(--pigment-copper)',
  in_beta:     'var(--pigment-terracotta)',
  planned:     'var(--pigment-indigo)',
  exploring:   '#b4b2a9',
  considering: '#d4d2c8',
};

/** First-names-only attribution string. Empty when no attribution exists. */
function attributionLine(attributed: { name: string }[]): string {
  if (!attributed.length) return '';
  const names = attributed.map(a => a.name.split(' ')[0]);
  if (names.length === 1) return `Shaped by ${names[0]}.`;
  if (names.length === 2) return `Shaped by ${names[0]} and ${names[1]}.`;
  return `Shaped by ${names.slice(0, -1).join(', ')} and ${names.at(-1)}.`;
}

const hasArrows = items.length > 3;
---
<section class="roadmap-section" aria-label="On the roadmap">
  <header class="roadmap-header">
    <h2 class="roadmap-title">On the <em>roadmap.</em></h2>
    <div class="roadmap-actions">
      <a href="/roadmap" class="roadmap-all">See the full roadmap →</a>
      {hasArrows && (
        <div class="roadmap-arrows" role="group" aria-label="Scroll controls">
          <button type="button" class="roadmap-arrow" data-dir="prev" aria-label="Previous" disabled>
            <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true">
              <path d="M9 2 L4 7 L9 12" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
          <button type="button" class="roadmap-arrow" data-dir="next" aria-label="Next">
            <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true">
              <path d="M5 2 L10 7 L5 12" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
        </div>
      )}
    </div>
  </header>

  <div class="carousel-wrap">
    <div class="carousel-scroll" data-carousel-scroll>
      <div class="carousel-strip">
        {items.map(item => (
          <article class="carousel-card">
            <header class="card-status">
              <span class="card-dot" style={`background:${STATUS_DOT_COLOR[item.status]}`} aria-hidden="true"></span>
              <span class="card-status-label" style={`color:${STATUS_LABEL_COLOR[item.status]}`}>
                {STATUS_LABEL[item.status]}{item.target ? ` · ${item.target.toUpperCase()}` : ''}
              </span>
            </header>
            <h3 class="card-title">{item.title}</h3>
            <p class="card-desc">
              {item.description}
              {item.attributed.length > 0 && (
                <span class="card-attribution"> {attributionLine(item.attributed)}</span>
              )}
            </p>
          </article>
        ))}
      </div>
    </div>
    {hasArrows && <div class="carousel-fade-right" data-carousel-fade></div>}
  </div>
</section>

<script>
  // Vanilla carousel — scroll by card width, update arrow disabled state,
  // fade the right gradient when scrolled to the end.
  document.querySelectorAll<HTMLElement>('.roadmap-section').forEach((section) => {
    const scroll = section.querySelector<HTMLElement>('[data-carousel-scroll]');
    const fade = section.querySelector<HTMLElement>('[data-carousel-fade]');
    if (!scroll) return;
    const prev = section.querySelector<HTMLButtonElement>('.roadmap-arrow[data-dir="prev"]');
    const next = section.querySelector<HTMLButtonElement>('.roadmap-arrow[data-dir="next"]');

    function cardWidth() {
      const card = scroll!.querySelector<HTMLElement>('.carousel-card');
      return card ? card.getBoundingClientRect().width : scroll!.clientWidth;
    }

    function update() {
      const max = scroll!.scrollWidth - scroll!.clientWidth;
      const atStart = scroll!.scrollLeft <= 1;
      const atEnd = scroll!.scrollLeft >= max - 1;
      if (prev) prev.disabled = atStart;
      if (next) next.disabled = atEnd;
      if (fade) fade.style.opacity = atEnd ? '0' : '1';
    }

    prev?.addEventListener('click', () => scroll.scrollBy({ left: -cardWidth(), behavior: 'smooth' }));
    next?.addEventListener('click', () => scroll.scrollBy({ left:  cardWidth(), behavior: 'smooth' }));
    scroll.addEventListener('scroll', update, { passive: true });
    update();
  });
</script>

<style>
  .roadmap-section {
    display: flex;
    flex-direction: column;
    gap: 24px;
  }

  .roadmap-header {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
  }
  .roadmap-title {
    font-family: var(--font-serif);
    font-weight: 400;
    font-size: 22px;
    line-height: 1.2;
    color: var(--on-surface);
    margin: 0;
  }
  .roadmap-title em { font-style: italic; }
  .roadmap-actions {
    display: flex;
    align-items: baseline;
    gap: 18px;
  }
  .roadmap-all {
    font-family: var(--font-sans);
    font-size: 12px;
    letter-spacing: var(--tracking-wider);
    text-transform: uppercase;
    color: var(--pigment-terracotta);
    text-decoration: none;
    border-bottom: none;
  }
  .roadmap-all:hover { opacity: 0.8; border-bottom: none; }

  .roadmap-arrows {
    display: flex;
    gap: 8px;
    align-self: center;
  }
  .roadmap-arrow {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    border: 0.5px solid rgba(0, 0, 0, 0.15);
    background: var(--background);
    color: var(--on-surface);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    padding: 0;
    transition: opacity var(--duration-fast) var(--ease-standard),
                background var(--duration-fast) var(--ease-standard);
  }
  .roadmap-arrow:hover:not(:disabled) { background: var(--surface-container-low); }
  .roadmap-arrow:disabled { opacity: 0.25; cursor: default; }

  .carousel-wrap { position: relative; }

  .carousel-scroll {
    overflow-x: auto;
    scroll-snap-type: x mandatory;
    scroll-behavior: smooth;
    scrollbar-width: none;
    border-top: 0.5px solid rgba(0, 0, 0, 0.08);
    border-bottom: 0.5px solid rgba(0, 0, 0, 0.08);
  }
  .carousel-scroll::-webkit-scrollbar { display: none; }

  .carousel-strip {
    display: flex;
  }
  .carousel-card {
    flex: 0 0 calc((100% - 2px) / 3);
    scroll-snap-align: start;
    background: var(--background);
    padding: 24px 26px;
    box-sizing: border-box;
    border-right: 0.5px solid rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    gap: 12px;
    min-height: 168px;
  }
  .carousel-card:last-child { border-right: none; }

  .carousel-fade-right {
    position: absolute;
    right: 0; top: 0; bottom: 0;
    width: 80px;
    background: linear-gradient(to right, transparent, var(--background));
    pointer-events: none;
    transition: opacity 0.2s ease;
  }

  /* Card contents */
  .card-status {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .card-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    flex-shrink: 0;
  }
  .card-status-label {
    font-family: var(--font-sans);
    font-size: 11px;
    letter-spacing: var(--tracking-wider);
    font-weight: 600;
  }
  .card-title {
    font-family: var(--font-serif);
    font-weight: 400;
    font-size: 19px;
    line-height: 1.2;
    color: var(--on-surface);
    margin: 0;
  }
  .card-desc {
    font-size: 13px;
    line-height: 1.55;
    color: var(--on-surface-variant);
    margin: 0;
  }
  .card-attribution {
    color: var(--on-surface-muted);
  }

  /* Mobile: one card per view */
  @media (max-width: 768px) {
    .carousel-card { flex: 0 0 88%; }
    .roadmap-arrows { display: none; }
    .carousel-fade-right { display: none; }
  }
</style>
