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

  export let config: CalculatorDef;

  const exampleInput = 15;

  let supportsExample = false;
  $: supportsExample =
    config.type === 'standard' &&
    typeof config.factor === 'number' &&
    !!config.labels.in1 &&
    !!config.labels.in2;

  $: result = supportsExample
    ? solve(config, 1, exampleInput.toString(), '', '')
    : null;
  $: offset = config.offset ?? 0;
  $: hasOffset = Boolean(offset);
  $: formattedFactorValue = supportsExample
    ? formatConversionValue(config.factor)
    : '';
  $: formattedOffsetValue = hasOffset
    ? formatConversionValue(offset)
    : '';
  $: formulaExpression = supportsExample
    ? `${exampleInput} x ${formattedFactorValue}${hasOffset ? ` ${offset > 0 ? '+' : '-'} ${formatConversionValue(Math.abs(offset))}` : ''}`
    : '';

  $: reverseExampleValue =
    supportsExample && typeof config.factor === 'number' && config.factor !== 0
      ? (1 - offset) / config.factor
      : null;
  $: formattedReverseValue = formatConversionValue(reverseExampleValue);
</script>

{#if supportsExample && result}
  <section class="example-card">
    <h3>How to convert {config.labels.in1} to {config.labels.in2}</h3>
    {#if hasOffset}
      <p class="example-note">
        Formula: {config.labels.in2} = ({config.labels.in1} x {formattedFactorValue}) {offset > 0 ? '+' : '-'} {formatConversionValue(Math.abs(offset))}
      </p>
    {:else}
      <p class="example-note">
        1 {config.labels.in1} = {formattedFactorValue} {config.labels.in2}
      </p>
      <p class="example-note">
        1 {config.labels.in2} = {formattedReverseValue} {config.labels.in1}
      </p>
    {/if}
    <p class="example-line">
      Example: convert {exampleInput} {config.labels.in1} to {config.labels.in2}
    </p>
    <p class="example-line">
      {formulaExpression} =
      <span class="example-result">{result.val2} {config.labels.in2}</span>
    </p>
  </section>
{/if}

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

  .example-card h3 {
    margin: 0 0 0.25rem;
    font-size: 1rem;
    font-weight: 600;
  }

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

  .example-line {
    margin: 0;
    font-size: 0.9rem;
    line-height: 1.4;
    color: var(--text);
  }

  .example-result {
    font-weight: 600;
    margin-left: 0.35rem;
  }

  @media (max-width: 640px) {
    .example-card {
      margin: 0 1.25rem 1.25rem;
      padding: 1rem;
    }
  }
</style>
