<script lang="ts">
  import { parseScientificNotation, type ScientificNotationParts } from '$lib/utils/formatScientific';

  export let value: string | number | null | undefined = null;
  export let fallback = '—';
  export let className = '';

  const formattedValue = value == null ? '' : `${value}`;
  const scientific: ScientificNotationParts | null = formattedValue
    ? parseScientificNotation(formattedValue)
    : null;
</script>

{#if scientific}
  <span class={`scientific-notation ${className}`.trim()}>
    <span class="scientific-base">{scientific.base}</span>
    <span class="scientific-suffix">
      ×10<sup>{scientific.exponent}</sup>
    </span>
  </span>
{:else}
  <span class={`scientific-plain ${className}`.trim()}>
    {formattedValue || fallback}
  </span>
{/if}

<style>
  .scientific-notation,
  .scientific-plain {
    display: inline-flex;
    align-items: baseline;
    gap: 0.15rem;
  }

  .scientific-suffix {
    display: inline-flex;
    align-items: baseline;
    gap: 0.15rem;
    font-size: 0.85em;
  }

  .scientific-suffix sup {
    font-size: 0.75em;
    vertical-align: super;
  }
</style>
