<script>
  /** @type {{value: string, text: string}[]} */
  export let options = []
  export let value = "";
  export let label = "Select";
  export let prefer = null;
  export let color = "#ffffff";
  export let bgcolor = "#444444";

  $: {
    if (options.length > 0 && !options.find(o => o.value === value)) {
      if (prefer != null) {
        const preferred = options.find(o => o.value.includes(prefer));
        if (preferred != null) {
          value = preferred.value;
        } else {
          value = options[0].value;
        }
      } else {
        value = options[0].value;
      }    
    }
  }
</script>

<div class="selector" style="--color: {color || "#ffcc11"}; --bgcolor: {bgcolor || "#776655"}">
  <h2>{label}</h2>
  {#each options as option (option.value)}
    <div on:click={() => value = option.value} class="option" class:selected={option.value === value}>{option.text}</div>
  {/each}
</div>

<style>
  .selector {
    margin: auto;
  }

  h2 {
    font-size: 1.25em;
    margin-top: 1em;
  }

  .option {
    display: inline-block;
    margin: 0;
    padding: 0.5em 1.5ch;
    line-height: 1.1em;
    background: #333;
    border: 1px solid #000;
    cursor: pointer;
  }
  .option.selected {
    color: var(--color);
    background-color: var(--bgcolor);
  }
  .option:first-of-type {
    border-top-left-radius: 0.5em;
    border-bottom-left-radius: 0.5em;
  }
  .option:last-of-type {
    border-top-right-radius: 0.5em;
    border-bottom-right-radius: 0.5em;
  }

</style>