(function () {
  "use strict";

  const tr = (window.SVX && window.SVX.tr) || function (ca) { return ca; };

  /**
   * Reusable component for fields that need CA/ES (mandatory) and optional EN.
   *
   * Props:
   * - label: field label shown above
   * - valueCa, valueEs, valueEn: current values
   * - onChangeCa(value), onChangeEs(value), onChangeEn(value): change handlers
   * - enEnabled: boolean - if true, shows EN input with magic wand
   * - multiline: boolean - if true uses textarea, otherwise input
   * - rows: number - rows for textarea (default 3)
   * - placeholder: optional placeholder text
   * - help: optional help text shown below label
   */
  function TranslatableField(props) {
    const [translating, setTranslating] = React.useState(false);
    const label = props.label || "";
    const enEnabled = !!props.enEnabled;
    const multiline = !!props.multiline;
    const rows = props.rows || 3;

    async function handleTranslate() {
      // Use CA as source if available, else ES
      const source = (props.valueCa && props.valueCa.trim())
        ? { text: props.valueCa, lang: "ca" }
        : (props.valueEs && props.valueEs.trim())
          ? { text: props.valueEs, lang: "es" }
          : null;
      if (!source) {
        window.SVX.toast(tr("Omple primer el camp en catala o castella", "Rellena primero el campo en catalan o castellano"), "warn");
        return;
      }
      setTranslating(true);
      try {
        const translated = await window.SVX.translateWithToast(source.text, source.lang, "en");
        if (translated && props.onChangeEn) {
          props.onChangeEn(translated);
        }
      } finally {
        setTranslating(false);
      }
    }

    const inputStyle = {
      width: "100%",
      padding: "10px 12px",
      borderRadius: 6,
      border: "1px solid var(--line)",
      fontFamily: "inherit",
      fontSize: 14,
      color: "var(--ink)",
      background: "var(--paper)",
    };
    const textareaStyle = Object.assign({}, inputStyle, { resize: "vertical", minHeight: rows * 22 + 20 });

    function fieldFor(value, onChange, langKey, langLabel) {
      const isEn = langKey === "en";
      return (
        <div style={{flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 4}}>
          <div style={{display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8}}>
            <span style={{fontSize: 11, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-3)"}}>{langLabel}</span>
            {isEn && (
              <button type="button" onClick={handleTranslate} disabled={translating}
                style={{
                  display: "inline-flex", alignItems: "center", gap: 4,
                  padding: "4px 8px", fontSize: 11, fontWeight: 500,
                  borderRadius: 6, border: "1px solid var(--accent)",
                  background: translating ? "var(--paper-2)" : "var(--accent-soft, #faf5e8)",
                  color: "var(--accent, var(--vinya-700))",
                  cursor: translating ? "wait" : "pointer",
                  opacity: translating ? 0.6 : 1,
                  transition: "all 150ms ease"
                }}
                title={tr("Traduir automaticament des del catala/castella", "Traducir automaticamente desde catalan/castellano")}>
                <i className="ph ph-magic-wand" style={{fontSize: 12}}></i>
                {translating ? tr("Traduint...", "Traduciendo...") : tr("Traduir", "Traducir")}
              </button>
            )}
          </div>
          {multiline
            ? <textarea rows={rows} style={textareaStyle} value={value || ""} placeholder={props.placeholder || ""} onChange={function(e) { onChange(e.target.value); }} />
            : <input style={inputStyle} value={value || ""} placeholder={props.placeholder || ""} onChange={function(e) { onChange(e.target.value); }} />
          }
        </div>
      );
    }

    return (
      <div style={{display: "flex", flexDirection: "column", gap: 6}}>
        {label && (
          <div>
            <span className="eyebrow" style={{display: "block"}}>{label}</span>
            {props.help && <p style={{margin: "2px 0 0", fontSize: 12, color: "var(--ink-3)", lineHeight: 1.4, fontStyle: "italic"}}>{props.help}</p>}
          </div>
        )}
        <div style={{display: "flex", gap: 12, flexWrap: "wrap"}}>
          {fieldFor(props.valueCa, props.onChangeCa, "ca", "Catala")}
          {fieldFor(props.valueEs, props.onChangeEs, "es", "Castellano")}
        </div>
        {enEnabled && (
          <div style={{display: "flex", gap: 12, marginTop: 4}}>
            {fieldFor(props.valueEn, props.onChangeEn, "en", "English")}
          </div>
        )}
      </div>
    );
  }

  window.TranslatableField = TranslatableField;
})();
