<script lang="ts">
  import type { CalendarEvent } from '$lib/types.js';

  let { events }: { events: CalendarEvent[] } = $props();

  type EventType = 'earnings' | 'exdividend' | 'dividend';
  const eventIcon  = (t: EventType): string => ({ earnings: '📊', exdividend: '💰', dividend: '💵' })[t] ?? '📅';
  const eventColor = (t: EventType): string =>
    ({ earnings: '#60a5fa', exdividend: '#facc15', dividend: '#4ade80' })[t] ?? '#94a3b8';

  const fmtMoney = (n: number | null | undefined): string | null => n == null ? null :
    n >= 1e9 ? '$' + (n / 1e9).toFixed(1) + 'B' :
    n >= 1e6 ? '$' + (n / 1e6).toFixed(1) + 'M' : '$' + n.toFixed(2);

  const upcoming = $derived(events.filter(e => !e.isPast).slice(0, 20));
  const past     = $derived(events.filter(e => e.isPast).slice(0, 10));
</script>

{#if events.length > 0}
  <section class="section">
    <div class="section-header">
      <h2>📅 Upcoming Events</h2>
      <span class="count">{upcoming.length} upcoming</span>
      {#if past.length > 0}
        <span class="count" style="margin-left:4px">{past.length} recent</span>
      {/if}
    </div>
    <div class="cal-grid">
      {#each upcoming as ev}
        <div class="cal-event">
          <div class="cal-date">{ev.date}</div>
          <div class="cal-content">
            <span class="cal-ticker">{ev.ticker}</span>
            <span class="cal-type" style="color:{eventColor(ev.type)}">
              {eventIcon(ev.type)} {ev.label}
              {#if ev.detail}<span class="cal-detail">· {ev.detail}</span>{/if}
            </span>
            {#if ev.epsEstimate != null}
              <span class="cal-est">EPS est. ${ev.epsEstimate.toFixed(2)} · Rev est. {fmtMoney(ev.revEstimate)}</span>
            {/if}
          </div>
        </div>
      {/each}

      {#if past.length > 0}
        <div class="cal-divider">— Past —</div>
        {#each past as ev}
          <div class="cal-event past">
            <div class="cal-date">{ev.date}</div>
            <div class="cal-content">
              <span class="cal-ticker">{ev.ticker}</span>
              <span class="cal-type past-type">{eventIcon(ev.type)} {ev.label}</span>
            </div>
          </div>
        {/each}
      {/if}
    </div>
  </section>
{/if}

