// Store de ediciones — persistente en localStorage
// Guarda overrides por id de fila. No modifica AUDIT_DATA; se aplica al vuelo.

const STORAGE_KEY = "xul-audit-edits-v2";

function loadEdits() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    return raw ? JSON.parse(raw) : {};
  } catch { return {}; }
}

function saveEdits(edits) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(edits)); } catch {}
}

// Función para persistir cambios en el archivo físico data.js vía servidor local
async function syncToFile(fullData) {
  try {
    const res = await fetch('/api/save', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ fullData })
    });
    if (res.ok) {
      console.log("💾 Cambios sincronizados con data.js");
      return true;
    }
  } catch (err) {
    console.warn("⚠️ No se pudo sincronizar con el archivo (¿está el servidor save-server.js activo?)", err);
    return false;
  }
}

// Hook para consumir y actualizar ediciones
window.useEdits = function useEdits() {
  const [edits, setEditsState] = React.useState(loadEdits);

  const setEdit = React.useCallback(async (id, patch) => {
    setEditsState(prev => {
      const next = { ...prev, [id]: { ...(prev[id] || {}), ...patch } };
      // Limpiar keys vacíos
      const rowEdit = next[id];
      Object.keys(rowEdit).forEach(k => {
        if (rowEdit[k] === undefined) delete rowEdit[k];
      });
      if (Object.keys(rowEdit).length === 0) delete next[id];
      saveEdits(next);

      // Sincronizar con el archivo
      const effectiveData = window.applyEditsToAll(window.AUDIT_DATA, next);
      syncToFile(effectiveData).then(success => {
        if (success) {
          // Si se guardó en el archivo, podríamos limpiar el localStorage, 
          // pero mejor lo dejamos para evitar parpadeos hasta que se recargue.
        }
      });

      return next;
    });
  }, []);

  const resetEdit = React.useCallback((id) => {
    setEditsState(prev => {
      const next = { ...prev };
      delete next[id];
      saveEdits(next);
      const effectiveData = window.applyEditsToAll(window.AUDIT_DATA, next);
      syncToFile(effectiveData);
      return next;
    });
  }, []);

  const resetAll = React.useCallback(() => {
    setEditsState({});
    saveEdits({});
    syncToFile(window.AUDIT_DATA);
  }, []);

  return { edits, setEdit, resetEdit, resetAll };
};

// Aplica overrides a una fila y recomputa coste si hace falta
window.applyEdits = function applyEdits(row, edits) {
  const patch = edits[row.id];
  if (!patch) return row;
  const merged = { ...row, ...patch };
  // Recalcular costeLabel si el coste cambió
  if (patch.coste !== undefined) {
    merged.costeLabel = merged.coste === 0 ? "0 €" : `${merged.coste} €${merged.coste >= 5 ? "/mes" : ""}`;
  }
  return merged;
};

window.applyEditsToAll = function applyEditsToAll(data, edits) {
  return data.map(row => window.applyEdits(row, edits));
};

// Componente Editable text (single-line o multi-line)
window.EditableText = function EditableText({ value, onChange, multiline, placeholder, className, style }) {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(value);
  const ref = React.useRef(null);

  React.useEffect(() => { setDraft(value); }, [value]);
  React.useEffect(() => {
    if (editing && ref.current) {
      ref.current.focus();
      ref.current.select?.();
    }
  }, [editing]);

  const commit = () => {
    setEditing(false);
    if (draft !== value) onChange(draft);
  };

  const cancel = () => {
    setEditing(false);
    setDraft(value);
  };

  const handleKey = (e) => {
    if (e.key === "Escape") { e.preventDefault(); cancel(); }
    if (!multiline && e.key === "Enter") { e.preventDefault(); commit(); }
    if (multiline && (e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); commit(); }
  };

  if (!editing) {
    return (
      <span
        className={`editable ${className || ""}`}
        style={style}
        onClick={(e) => { e.stopPropagation(); setEditing(true); }}
        title="Clic para editar"
      >
        {value || <span style={{ color: "var(--fg-subtle)", fontStyle: "italic" }}>{placeholder || "—"}</span>}
      </span>
    );
  }

  const Tag = multiline ? "textarea" : "input";
  return (
    <Tag
      ref={ref}
      className={`editable-input ${className || ""}`}
      value={draft}
      onChange={(e) => setDraft(e.target.value)}
      onBlur={commit}
      onKeyDown={handleKey}
      onClick={(e) => e.stopPropagation()}
      style={style}
      rows={multiline ? 3 : undefined}
    />
  );
};

// Componente Editable select
window.EditableSelect = function EditableSelect({ value, options, onChange, renderValue, className }) {
  const [editing, setEditing] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (editing && ref.current) ref.current.focus();
  }, [editing]);

  if (!editing) {
    return (
      <span
        className={`editable ${className || ""}`}
        onClick={(e) => { e.stopPropagation(); setEditing(true); }}
        title="Clic para editar"
      >
        {renderValue ? renderValue(value) : value}
      </span>
    );
  }

  return (
    <select
      ref={ref}
      className="editable-input"
      value={value}
      onChange={(e) => { onChange(e.target.value); setEditing(false); }}
      onBlur={() => setEditing(false)}
      onClick={(e) => e.stopPropagation()}
      style={{ minWidth: 90 }}
    >
      {options.map(o => (
        <option key={o.value ?? o} value={o.value ?? o}>{o.label ?? o}</option>
      ))}
    </select>
  );
};

// Editable number
window.EditableNumber = function EditableNumber({ value, onChange, suffix, className }) {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(String(value));
  const ref = React.useRef(null);

  React.useEffect(() => { setDraft(String(value)); }, [value]);
  React.useEffect(() => {
    if (editing && ref.current) { ref.current.focus(); ref.current.select?.(); }
  }, [editing]);

  const commit = () => {
    setEditing(false);
    const n = parseFloat(draft);
    if (!isNaN(n) && n !== value) onChange(n);
    else setDraft(String(value));
  };

  if (!editing) {
    return (
      <span className={`editable ${className || ""}`} onClick={(e) => { e.stopPropagation(); setEditing(true); }} title="Clic para editar">
        {value}{suffix ? ` ${suffix}` : ""}
      </span>
    );
  }

  return (
    <input
      ref={ref}
      type="number"
      className="editable-input"
      value={draft}
      onChange={(e) => setDraft(e.target.value)}
      onBlur={commit}
      onKeyDown={(e) => {
        if (e.key === "Enter") { e.preventDefault(); commit(); }
        if (e.key === "Escape") { e.preventDefault(); setEditing(false); setDraft(String(value)); }
      }}
      onClick={(e) => e.stopPropagation()}
      style={{ width: 70 }}
    />
  );
};
