<script lang="ts">
  import { solve } from '$lib/engine';
  import type { CalculatorDef } from '$lib/data/calculators';

  export let config: CalculatorDef;

  const numericSamples = [0.1, 0.5, 1, 2, 5, 10, 20, 50, 100];

  type Row = { input: number; output: string };

  const buildRow = (value: number, c: CalculatorDef): Row => {
    const formatted = solve(c, 1, value.toString(), '', '');
    return {
      input: value,
      output: formatted.val2 || '—',
    };
  };

  let rows: Row[] = [];
  let supportsTable = false;
  let inputLabel = 'source units';
  let outputLabel = 'target units';

  $: supportsTable = ['standard', 'inverse'].includes(config.type);
  $: rows = (config && supportsTable)
    ? numericSamples.map(v => buildRow(v, config))
    : [];
  $: inputLabel = config.labels?.in1 ?? 'source units';
  $: outputLabel = config.labels?.in2 ?? 'target units';
</script>

{#if supportsTable && rows.length}
  <section class="quick-chart">
    <h3>Quick conversion chart</h3>
    {#if config.labels.in1 && config.labels.in2}
      <p class="chart-note">
        {config.labels.in1} to {config.labels.in2} conversions for reference values.
      </p>
    {/if}
    <div class="chart-grid">
      {#each rows as row}
        <div class="chart-row">
          <p class="chart-statement">
            Converting {row.input} <span class="chart-unit">{inputLabel}</span> into <span class="chart-unit">{outputLabel}</span> equals
            <span class="chart-output-value">{row.output}</span>
            <span class="chart-output-unit">{outputLabel}</span>.
          </p>
        </div>
      {/each}
    </div>
  </section>
{/if}

<style>
  .quick-chart {
    margin: 1rem 2rem 2rem;
    padding: 1rem 1.25rem;
    border-radius: 12px;
    background: var(--section-bg);
    border: 1px solid var(--border);
  }

  .quick-chart h3 {
    margin: 0 0 0.5rem;
    font-size: 1rem;
    font-weight: 600;
  }

  .chart-note {
    margin: 0 0 0.75rem;
    font-size: 0.85rem;
    color: var(--text-muted);
  }

  .chart-grid {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
  }

  .chart-row {
    font-size: 0.95rem;
  }

  .chart-statement {
    margin: 0;
    font-weight: 600;
    line-height: 1.25;
  }

  .chart-output-value {
    margin: 0 0.25rem;
    font-weight: 600;
    color: var(--text);
  }

  .chart-unit,
  .chart-output-unit {
    font-variant: petite-caps;
  }

  @media (max-width: 640px) {
    .quick-chart {
      margin: 0.75rem 1.25rem 1.25rem;
      padding: 0.9rem 1rem;
    }
    .chart-row {
      font-size: 0.9rem;
    }
    .chart-statement {
      line-height: 1.35;
    }
  }
</style>
