// Shared form controls — light "Soft Clinical" theme.
// Teal = brand/selection; coral = pain severity (Scale10 only).
const { useState: useStateF } = React;

const FC = {
  accent: "#ef7b60", accentDeep: "#b75746",
  accentSoft: "rgba(239,123,96,0.10)",
  text: "#4a2723", text2: "#6b4b45", muted: "#806660",
  panel: "#fff0ef", panelAlt: "#fde2d7",
  border: "rgba(74,39,35,0.09)", borderStrong: "rgba(74,39,35,0.16)",
  coral: "#ff6b4a",
};

function FieldLabel({ children, idx }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
      {idx != null && (
        <div style={{
          width: 24, height: 24, borderRadius: 7,
          background: FC.accentSoft, color: FC.accentDeep,
          display: "grid", placeItems: "center",
          fontSize: 10.5, fontWeight: 700, flexShrink: 0,
        }}>{String(idx).padStart(2, "0")}</div>
      )}
      <div style={{ fontSize: 14, color: FC.text, lineHeight: 1.4, fontWeight: 500 }}>{children}</div>
    </div>
  );
}

function RadioPill({ options, value, onChange, columns }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: columns ? `repeat(${columns}, 1fr)` : `repeat(auto-fit, minmax(120px, 1fr))`,
      gap: 7,
    }}>
      {options.map((o) => {
        const sel = value === o.id;
        return (
          <button key={o.id} onClick={() => onChange(o.id)} style={{
            padding: "11px 15px", borderRadius: 999,
            background: sel ? FC.accent : FC.panel,
            color: sel ? "#fff" : FC.text2,
            border: `1.5px solid ${sel ? "transparent" : FC.border}`,
            fontSize: 12.5, fontWeight: 600, cursor: "pointer",
            transition: "all 0.2s",
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

function YesNo({ value, onChange }) {
  return (
    <div style={{ display: "flex", gap: 7 }}>
      {[{ id: "sim", label: "Sim" }, { id: "nao", label: "Não" }].map((o) => {
        const sel = value === o.id;
        return (
          <button key={o.id} onClick={() => onChange(o.id)} style={{
            padding: "10px 26px", borderRadius: 999,
            background: sel ? (o.id === "sim" ? FC.accent : FC.panelAlt) : FC.panel,
            color: sel && o.id === "sim" ? "#fff" : FC.text2,
            border: `1.5px solid ${sel ? "transparent" : FC.border}`,
            fontSize: 13, fontWeight: 600, cursor: "pointer", transition: "all 0.2s",
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

// chip micro-interactions
if (typeof document !== "undefined" && !document.getElementById("fc-chip-style")) {
  const s = document.createElement("style");
  s.id = "fc-chip-style";
  s.textContent = `
    .fc-chip { transition: transform .16s cubic-bezier(.2,.8,.2,1); }
    .fc-chip:hover { transform: translateY(-1px); }
    .fc-chip:active { transform: scale(.94); }
    @keyframes fcPop { 0%{transform:scale(.85)} 55%{transform:scale(1.08)} 100%{transform:scale(1)} }
    .fc-chip-sel { animation: fcPop .3s cubic-bezier(.2,.8,.2,1); }
  `;
  document.head.appendChild(s);
}

function CheckGrid({ options, values, onToggle, columns = 3, searchable = false, onClear }) {
  const [query, setQuery] = useStateF("");
  const norm = (s) => (s || "").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  const items = options.map((o) => (typeof o === "string" ? { id: o, label: o } : o));
  const filtered = searchable && query ? items.filter((it) => norm(it.label).includes(norm(query))) : items;
  const selCount = values.length;

  return (
    <div>
      {searchable && (
        <div style={{ position: "relative", marginBottom: 12, maxWidth: 320 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={FC.muted} strokeWidth="2"
            style={{ position: "absolute", left: 13, top: "50%", transform: "translateY(-50%)" }}>
            <circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" />
          </svg>
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Buscar…"
            style={{
              width: "100%", padding: "10px 14px 10px 36px",
              background: FC.panel, border: `1.5px solid ${FC.border}`,
              borderRadius: 999, color: FC.text, fontSize: 13, outline: "none",
              fontFamily: "'Inter', sans-serif",
            }} />
          {query && (
            <button onClick={() => setQuery("")} style={{
              position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)",
              background: "none", border: "none", color: FC.muted, cursor: "pointer", fontSize: 16, lineHeight: 1,
            }}>×</button>
          )}
        </div>
      )}

      <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
        {filtered.map((it) => {
          const sel = values.includes(it.id);
          return (
            <button
              key={it.id}
              className={"fc-chip" + (sel ? " fc-chip-sel" : "")}
              onClick={() => onToggle(it.id)}
              style={{
                padding: "9px 14px 9px 10px", borderRadius: 999,
                background: sel ? FC.accent : FC.panel,
                border: `1.5px solid ${sel ? "transparent" : FC.border}`,
                color: sel ? "#fff" : FC.text2,
                fontSize: 12.5, fontWeight: sel ? 600 : 500, cursor: "pointer",
                display: "inline-flex", alignItems: "center", gap: 7, lineHeight: 1.2,
                boxShadow: sel ? "0 6px 16px -6px rgba(239,123,96,0.45)" : "none",
                fontFamily: "'Inter', sans-serif",
              }}>
              <span style={{
                width: 16, height: 16, borderRadius: 999, flexShrink: 0,
                display: "grid", placeItems: "center",
                border: sel ? "none" : `1.5px solid ${FC.borderStrong}`,
                background: sel ? "rgba(255,255,255,0.28)" : "transparent",
                color: sel ? "#fff" : FC.muted, fontSize: 13, fontWeight: 400,
              }}>
                {sel
                  ? <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.5"><polyline points="20 6 9 17 4 12" /></svg>
                  : "+"}
              </span>
              {it.label}
            </button>
          );
        })}
        {searchable && query && filtered.length === 0 && (
          <div style={{ fontSize: 12, color: FC.muted, fontStyle: "italic", padding: "6px 2px" }}>
            Nada encontrado pra “{query}”.
          </div>
        )}
      </div>

      {selCount > 0 && (
        <div style={{
          display: "flex", alignItems: "center", gap: 12, marginTop: 12,
          fontSize: 12, color: FC.muted, fontWeight: 600,
        }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: FC.accentDeep }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: FC.accent }} />
            {selCount} {selCount === 1 ? "marcado" : "marcados"}
          </span>
          {onClear && (
            <button onClick={onClear} style={{
              background: "none", border: "none", color: FC.muted, cursor: "pointer",
              fontSize: 12, textDecoration: "underline", fontFamily: "inherit",
            }}>limpar</button>
          )}
        </div>
      )}
    </div>
  );
}

function Scale10({ value, onChange, leftLabel, rightLabel }) {
  return (
    <div>
      <div style={{ display: "flex", gap: 4, marginBottom: 7 }}>
        {Array.from({ length: 10 }, (_, i) => {
          const n = i + 1;
          const sel = value === n;
          const intensity = i / 9;
          return (
            <button key={n} onClick={() => onChange(n)} style={{
              flex: 1, padding: "11px 0", borderRadius: 9,
              background: sel
                ? `linear-gradient(180deg, #ff8765, ${FC.coral})`
                : `rgba(255,107,74,${0.05 + intensity * 0.11})`,
              border: `1.5px solid ${sel ? "transparent" : FC.border}`,
              color: sel ? "#fff" : FC.text2,
              fontSize: 13, fontWeight: 700, cursor: "pointer",
              transition: "all 0.15s",
              boxShadow: sel ? `0 6px 16px -6px rgba(255,90,60,0.5)` : "none",
            }}>{n}</button>
          );
        })}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: FC.muted, fontWeight: 500 }}>
        <span>{leftLabel}</span>
        <span>{rightLabel}</span>
      </div>
    </div>
  );
}

function TextInputF({ value, onChange, placeholder, multiline, rows = 3, maxLength }) {
  const limit = maxLength || (multiline ? 2000 : 500);
  const base = {
    width: "100%", padding: multiline ? "13px 15px" : "12px 15px",
    background: FC.panel, border: `1.5px solid ${FC.border}`,
    borderRadius: 12, color: FC.text, fontSize: 14,
    fontFamily: "'Inter', sans-serif", outline: "none",
  };
  if (multiline) {
    return <textarea value={value || ""} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} rows={rows} maxLength={limit} style={{ ...base, resize: "vertical", lineHeight: 1.5 }} />;
  }
  return <input value={value || ""} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} maxLength={limit} style={base} />;
}

function Q({ idx, label, sub, children, mb = 22 }) {
  return (
    <div style={{ marginBottom: mb }}>
      <FieldLabel idx={idx}>{label}</FieldLabel>
      {sub && <div style={{ fontSize: 12.5, color: FC.muted, marginTop: -8, marginBottom: 12, marginLeft: idx != null ? 34 : 0 }}>{sub}</div>}
      <div style={{ marginLeft: idx != null ? 34 : 0 }}>{children}</div>
    </div>
  );
}

window.FormControls = { FieldLabel, RadioPill, YesNo, CheckGrid, Scale10, TextInputF, Q, FC };
