import { EXAMPLES } from "../examples.ts";

interface Props {
  script: string;
  onChange: (s: string) => void;
  onRun: () => void;
  running: boolean;
}

export function ScriptPanel({ script, onChange, onRun, running }: Props) {
  return (
    <div className="script-panel">
      <div className="script-toolbar">
        <label className="field">
          <span>Example</span>
          <select
            value=""
            onChange={(e) => {
              const ex = EXAMPLES.find((x) => x.name === e.target.value);
              if (ex) onChange(ex.code);
              e.target.value = "";
            }}
          >
            <option value="" disabled>
              Load an example…
            </option>
            {EXAMPLES.map((ex) => (
              <option key={ex.name} value={ex.name}>
                {ex.name}
              </option>
            ))}
          </select>
        </label>

        <button className="run-btn" onClick={onRun} disabled={running}>
          {running ? "Running…" : "Run ▶"}
        </button>
      </div>

      <textarea
        className="editor"
        spellCheck={false}
        value={script}
        onChange={(e) => onChange(e.target.value)}
        onKeyDown={(e) => {
          if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
            e.preventDefault();
            onRun();
          }
        }}
      />
      <div className="editor-hint">
        Define <code>out = filterImage(img)</code>. <code>img</code> is an{" "}
        <code>H × W × 3</code> array of doubles in <code>[0, 255]</code> (RGB).
        Press <kbd>⌘/Ctrl</kbd>+<kbd>Enter</kbd> to run.
      </div>
    </div>
  );
}
