import React from 'react'

import { Icon } from './icon.js'

/**
 * Styled native select with Lucide chevron.
 */
export interface SelectOption {
  value: string;
  label: string;
}
export interface SelectProps {
  label?: string;
  options: SelectOption[];
  value?: string;
  defaultValue?: string;
  onChange?: (e: React.ChangeEvent<HTMLSelectElement>) => void;
  disabled?: boolean;
  style?: React.CSSProperties;
}

const CSS = `
.ct-select-field { display: flex; flex-direction: column; gap: 6px; }
.ct-select-field__label { font: 600 13px/1.2 var(--font-sans); color: var(--ink-1); }
.ct-select__wrap { position: relative; display: flex; align-items: center; }
.ct-select {
  width: 100%; height: 34px;
  font: var(--text-body);
  color: var(--ink-1);
  background: var(--surface-card);
  border: 1px solid var(--line-2);
  border-radius: var(--radius-2);
  padding: 0 30px 0 12px;
  appearance: none;
  cursor: pointer;
  transition: border-color var(--duration-fast) var(--ease-out);
}
.ct-select:hover:not(:disabled):not(:focus) { border-color: var(--border-strong); }
.ct-select:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
.ct-select:disabled { opacity: 0.5; cursor: not-allowed; }
.ct-select__chevron { position: absolute; right: 10px; color: var(--ink-3); pointer-events: none; display: flex; }
`;
(function inject() {
  if (typeof document !== 'undefined' && !document.getElementById('ct-select-css')) {
    const s = document.createElement('style'); s.id = 'ct-select-css'; s.textContent = CSS;
    document.head.appendChild(s);
  }
})();

export function Select({ label, options, style, ...rest }: SelectProps) {
  return (
    <div className="ct-select-field" style={style}>
      {label ? <label className="ct-select-field__label">{label}</label> : null}
      <div className="ct-select__wrap">
        <select className="ct-select" {...rest}>
          {options.map((o) => (
            <option key={o.value} value={o.value}>{o.label}</option>
          ))}
        </select>
        <span className="ct-select__chevron"><Icon name="chevron-down" size={15} /></span>
      </div>
    </div>
  );
}
