<script lang="ts">
  import { api } from '$lib/api';
  import MixCalculatorPrintDocument from '$lib/components/MixCalculatorPrintDocument.svelte';
  import type { MixCalculatorSession } from '$lib/types';

  let { session }: { session: MixCalculatorSession } = $props();

  const printableTitle = $derived(
    `MixCalculator_${session.client_name}_${session.product_name}_${session.mix_date}_${session.session_number}`.replace(/[^\w.-]+/g, '_')
  );

  async function downloadPdf() {
    const blob = await api.mixCalculatorSessionPdf(session.id);
    const url = URL.createObjectURL(blob);
    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = `${printableTitle}.pdf`;
    document.body.appendChild(anchor);
    anchor.click();
    anchor.remove();
    URL.revokeObjectURL(url);
  }
</script>

<svelte:head>
  <title>{printableTitle}</title>
</svelte:head>

<section class="print-page">
  <div class="print-toolbar">
    <a class="secondary-button" href={`/mix-calculator/${session.id}`}>Back to session</a>
    <button class="secondary-button" type="button" onclick={downloadPdf}>Download PDF</button>
    <button class="primary-button" type="button" onclick={() => window.print()}>Print / Save PDF</button>
  </div>

  <MixCalculatorPrintDocument session={session} generatedAt={new Date().toISOString()} />
</section>

<style>
  .print-page {
    display: grid;
    gap: 1rem;
    justify-items: center;
    padding: 1.5rem 1rem 2.5rem;
    background:
      linear-gradient(180deg, #eef4f0 0%, #e6eee9 100%);
  }

  .print-toolbar {
    display: flex;
    justify-content: flex-end;
    gap: 0.75rem;
  }

  .primary-button,
  .secondary-button {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.78rem 0.96rem;
    border-radius: 0.9rem;
    border: 1px solid var(--line-strong);
    font-weight: 600;
    cursor: pointer;
  }

  .primary-button {
    border: none;
    background: var(--color-brand);
    color: #fff;
  }

  .secondary-button {
    background: #fff;
    color: #304038;
  }

  @media (max-width: 900px) {
    .print-toolbar {
      justify-content: stretch;
    }

    .print-toolbar > :global(*) {
      flex: 1 1 auto;
    }
  }

  @media print {
    :global(body) {
      background: #fff;
    }

    .print-page {
      padding: 0;
      background: #fff;
    }

    .print-toolbar {
      display: none;
    }
  }
</style>
