/* ComposerModal — the post form as a pop-up dialog (Addendum A §B).
   Opened from the calendar, the posts list, analytics reuse, or “+ New”.
   Hosts the full Composer (form + live preview + rules + workflow). */
(function () {
  const D = window.CROPR_DATA;
  const isLocked = (p) => ["published", "amplify", "tracked"].includes(p.status) || p.scheduleState === "published";
  function ComposerModal({ postId, onClose, onToast, onReuse }) {
    // Escape always closes — so a user is never trapped in the dialog.
    React.useEffect(() => {
      const onKey = (e) => { if (e.key === "Escape") onClose(); };
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, [onClose]);
    const post = postId ? window.CroprStore.get(postId) : null;
    if (!post) return null;
    const locked = isLocked(post);
    return (
      // overflowX hidden + a viewport-capped width keep the close button on-screen
      // on narrow windows (the modal used to overflow, stranding the user).
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(20,20,30,0.5)", backdropFilter: "blur(3px)", display: "grid", placeItems: "start center", zIndex: 70, padding: "3vh 18px", overflowY: "auto", overflowX: "hidden" }}>
        <div onClick={(e) => e.stopPropagation()} style={{ width: "min(1180px, 100%)", background: "var(--bg-subtle)", borderRadius: 20, boxShadow: "var(--shadow-xl)", border: "1px solid var(--border)", overflow: "hidden" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 22px", background: "var(--surface)", borderBottom: "1px solid var(--border)", position: "sticky", top: 0, zIndex: 5 }}>
            <Icon name={locked ? "lock" : "pen-line"} size={19} color="var(--accent)" />
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ fontSize: 16, fontWeight: 700, letterSpacing: "-.01em", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{post.title || "Untitled post"}</div>
            </div>
            {locked && <Badge color="var(--fg3)" dot>Read-only</Badge>}
            <StatusBadge status={post.status} />
            {/* "Reuse to edit" lives in the read-only banner inside the body
                (Composer.jsx); no duplicate in the header. */}
            <button onClick={onClose} title="Close (Esc)" style={{ flex: "none", border: 0, background: "var(--bg-muted)", borderRadius: 10, width: 36, height: 36, cursor: "pointer", display: "grid", placeItems: "center" }}><Icon name="x" size={18} /></button>
          </div>
          <div style={{ padding: 22 }}>
            <Composer post={post} onToast={onToast} onNav={() => {}} locked={locked} onReuse={onReuse} />
          </div>
        </div>
      </div>
    );
  }
  window.ComposerModal = ComposerModal;
})();
