/* The Pulse — Editions manager: save, switch, duplicate, rename & delete
   monthly issues. Lives as a pinned bar at the top of the editor column. */
(function () {
  const I = window.PulseIcons;
  const { useState, useRef, useEffect } = React;

  function timeAgo(ts) {
    if (!ts) return "";
    const d = new Date(ts);
    const today = new Date();
    const sameDay = d.toDateString() === today.toDateString();
    const time = d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
    if (sameDay) return "Saved " + time;
    return "Saved " + d.toLocaleDateString([], { month: "short", day: "numeric" }) + " · " + time;
  }

  function EditionsBar(props) {
    const { editions, currentId, onSwitch, onRename, onNew, onBlank, onDuplicate, onDelete } = props;
    const [open, setOpen] = useState(false);
    const wrapRef = useRef(null);
    const cur = editions.find((e) => e.id === currentId) || editions[0];

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

    return (
      <div className="ed-editions" ref={wrapRef}>
        <div className="edn-bar">
          <span className="edn-ico"><I.Layers size={16} /></span>
          <input
            className="edn-name"
            value={cur.label}
            onChange={(e) => onRename(cur.id, e.target.value)}
            placeholder="Untitled issue"
            spellCheck={false}
          />
          <button className={"edn-toggle" + (open ? " on" : "")} onClick={() => setOpen(!open)}
                  title="Switch editions">
            <span className="edn-count">{editions.length}</span>
            <I.ChevDown size={15} />
          </button>
        </div>

        {open && (
          <div className="edn-pop">
            <div className="edn-pop-h">Saved editions</div>
            <div className="edn-list">
              {editions.map((e) => (
                <div key={e.id} className={"edn-item" + (e.id === currentId ? " on" : "")}>
                  <button className="edn-item-main" onClick={() => { onSwitch(e.id); setOpen(false); }}>
                    <span className="edn-check">{e.id === currentId ? <I.Check size={14} /> : null}</span>
                    <span className="edn-item-txt">
                      <b>{e.label || "Untitled issue"}</b>
                      <em>{timeAgo(e.updatedAt)}</em>
                    </span>
                  </button>
                  <button className="edn-mini" title="Duplicate" onClick={() => onDuplicate(e.id)}>
                    <I.Copy size={14} />
                  </button>
                  <button className="edn-mini danger" title="Delete"
                          disabled={editions.length <= 1}
                          onClick={() => onDelete(e.id)}>
                    <I.Trash size={14} />
                  </button>
                </div>
              ))}
            </div>
            <div className="edn-pop-foot">
              <button className="edn-new" onClick={() => { onNew(); setOpen(false); }}>
                <I.Plus size={15} /> New edition <span>copies this one</span>
              </button>
              <button className="edn-blank" onClick={() => { onBlank(); setOpen(false); }}>
                Start from blank template
              </button>
            </div>
          </div>
        )}
      </div>
    );
  }

  window.PulseEditions = EditionsBar;
})();
