// Reusable input controls — UnitField, Combo, Chip, Tri, Switch, Seg, etc.
const { useState, useEffect, useRef, useMemo } = React;

// Tiny inline icon helpers
const Icon = {
  caret: () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
  ),
  search: () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
  ),
  x: () => (
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
  ),
  spark: () => (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v3"/><path d="M12 18v3"/><path d="M3 12h3"/><path d="M18 12h3"/><path d="m5.6 5.6 2.1 2.1"/><path d="m16.3 16.3 2.1 2.1"/><path d="m5.6 18.4 2.1-2.1"/><path d="m16.3 7.7 2.1-2.1"/></svg>
  ),
};

function UnitField({ value, onChange, unit, onUnitChange, units, placeholder, ariaLabel, inputMode = "decimal" }) {
  return (
    <div className="unit-field" aria-label={ariaLabel}>
      <input
        type="text"
        inputMode={inputMode}
        value={value}
        onChange={e => {
          // Only allow digits + one decimal
          const v = e.target.value.replace(/[^\d.]/g, "").replace(/(\..*?)\..*/g, "$1");
          onChange(v);
        }}
        placeholder={placeholder}
        aria-label={ariaLabel}
      />
      <div className="unit-toggle" role="group" aria-label={`${ariaLabel} unit`}>
        {units.map(u => (
          <button
            key={u}
            type="button"
            aria-pressed={unit === u}
            onClick={() => onUnitChange(u)}
          >{u}</button>
        ))}
      </div>
    </div>
  );
}

function Seg({ options, value, onChange, ariaLabel }) {
  return (
    <div className="seg" role="group" aria-label={ariaLabel}>
      {options.map(o => (
        <button
          key={o.value}
          type="button"
          aria-pressed={value === o.value}
          onClick={() => onChange(o.value)}
        >{o.label}</button>
      ))}
    </div>
  );
}

function Combo({ options, value, onSelect, onClear, placeholder, renderOption }) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [highlight, setHighlight] = useState(0);
  const wrapRef = useRef(null);
  const inputRef = useRef(null);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return options;
    return options.filter(o =>
      o.label.toLowerCase().includes(q) ||
      (o.hint || "").toLowerCase().includes(q)
    );
  }, [options, query]);

  useEffect(() => {
    function onDoc(e) {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);

  function commit(opt) {
    onSelect(opt);
    setQuery("");
    setOpen(false);
  }

  function onKey(e) {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setOpen(true);
      setHighlight(h => Math.min(filtered.length - 1, h + 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setHighlight(h => Math.max(0, h - 1));
    } else if (e.key === "Enter") {
      if (open && filtered[highlight]) {
        e.preventDefault();
        commit(filtered[highlight]);
      }
    } else if (e.key === "Escape") {
      setOpen(false);
    }
  }

  if (value) {
    return (
      <div className="combo" ref={wrapRef}>
        <button
          type="button"
          className={`dx-pill ${open ? "open" : ""}`}
          onClick={() => {
            setOpen(o => !o);
            setQuery("");
            // Pre-highlight the current selection so the user can see "where they are".
            const idx = options.findIndex(o => o.id === value.id);
            setHighlight(idx >= 0 ? idx : 0);
          }}
          aria-haspopup="listbox"
          aria-expanded={open}
          title="Click to change diagnosis"
        >
          <span className="dx-pill-text">
            {value.label}{value.id === "other" && value.text ? ` — ${value.text}` : ""}
          </span>
          <span className="dx-pill-caret"><Icon.caret /></span>
          <span
            className="x"
            role="button"
            tabIndex={0}
            aria-label="Clear diagnosis"
            onClick={e => { e.stopPropagation(); setOpen(false); onClear(); }}
            onKeyDown={e => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                e.stopPropagation();
                setOpen(false);
                onClear();
              }
            }}
          >
            <Icon.x />
          </span>
        </button>
        {open && (
          <div className="combo-menu" role="listbox">
            {options.map((o, i) => (
              <div
                key={o.id}
                className={`combo-option ${o.id === value.id ? "is-current" : ""}`}
                aria-selected={i === highlight}
                onMouseEnter={() => setHighlight(i)}
                onMouseDown={e => { e.preventDefault(); commit(o); }}
                role="option"
              >
                <span>{o.label}{o.id === value.id ? " · current" : ""}</span>
                <span className="tier">{(renderOption && renderOption(o)) || o.hint}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="combo" ref={wrapRef}>
      <div className={`combo-input ${open ? "open" : ""}`} onClick={() => { setOpen(true); inputRef.current?.focus(); }}>
        <Icon.search />
        <input
          ref={inputRef}
          value={query}
          placeholder={placeholder}
          onChange={e => { setQuery(e.target.value); setOpen(true); setHighlight(0); }}
          onFocus={() => setOpen(true)}
          onKeyDown={onKey}
          aria-expanded={open}
        />
        <span className="caret"><Icon.caret /></span>
      </div>
      {open && (
        <div className="combo-menu" role="listbox">
          {filtered.length === 0 ? (
            <div className="combo-empty">No matches.</div>
          ) : filtered.map((o, i) => (
            <div
              key={o.id}
              className="combo-option"
              aria-selected={i === highlight}
              onMouseEnter={() => setHighlight(i)}
              onMouseDown={e => { e.preventDefault(); commit(o); }}
              role="option"
            >
              <span>{o.label}</span>
              <span className="tier">{(renderOption && renderOption(o)) || o.hint}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function Chip({ active, onToggle, children }) {
  return (
    <button type="button" className="chip" aria-pressed={active} onClick={onToggle}>
      {children}
    </button>
  );
}

function Tri({ options, value, onChange }) {
  return (
    <div className="tri" role="radiogroup">
      {options.map(o => (
        <button
          key={o.id}
          type="button"
          className={o.cls}
          aria-pressed={value === o.id}
          onClick={() => onChange(value === o.id ? "" : o.id)}
        >{o.label}</button>
      ))}
    </div>
  );
}

function Switch({ checked, onChange, ariaLabel }) {
  return (
    <button
      type="button"
      className="switch"
      aria-pressed={checked}
      aria-label={ariaLabel}
      onClick={() => onChange(!checked)}
    />
  );
}

function TierChip({ tier }) {
  const label = window.RD.TIER_LABEL[tier];
  const hint = window.RD.TIER_HINT[tier];
  return (
    <button
      type="button"
      className={`tier-chip ${tier}`}
      title={hint + " · click for details"}
      onClick={() => window.dispatchEvent(new CustomEvent("rd:open-about", { detail: { section: "tiers" } }))}
      style={{ font: "inherit", cursor: "pointer" }}
    >
      {label}
    </button>
  );
}

Object.assign(window, { Icon, UnitField, Seg, Combo, Chip, Tri, Switch, TierChip });
