/* global React, Icon */
/* Sidebar — list of saved SOPs with inline rename */

const { useState: useStateSB, useRef: useRefSB, useEffect: useEffectSB } = React;

function SidebarItem({ doc, active, onSelect, onRename, onDelete }) {
  const [editing, setEditing] = useStateSB(false);
  const [draft, setDraft] = useStateSB(doc.title || "");
  const inputRef = useRefSB(null);

  useEffectSB(() => {
    if (editing && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [editing]);

  // Sync draft when doc title changes externally (e.g. AI regen)
  useEffectSB(() => { if (!editing) setDraft(doc.title || ""); }, [doc.title, editing]);

  const commit = () => {
    const v = draft.trim();
    if (v && v !== doc.title) onRename(doc.id, v);
    else setDraft(doc.title || "");
    setEditing(false);
  };
  const cancel = () => {
    setDraft(doc.title || "");
    setEditing(false);
  };

  const label = doc.title?.trim() || "Sin título";
  const date = doc.date || "—";

  return (
    <div
      className={`sidebar__item ${active ? "sidebar__item--active" : ""}`}
      role="button"
      tabIndex={0}
      onClick={() => !editing && onSelect(doc.id)}
      onDoubleClick={(e) => { e.stopPropagation(); setEditing(true); }}
      onKeyDown={(e) => {
        if (editing) return;
        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onSelect(doc.id); }
        if (e.key === "F2") { e.preventDefault(); setEditing(true); }
      }}
    >
      {editing ? (
        <input
          ref={inputRef}
          className="sidebar__item-input"
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onBlur={commit}
          onClick={(e) => e.stopPropagation()}
          onKeyDown={(e) => {
            e.stopPropagation();
            if (e.key === "Enter") commit();
            if (e.key === "Escape") cancel();
          }}
          placeholder="Título del SOP"
        />
      ) : (
        <span className="sidebar__item-name" title={label}>{label}</span>
      )}

      <span className="sidebar__item-meta">
        <span>v{doc.version || "1.0"}</span>
        <span>·</span>
        <span>{date}</span>
      </span>

      <div className="sidebar__item-actions">
        <button
          className="sidebar__item-action"
          onClick={(e) => { e.stopPropagation(); setEditing(true); }}
          title="Renombrar"
        >
          <Icon name="edit" size={12} />
        </button>
        <button
          className="sidebar__item-action sidebar__item-action--danger"
          onClick={(e) => { e.stopPropagation(); if (confirm(`¿Eliminar "${label}"?`)) onDelete(doc.id); }}
          title="Eliminar"
        >
          <Icon name="trash" size={12} />
        </button>
      </div>
    </div>
  );
}

function Sidebar({ docs, activeId, onSelect, onNew, onDelete, onRename }) {
  const sorted = [...docs].sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
  return (
    <aside className="app__sidebar">
      <div className="sidebar__header">
        <span className="sidebar__title">SOPs · {docs.length}</span>
        <button className="btn btn--sm btn--primary" onClick={onNew} title="Nuevo SOP">
          <Icon name="plus" size={12} /> Nuevo
        </button>
      </div>
      <div className="sidebar__list">
        {sorted.length === 0 && (
          <div className="sidebar__empty">
            Aún no hay SOPs guardados. Pulsa <strong>Nuevo</strong> para empezar.
          </div>
        )}
        {sorted.map(d => (
          <SidebarItem
            key={d.id}
            doc={d}
            active={d.id === activeId}
            onSelect={onSelect}
            onRename={onRename}
            onDelete={onDelete}
          />
        ))}
      </div>
      {sorted.length > 0 && (
        <div className="sidebar__footnote">
          Doble-click o ✏️ para renombrar
        </div>
      )}
    </aside>
  );
}

window.Sidebar = Sidebar;
