<script lang="ts">
  import { goto } from '$app/navigation';
  import { api } from '$lib/api';
  import { featureFlags } from '$lib/features';
  import { clientSession, hasModuleAccess } from '$lib/session';
  import { toast } from '$lib/toast';
  import type {
    MixCalculatorCreateInput,
    MixCalculatorOptions,
    MixCalculatorPreview,
    MixCalculatorSession
  } from '$lib/types';

  let { options, initialSession = null }: { options: MixCalculatorOptions; initialSession?: MixCalculatorSession | null } = $props();

  const todayIso = new Date().toISOString().slice(0, 10);

  function initialClientNameValue() {
    return initialSession?.client_name ?? options.clients[0] ?? '';
  }

  function initialProductIdValue() {
    return initialSession?.product_id ?? 0;
  }

  function initialMixDateValue() {
    return initialSession?.mix_date ?? todayIso;
  }

  function initialBatchSizeValue() {
    return initialSession ? `${initialSession.batch_size_kg}` : '';
  }

  function initialPreparedByNameValue() {
    return initialSession?.prepared_by_name ?? '';
  }

  function initialNotesValue() {
    return initialSession?.notes ?? '';
  }

  function initialPreviewValue() {
    return initialSession;
  }

  let clientName = $state(initialClientNameValue());
  let productId = $state(initialProductIdValue());
  let mixDate = $state(initialMixDateValue());
  let batchSizeKg = $state(initialBatchSizeValue());
  let preparedByName = $state(initialPreparedByNameValue());
  let notes = $state(initialNotesValue());
  let preview = $state<MixCalculatorPreview | MixCalculatorSession | null>(initialPreviewValue());
  let formError = $state('');
  let formSuccess = $state('');
  let previewLoading = $state(false);
  let saveLoading = $state(false);

  const canEdit = $derived(hasModuleAccess($clientSession, 'mix_calculator', 'edit'));
  const isExistingSession = $derived(initialSession !== null);
  const availableClients = $derived(
    Array.from(new Set([...(options.clients ?? []), ...(initialSession ? [initialSession.client_name] : [])]))
  );
  const availableProducts = $derived(
    initialSession && !options.products.some((product) => product.product_id === initialSession.product_id)
      ? [
          ...options.products,
          {
            product_id: initialSession.product_id,
            client_name: initialSession.client_name,
            product_name: initialSession.product_name,
            mix_id: initialSession.mix_id,
            mix_name: initialSession.mix_name,
            unit_of_measure: initialSession.product_unit_of_measure,
            unit_size_kg: initialSession.product_unit_size_kg,
            mix_total_kg: initialSession.total_kg
          }
        ]
      : options.products
  );
  const filteredProducts = $derived(availableProducts.filter((product) => product.client_name === clientName));
  const selectedProduct = $derived(filteredProducts.find((product) => product.product_id === productId) ?? null);

  $effect(() => {
    if (!clientName && availableClients.length) {
      clientName = availableClients[0];
    }
  });

  $effect(() => {
    if (filteredProducts.length && !filteredProducts.some((product) => product.product_id === productId)) {
      productId = filteredProducts[0].product_id;
      return;
    }

    if (!filteredProducts.length) {
      productId = 0;
    }
  });

  $effect(() => {
    if (!preparedByName && $clientSession?.name) {
      preparedByName = $clientSession.name;
    }
  });

  function formatDate(value: string) {
    return new Intl.DateTimeFormat('en-NZ', {
      dateStyle: 'medium'
    }).format(new Date(value));
  }

  function formatNumber(value: number | null | undefined, digits = 2) {
    if (value === null || value === undefined) {
      return 'N/A';
    }

    return value.toFixed(digits);
  }

  function buildPayload(): MixCalculatorCreateInput | null {
    formError = '';
    formSuccess = '';

    const numericBatchSize = Number(batchSizeKg);
    if (!mixDate) {
      formError = 'Select a mix date.';
      return null;
    }
    if (!clientName) {
      formError = 'Select a client.';
      return null;
    }
    if (!productId) {
      formError = 'Select a product.';
      return null;
    }
    if (!Number.isFinite(numericBatchSize) || numericBatchSize <= 0) {
      formError = 'Enter a batch size greater than zero.';
      return null;
    }
    if (!preparedByName.trim()) {
      formError = 'Enter the prepared by name.';
      return null;
    }

    return {
      mix_date: mixDate,
      client_name: clientName,
      product_id: productId,
      batch_size_kg: numericBatchSize,
      prepared_by_name: preparedByName.trim(),
      status: initialSession?.status ?? 'saved',
      notes: notes.trim() || null
    };
  }

  async function calculatePreview() {
    const payload = buildPayload();
    if (!payload) {
      toast.error(formError);
      return;
    }

    previewLoading = true;
    const tid = toast.loading('Calculating…');
    try {
      preview = await api.previewMixCalculatorSession(payload);
      toast.dismiss(tid);
    } catch (error) {
      toast.dismiss(tid);
      toast.error(error instanceof Error ? error.message : 'Unable to calculate the mix session.');
      formError = error instanceof Error ? error.message : 'Unable to calculate the mix session.';
    } finally {
      previewLoading = false;
    }
  }

  function clearForm() {
    clientName = options.clients[0] ?? '';
    productId = 0;
    mixDate = todayIso;
    batchSizeKg = '';
    preparedByName = $clientSession?.name ?? '';
    notes = '';
    preview = null;
    formError = '';
    formSuccess = '';
  }

  function printPreview() {
    if (typeof window !== 'undefined') {
      window.print();
    }
  }

  async function saveSession(mode: 'update' | 'create', destination: 'detail' | 'print' = 'detail') {
    const payload = buildPayload();
    if (!payload) {
      return;
    }

    saveLoading = true;
    const tid = toast.loading(mode === 'update' ? 'Saving session…' : 'Creating session…');
    try {
      const saved =
        mode === 'update' && initialSession
          ? await api.updateMixCalculatorSession(initialSession.id, payload)
          : await api.createMixCalculatorSession(payload);

      toast.dismiss(tid);
      toast.success(mode === 'update' ? 'Session saved' : 'Session created');
      const target = destination === 'print' ? `/mix-calculator/${saved.id}/print` : `/mix-calculator/${saved.id}`;
      await goto(target);
    } catch (error) {
      toast.dismiss(tid);
      toast.error(error instanceof Error ? error.message : 'Unable to save the mix calculator session.');
      formError = error instanceof Error ? error.message : 'Unable to save the mix calculator session.';
      saveLoading = false;
    }
  }
</script>

{#if !canEdit && !initialSession}
  <section class="locked-card">
    <p class="eyebrow">Mix Calculator</p>
    <h2>Edit access is required to create a new session.</h2>
    <p>View-only users can open saved sessions from history, but cannot create or update production calculations.</p>
    {#if featureFlags.mixCalculatorSessionHistory}
      <a class="secondary-button" href="/mix-calculator">Back to session history</a>
    {/if}
  </section>
{:else}
  {#if featureFlags.mixCalculatorSessionHistory || initialSession}
    <section class="page-actions">
      {#if featureFlags.mixCalculatorSessionHistory}
        <a class="secondary-button" href="/mix-calculator">Session history</a>
      {/if}
      {#if initialSession}
        <a class="secondary-button" href={`/mix-calculator/${initialSession.id}/print`}>Printable view</a>
      {/if}
    </section>
  {/if}

  <section class="workspace-grid">
    <article class="form-card">
      <div class="section-header">
        <div>
          <h3>Session Inputs</h3>
          <p>Batch size drives the scale factor. Total bags are derived from the selected product unit size.</p>
        </div>
        {#if selectedProduct}
          <div class="product-pill">
            <strong>{selectedProduct.unit_size_kg}kg</strong>
            <span>{selectedProduct.unit_of_measure}</span>
          </div>
        {/if}
      </div>

      {#if formError}
        <p class="message error">{formError}</p>
      {/if}
      {#if formSuccess}
        <p class="message success">{formSuccess}</p>
      {/if}

      <div class="field-grid">
        <label>
          <span>Mix date</span>
          <input bind:value={mixDate} disabled={!canEdit} type="date" />
        </label>

        <label>
          <span>Client</span>
          <select bind:value={clientName} disabled={!canEdit}>
            <option value="">Select a client</option>
            {#each availableClients as client}
              <option value={client}>{client}</option>
            {/each}
          </select>
        </label>

        <label class="full-width">
          <span>Product</span>
          <select bind:value={productId} disabled={!canEdit || !filteredProducts.length}>
            <option value={0}>Select a product</option>
            {#each filteredProducts as product}
              <option value={product.product_id}>
                {product.product_name} · {product.mix_name} · {product.unit_of_measure}
              </option>
            {/each}
          </select>
        </label>

        <label>
          <span>Batch size (kg)</span>
          <input bind:value={batchSizeKg} disabled={!canEdit} inputmode="decimal" min="0" placeholder="560" type="number" />
        </label>

        <label>
          <span>Prepared by</span>
          <input bind:value={preparedByName} disabled={!canEdit} placeholder="Staff name" type="text" />
        </label>

        <label class="full-width">
          <span>Notes</span>
          <textarea bind:value={notes} disabled={!canEdit} placeholder="Optional production notes or shift context" rows="4"></textarea>
        </label>
      </div>

      {#if canEdit && selectedProduct}
        <div class="calculation-note">
          <strong>Source mix</strong>
          <span>{selectedProduct.mix_name} totals {formatNumber(selectedProduct.mix_total_kg, 2)}kg. Scale factor = batch size / source mix total.</span>
        </div>
      {/if}

      {#if canEdit}
        <div class="action-row">
          <button class="primary-button" disabled={previewLoading || saveLoading} type="button" onclick={calculatePreview}>
            <span class="button-icon" style="--button-icon-url: url('/icons/calculator.svg');" aria-hidden="true"></span>
            <span>{previewLoading ? 'Calculating...' : 'Calculate mix'}</span>
          </button>

          {#if featureFlags.mixCalculatorSessionSave}
            <button class="secondary-button" disabled={saveLoading || previewLoading} type="button" onclick={() => saveSession(isExistingSession ? 'update' : 'create')}>
              {saveLoading ? 'Saving...' : isExistingSession ? 'Save changes' : 'Save session'}
            </button>

            <button class="secondary-button" disabled={saveLoading || previewLoading} type="button" onclick={() => saveSession(isExistingSession ? 'update' : 'create', 'print')}>
              <span class="button-icon" style="--button-icon-url: url('/icons/print.svg');" aria-hidden="true"></span>
              <span>{saveLoading ? 'Saving...' : 'Save & print'}</span>
            </button>

            {#if initialSession}
              <button class="secondary-button" disabled={saveLoading || previewLoading} type="button" onclick={() => saveSession('create')}>
                Save as new
              </button>
            {/if}
          {:else}
            <button class="secondary-button" disabled={previewLoading || saveLoading || !preview} type="button" onclick={printPreview}>
              <span class="button-icon" style="--button-icon-url: url('/icons/print.svg');" aria-hidden="true"></span>
              <span>Print</span>
            </button>
          {/if}

          <button class="secondary-button" disabled={previewLoading || saveLoading} type="button" onclick={clearForm}>
            <span class="button-icon" style="--button-icon-url: url('/icons/trash.svg');" aria-hidden="true"></span>
            <span>Clear</span>
          </button>
        </div>
      {/if}
    </article>

    <article class="result-card">
      <div class="section-header">
        <div>
          <h3>Calculated Output</h3>
          <p>{preview ? 'Snapshot of the scaled raw material requirements.' : 'Run the calculation to preview the session output.'}</p>
        </div>
        {#if initialSession}
          <div class="session-chip">
            <span>Session</span>
            <strong>{initialSession.session_number}</strong>
          </div>
        {/if}
      </div>

      {#if preview}
        <div class="metric-row">
          <article class="metric-card">
            <span>Total kg</span>
            <strong>{formatNumber(preview.total_kg, 2)}</strong>
            <p>Scaled batch size</p>
          </article>
          <article class="metric-card">
            <span>Total bags</span>
            <strong>{formatNumber(preview.total_bags, 2)}</strong>
            <p>{preview.product_unit_of_measure}</p>
          </article>
          <article class="metric-card">
            <span>Prepared by</span>
            <strong>{preview.prepared_by_name}</strong>
            <p>{formatDate(preview.mix_date)}</p>
          </article>
        </div>

        {#if preview.warnings.length}
          <div class="warning-stack">
            {#each preview.warnings as warning}
              <p>{warning}</p>
            {/each}
          </div>
        {/if}

        <div class="summary-grid">
          <div>
            <span>Client</span>
            <strong>{preview.client_name}</strong>
          </div>
          <div>
            <span>Product</span>
            <strong>{preview.product_name}</strong>
          </div>
          <div>
            <span>Mix source</span>
            <strong>{preview.mix_name}</strong>
          </div>
          <div>
            <span>Unit size</span>
            <strong>{formatNumber(preview.product_unit_size_kg, 2)}kg</strong>
          </div>
        </div>

        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Raw material</th>
                <th>Mix %</th>
                <th>Required kg</th>
                <th>Unit</th>
              </tr>
            </thead>
            <tbody>
              {#each preview.lines as line}
                <tr>
                  <td data-label="Raw material">
                    <strong>{line.raw_material_name}</strong>
                  </td>
                  <td data-label="Mix %">{formatNumber(line.mix_percentage, 2)}%</td>
                  <td data-label="Required kg">{formatNumber(line.required_kg, 2)}kg</td>
                  <td data-label="Unit">{line.unit}</td>
                </tr>
              {/each}
            </tbody>
          </table>
        </div>
      {:else}
        <div class="empty-state">
          <div class="empty-shimmer-metrics">
            <div class="shimmer-metric"><div class="shimmer-line short"></div><div class="shimmer-line wide"></div></div>
            <div class="shimmer-metric"><div class="shimmer-line short"></div><div class="shimmer-line wide"></div></div>
            <div class="shimmer-metric"><div class="shimmer-line short"></div><div class="shimmer-line wide"></div></div>
          </div>
          <div class="empty-state-copy">
            <div class="empty-icon" aria-hidden="true">
              <span></span><span></span><span></span>
            </div>
            <strong>No calculation yet</strong>
            <span>Choose a client, product, date, and batch size on the left, then click Calculate mix.</span>
          </div>
          <div class="empty-shimmer-rows">
            {#each [1,2,3,4,5] as _}
              <div class="shimmer-row">
                <div class="shimmer-line wide"></div>
                <div class="shimmer-line medium"></div>
                <div class="shimmer-line medium"></div>
                <div class="shimmer-line short"></div>
              </div>
            {/each}
          </div>
        </div>
      {/if}
    </article>
  </section>

  {#if preview}
    <section class="print-only" aria-hidden="true">
      <article class="print-sheet">
        <header class="print-header">
          <div>
            <p class="print-eyebrow">Mix Calculator</p>
            <h1>{preview.product_name}</h1>
            <p class="print-subtitle">{preview.client_name} · {preview.mix_name}</p>
          </div>
          <div class="print-meta">
            <div>
              <span>Mix date</span>
              <strong>{formatDate(preview.mix_date)}</strong>
            </div>
            <div>
              <span>Prepared by</span>
              <strong>{preview.prepared_by_name}</strong>
            </div>
          </div>
        </header>

        <section class="print-summary">
          <div>
            <span>Batch size</span>
            <strong>{formatNumber(preview.batch_size_kg, 2)}kg</strong>
          </div>
          <div>
            <span>Total kilograms</span>
            <strong>{formatNumber(preview.total_kg, 2)}kg</strong>
          </div>
          <div>
            <span>Total bags</span>
            <strong>{formatNumber(preview.total_bags, 2)}</strong>
          </div>
          <div>
            <span>Unit size</span>
            <strong>{formatNumber(preview.product_unit_size_kg, 2)}kg</strong>
          </div>
        </section>

        {#if preview.notes}
          <section class="print-notes">
            <h2>Notes</h2>
            <p>{preview.notes}</p>
          </section>
        {/if}

        {#if preview.warnings.length}
          <section class="print-warnings">
            <h2>Warnings</h2>
            {#each preview.warnings as warning}
              <p>{warning}</p>
            {/each}
          </section>
        {/if}

        <section class="print-table">
          <div class="print-table-header">
            <h2>Required raw materials</h2>
            <span>{preview.product_unit_of_measure} · {formatNumber(preview.product_unit_size_kg, 2)}kg per unit</span>
          </div>
          <table>
            <thead>
              <tr>
                <th>Raw material</th>
                <th>Mix %</th>
                <th>Required kg</th>
                <th>Unit</th>
              </tr>
            </thead>
            <tbody>
              {#each preview.lines as line}
                <tr>
                  <td>{line.raw_material_name}</td>
                  <td>{formatNumber(line.mix_percentage, 2)}%</td>
                  <td>{formatNumber(line.required_kg, 2)}kg</td>
                  <td>{line.unit}</td>
                </tr>
              {/each}
            </tbody>
          </table>
        </section>
      </article>
    </section>
  {/if}
{/if}

<style>
  h2,
  h3,
  p {
    margin: 0;
  }

  .eyebrow {
    color: #7d8d84;
    font-size: 0.78rem;
    font-weight: 600;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    display: inline-flex;
    align-items: center;
    gap: 0.45rem;
  }

  .eyebrow-icon {
    display: inline-block;
    width: 0.95rem;
    height: 0.95rem;
    background-color: currentColor;
    -webkit-mask: var(--button-icon-url) center / contain no-repeat;
    mask: var(--button-icon-url) center / contain no-repeat;
  }

  .page-actions,
  .workspace-grid {
    margin-bottom: 1.2rem;
  }

  .page-actions {
    display: flex;
    justify-content: flex-end;
    gap: 0.75rem;
    flex-wrap: wrap;
  }

  .page-intro {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 1rem;
  }

  .page-intro h2 {
    margin: 0.3rem 0 0.45rem;
    max-width: 16ch;
    font-size: clamp(1.7rem, 3vw, 2.2rem);
    font-weight: 700;
  }

  .page-intro p:last-child,
  .section-header p,
  .metric-card p,
  .summary-grid span,
  .calculation-note span,
  .empty-state span {
    color: var(--muted);
  }

  .header-actions,
  .action-row {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    flex-wrap: wrap;
  }

  .workspace-grid {
    display: grid;
    grid-template-columns: minmax(0, 0.95fr) minmax(0, 1.05fr);
    gap: 1rem;
  }

  .form-card,
  .result-card,
  .metric-card,
  .locked-card {
    border: 1px solid var(--line);
    border-radius: 1.3rem;
    background: var(--panel);
    box-shadow: var(--shadow);
  }

  .form-card,
  .result-card,
  .locked-card {
    padding: 1.2rem;
  }

  .locked-card {
    max-width: 42rem;
  }

  .locked-card h2 {
    margin: 0.35rem 0 0.45rem;
    font-size: clamp(1.7rem, 3vw, 2.1rem);
  }

  .section-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 1rem;
    margin-bottom: 1rem;
  }

  .section-header h3 {
    font-size: 1.15rem;
    font-weight: 700;
  }

  .product-pill,
  .session-chip {
    display: grid;
    gap: 0.14rem;
    padding: 0.72rem 0.82rem;
    border: 1px solid var(--line);
    border-radius: 0.92rem;
    background: var(--panel-soft);
  }

  .product-pill span,
  .session-chip span {
    color: var(--muted);
    font-size: 0.78rem;
    text-transform: uppercase;
    letter-spacing: 0.06em;
  }

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

  .field-grid label {
    display: grid;
    gap: 0.38rem;
  }

  .field-grid label span {
    font-size: 0.88rem;
    font-weight: 600;
  }

  .full-width {
    grid-column: 1 / -1;
  }

  input,
  select,
  textarea {
    width: 100%;
    padding: 0.78rem 0.82rem;
    border: 1px solid var(--line-strong);
    border-radius: 0.88rem;
    background: #fff;
    color: var(--text);
  }

  textarea {
    resize: vertical;
  }

  .calculation-note,
  .warning-stack,
  .empty-state {
    margin-top: 1rem;
    padding: 0.92rem;
    border-radius: 1rem;
  }

  .calculation-note {
    display: grid;
    gap: 0.2rem;
    background: var(--panel-soft);
  }

  .warning-stack {
    display: grid;
    gap: 0.45rem;
    background: #fff6e6;
    color: #8b5b1e;
  }

  .message {
    margin-bottom: 0.85rem;
    padding: 0.75rem 0.85rem;
    border-radius: 0.88rem;
    font-size: 0.9rem;
  }

  .message.error {
    background: #fff1f0;
    color: #b2463f;
  }

  .message.success {
    background: var(--green-soft);
    color: var(--green-deep);
  }

  .action-row {
    margin-top: 1rem;
  }

  .primary-button,
  .secondary-button {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    padding: 0.78rem 0.96rem;
    border-radius: 0.9rem;
    border: 1px solid var(--line-strong);
    font-weight: 600;
    cursor: pointer;
    transition:
      transform 140ms ease,
      box-shadow 140ms ease,
      background-color 140ms ease,
      border-color 140ms ease;
  }

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

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

  .primary-button:hover:not(:disabled),
  .secondary-button:hover:not(:disabled) {
    transform: translateY(-1px);
  }

  .primary-button:hover:not(:disabled) {
    box-shadow: none;
    filter: brightness(1.04);
  }

  .secondary-button:hover:not(:disabled) {
    border-color: #9fb0a6;
    background: #f6faf7;
    box-shadow: none;
  }

  .button-icon {
    display: inline-block;
    width: 1rem;
    height: 1rem;
    background-color: currentColor;
    -webkit-mask: var(--button-icon-url) center / contain no-repeat;
    mask: var(--button-icon-url) center / contain no-repeat;
    flex-shrink: 0;
  }

  button:disabled {
    cursor: wait;
    opacity: 0.7;
  }

  .metric-row,
  .summary-grid {
    display: grid;
    gap: 0.85rem;
  }

  .metric-row {
    grid-template-columns: repeat(3, minmax(0, 1fr));
    margin-bottom: 1rem;
  }

  .metric-card {
    padding: 1rem;
  }

  .metric-card span {
    display: block;
    color: var(--muted);
    font-size: 0.84rem;
  }

  .metric-card strong {
    display: block;
    margin: 0.45rem 0 0.18rem;
    font-size: 1.45rem;
  }

  .summary-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
    margin-bottom: 1rem;
  }

  .summary-grid div {
    padding: 0.88rem 0.92rem;
    border: 1px solid var(--line);
    border-radius: 1rem;
    background: var(--panel-soft);
  }

  .summary-grid span {
    display: block;
    margin-bottom: 0.2rem;
    font-size: 0.78rem;
    text-transform: uppercase;
    letter-spacing: 0.06em;
  }

  .table-wrap {
    overflow-x: auto;
  }

  table {
    width: 100%;
    min-width: 30rem;
    border-collapse: collapse;
  }

  th,
  td {
    padding: 0.9rem 0.85rem;
    text-align: left;
    border-bottom: 1px solid var(--line);
  }

  th {
    color: var(--muted);
    font-size: 0.78rem;
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    gap: 0;
    border-radius: 1rem;
    overflow: hidden;
    border: 1px solid var(--line);
  }

  .empty-shimmer-metrics {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 0.75rem;
    padding: 1rem;
    border-bottom: 1px solid var(--line);
    background: var(--panel-soft);
  }

  .shimmer-metric {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    padding: 0.85rem;
    border: 1px solid var(--line);
    border-radius: 0.85rem;
    background: var(--panel);
  }

  .empty-state-copy {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.5rem;
    padding: 2rem 1.5rem;
    text-align: center;
    background: var(--panel);
    border-bottom: 1px solid var(--line);
  }

  .empty-state-copy strong {
    font-size: 0.98rem;
    font-weight: 700;
    color: var(--text);
  }

  .empty-state-copy span {
    max-width: 26rem;
    font-size: 0.84rem;
    color: var(--muted);
    line-height: 1.5;
  }

  .empty-icon {
    display: flex;
    align-items: flex-end;
    gap: 0.28rem;
    height: 2.2rem;
    margin-bottom: 0.35rem;
  }

  .empty-icon span {
    width: 0.38rem;
    border-radius: 999px 999px 0 0;
    background: var(--color-border);
    animation: bar-pulse 1.6s ease-in-out infinite;
  }

  .empty-icon span:nth-child(1) { height: 60%; animation-delay: 0s; }
  .empty-icon span:nth-child(2) { height: 100%; animation-delay: 0.2s; }
  .empty-icon span:nth-child(3) { height: 40%; animation-delay: 0.4s; }

  @keyframes bar-pulse {
    0%, 100% { opacity: 0.35; }
    50%       { opacity: 1; }
  }

  .empty-shimmer-rows {
    display: flex;
    flex-direction: column;
    background: var(--panel-soft);
  }

  .shimmer-row {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr 0.75fr;
    gap: 1rem;
    align-items: center;
    padding: 0.78rem 1rem;
    border-bottom: 1px solid var(--line);
  }

  .shimmer-row:last-child {
    border-bottom: none;
  }

  .shimmer-line {
    height: 0.7rem;
    border-radius: 999px;
    background: linear-gradient(
      90deg,
      var(--color-border) 25%,
      color-mix(in srgb, var(--color-border) 40%, white) 50%,
      var(--color-border) 75%
    );
    background-size: 200% 100%;
    animation: shimmer 1.8s ease-in-out infinite;
  }

  .shimmer-line.short  { width: 40%; }
  .shimmer-line.medium { width: 65%; }
  .shimmer-line.wide   { width: 90%; }

  @keyframes shimmer {
    0%   { background-position: 200% 0; }
    100% { background-position: -200% 0; }
  }

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

    .metric-row {
      grid-template-columns: 1fr;
    }
  }

  @media (max-width: 720px) {
    .page-intro,
    .section-header {
      flex-direction: column;
    }

    .field-grid,
    .summary-grid {
      grid-template-columns: 1fr;
    }

    table,
    thead,
    tbody,
    tr,
    td {
      display: block;
      width: 100%;
    }

    thead {
      display: none;
    }

    tbody {
      display: grid;
      gap: 0.75rem;
    }

    tbody tr {
      border: 1px solid var(--line);
      border-radius: 1rem;
      background: var(--panel-soft);
      overflow: hidden;
    }

    tbody td {
      border-bottom: 1px solid var(--line);
    }

    tbody td:last-child {
      border-bottom: none;
    }

    tbody td::before {
      content: attr(data-label);
      display: block;
      margin-bottom: 0.24rem;
      color: var(--muted);
      font-size: 0.72rem;
      font-weight: 700;
      letter-spacing: 0.06em;
      text-transform: uppercase;
    }
  }

  .print-only {
    display: none;
  }

  @media print {
    :global(body) {
      background: #fff !important;
      margin: 0 !important;
    }

    :global(body *) {
      visibility: hidden !important;
    }

    .print-only,
    .print-only :global(*) {
      visibility: visible !important;
    }

    .print-only {
      display: block;
      position: absolute;
      inset: 0;
      padding: 1.4cm;
      background: #fff;
      color: #1a2421;
      font-family: inherit;
    }

    .print-sheet {
      width: 100%;
    }

    .print-header {
      display: flex;
      justify-content: space-between;
      gap: 1.5rem;
      padding-bottom: 1rem;
      border-bottom: 1px solid #cbd6cf;
    }

    .print-header h1 {
      margin: 0.25rem 0 0.3rem;
      font-size: 1.7rem;
    }

    .print-eyebrow {
      color: #5f6f67;
      font-size: 0.72rem;
      font-weight: 700;
      letter-spacing: 0.08em;
      text-transform: uppercase;
      margin: 0;
    }

    .print-subtitle {
      color: #5f6f67;
      margin: 0;
    }

    .print-meta {
      display: grid;
      gap: 0.55rem;
      min-width: 12rem;
    }

    .print-meta div,
    .print-summary div {
      display: grid;
      gap: 0.1rem;
    }

    .print-meta span,
    .print-summary span,
    .print-table-header span {
      color: #5f6f67;
      font-size: 0.72rem;
      letter-spacing: 0.04em;
      text-transform: uppercase;
    }

    .print-summary {
      display: grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 0.85rem;
      padding: 1rem 0;
      border-bottom: 1px solid #cbd6cf;
    }

    .print-notes,
    .print-warnings {
      margin-top: 0.85rem;
      padding: 0.75rem 0.9rem;
      border: 1px solid #cbd6cf;
      border-radius: 0.5rem;
    }

    .print-warnings {
      border-color: #d8a76b;
      background: #fff6e6;
      color: #8b5b1e;
    }

    .print-notes h2,
    .print-warnings h2,
    .print-table-header h2 {
      margin: 0 0 0.35rem;
      font-size: 0.95rem;
    }

    .print-table {
      margin-top: 1rem;
    }

    .print-table-header {
      display: flex;
      align-items: baseline;
      justify-content: space-between;
      gap: 1rem;
      margin-bottom: 0.5rem;
    }

    .print-table table {
      width: 100%;
      border-collapse: collapse;
    }

    .print-table th,
    .print-table td {
      padding: 0.55rem 0.5rem;
      text-align: left;
      border-bottom: 1px solid #cbd6cf;
      font-size: 0.92rem;
    }

    .print-table th {
      color: #5f6f67;
      font-size: 0.72rem;
      letter-spacing: 0.06em;
      text-transform: uppercase;
    }

    @page {
      margin: 1cm;
    }
  }
</style>
