// Sidebar — details for selected node

const { useState: useStateS, useEffect: useEffectS, useMemo: useMemoS } = React;

// Two-step delete control for nodes (page/section/content/fold)
function DeleteNodeButton({ summary, onConfirm }) {
  const [armed, setArmed] = useStateS(false);
  useEffectS(() => { setArmed(false); }, [summary]); // reset when selection changes
  if (armed) {
    return (
      <span className="del-node-confirm" title={summary || ""}>
        <button className="del-confirm-yes" onClick={() => { onConfirm(); setArmed(false); }}>
          Confirm delete
        </button>
        <button className="del-confirm-no" onClick={() => setArmed(false)}>Cancel</button>
      </span>
    );
  }
  return (
    <button
      className="iconbtn tiny del-node-btn"
      onClick={() => setArmed(true)}
      title={summary || "Delete this item"}
    >
      <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
        <path d="M3 4 L3 10 Q3 10.5 3.5 10.5 L8.5 10.5 Q9 10.5 9 10 L9 4" stroke="currentColor" strokeWidth="1.2" fill="none" strokeLinecap="round" />
        <path d="M2 3.5 L10 3.5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
        <path d="M4.5 3 L4.5 2.2 Q4.5 1.7 5 1.7 L7 1.7 Q7.5 1.7 7.5 2.2 L7.5 3" stroke="currentColor" strokeWidth="1.2" fill="none" strokeLinecap="round" />
      </svg>
      Delete
    </button>
  );
}

function Sidebar({
  selectedId, nodes, children, commentsByNode,
  onAddComment, onDeleteComment, onClearSelection, onNavigate, onLocate, getBreadcrumb,
  collapsed, onToggleCollapsed,
  suggestionsByContent, functionalityByContent, votes, pageNodes,
  onSubmitSuggestion, onUpvoteSuggestion, onDeleteSuggestion, onAddSuggestionComment, onDeleteSuggestionComment,
  onAddFunctionality, onDeleteFunctionality, onAddFunctionalityComment, onDeleteFunctionalityComment,
  onDeleteNode,
}) {
  const node = selectedId ? nodes[selectedId] : null;
  const [draft, setDraft] = useStateS("");

  // Reset draft when switching nodes
  useEffectS(() => { setDraft(""); }, [selectedId]);

  // Compute aggregates (works even with no selection — guarded below)
  const pageId = node ? (node.type === "page" ? node.id : node.pageId) : null;
  const pageNode = pageId ? nodes[pageId] : null;
  const sectionCount = pageId ? (children[pageId] || []).length : 0;
  const contentCount = pageId
    ? (children[pageId] || []).reduce((s, sid) => s + (children[sid]?.length || 0), 0)
    : 0;
  const comments = node ? (commentsByNode[node.id] || []) : [];
  const breadcrumb = node ? getBreadcrumb(node.id) : [];
  const typeTone = node ? (node.type === "page" ? "page" : node.type === "section" ? "section" : "content") : null;
  const isFold = node && node.subtype === "fold";

  // Cascading delete summary
  const deleteSummary = useMemoS(() => {
    if (!node || !onDeleteNode) return null;
    if (node.type === "page") {
      const secCount = (children[node.id] || []).length;
      const conCount = (children[node.id] || []).reduce((s, sid) => s + (children[sid]?.length || 0), 0);
      const foldCount = (children[`foldlist:${node.id}`] || []).length;
      const bits = [];
      if (secCount) bits.push(`${secCount} section${secCount !== 1 ? "s" : ""}`);
      if (conCount) bits.push(`${conCount} content item${conCount !== 1 ? "s" : ""}`);
      if (foldCount) bits.push(`${foldCount} fold item${foldCount !== 1 ? "s" : ""}`);
      return bits.length ? `Deletes this page and ${bits.join(" + ")}.` : "Deletes this page.";
    }
    if (node.type === "section") {
      const conCount = (children[node.id] || []).length;
      return conCount ? `Deletes this section and ${conCount} content item${conCount !== 1 ? "s" : ""}.` : "Deletes this section.";
    }
    if (isFold) return "Deletes this above-the-fold item.";
    return "Deletes this content item.";
  }, [node, children, isFold, onDeleteNode]);

  // -------- Collapsed rail --------
  if (collapsed) {
    return (
      <aside className="sidebar sidebar-rail" aria-label="Inspector (collapsed)">
        <button
          className="rail-toggle"
          onClick={onToggleCollapsed}
          title="Expand inspector"
          aria-label="Expand inspector"
        >
          <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true">
            <path d="M9 2.5 L4 7 L9 11.5" stroke="currentColor" strokeWidth="1.7" fill="none" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>

        {!node && (
          <div className="rail-empty" title="Nothing selected">
            <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true">
              <circle cx="9" cy="9" r="6.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeDasharray="2 2.5" />
              <circle cx="9" cy="9" r="1.5" fill="currentColor" />
            </svg>
            <span className="rail-empty-label">Select<br/>anything</span>
          </div>
        )}

        {node && (
          <div className="rail-stack">
            {/* Type marker */}
            <div className={`rail-type-mark ${typeTone}`} title={`${node.type.charAt(0).toUpperCase() + node.type.slice(1)} · click to expand`}>
              {node.type === "page" && <window.Glyph type="page" />}
              {node.type === "section" && <window.Glyph type="section" />}
              {node.type === "content" && <window.Glyph type="content" />}
            </div>

            {/* Title initial (vertical) */}
            <div className="rail-title" title={node.title} onClick={onToggleCollapsed}>
              {node.title}
            </div>

            {/* Status pip */}
            {(node.status || pageNode?.status) && (
              <div className={`rail-pip status-${node.status || pageNode.status}`} title={`Status · ${window.statusLabel(node.status || pageNode.status)}`}>
                <span className="rail-pip-dot"></span>
                <span className="rail-pip-label">{(node.status || pageNode.status) === "mvp" ? "P1" : (node.status || pageNode.status) === "phase2" ? "P2" : "—"}</span>
              </div>
            )}

            {/* Comments */}
            <div
              className={`rail-pip ${comments.length > 0 ? "rail-pip-accent" : ""}`}
              title={`${comments.length} comment${comments.length !== 1 ? "s" : ""}`}
              onClick={onToggleCollapsed}
            >
              <window.CommentGlyph />
              <span className="rail-pip-num">{comments.length}</span>
            </div>

            {/* AEO targets */}
            {node.aeo && node.aeo.length > 0 && (
              <div className="rail-pip" title={`${node.aeo.length} AEO question${node.aeo.length !== 1 ? "s" : ""}`}>
                <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
                  <circle cx="6" cy="6" r="5" fill="none" stroke="currentColor" strokeWidth="1.2" />
                  <path d="M5 5 Q5 3.5 6 3.5 Q7 3.5 7 4.5 Q7 5.3 6 5.8 L6 6.5" stroke="currentColor" strokeWidth="1.1" fill="none" strokeLinecap="round" />
                  <circle cx="6" cy="8.3" r="0.6" fill="currentColor" />
                </svg>
                <span className="rail-pip-num">{node.aeo.length}</span>
              </div>
            )}

            {/* Above-fold count */}
            {node.aboveFold && node.aboveFold.length > 0 && (
              <div className="rail-pip" title={`${node.aboveFold.length} above-the-fold items`}>
                <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
                  <rect x="1.5" y="2" width="9" height="3.5" rx="0.5" fill="currentColor" opacity="0.7" />
                  <line x1="1" y1="7" x2="11" y2="7" stroke="currentColor" strokeWidth="1" strokeDasharray="1 1.2" />
                  <rect x="1.5" y="8" width="9" height="2" rx="0.5" fill="currentColor" opacity="0.25" />
                </svg>
                <span className="rail-pip-num">{node.aboveFold.length}</span>
              </div>
            )}

            {/* Children */}
            {node.type !== "content" && (children[node.id] || []).length > 0 && (
              <div className="rail-pip" title={`${(children[node.id] || []).length} ${node.type === "page" ? "sections" : "content items"}`}>
                <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
                  <rect x="1.5" y="2" width="9" height="1.6" rx="0.4" fill="currentColor" />
                  <rect x="1.5" y="5.2" width="9" height="1.6" rx="0.4" fill="currentColor" opacity="0.7" />
                  <rect x="1.5" y="8.4" width="6" height="1.6" rx="0.4" fill="currentColor" opacity="0.45" />
                </svg>
                <span className="rail-pip-num">{(children[node.id] || []).length}</span>
              </div>
            )}

            {/* Content-only: suggestion versions */}
            {node.type === "content" && (suggestionsByContent[node.id] || []).length > 0 && (
              <div className="rail-pip" title={`${(suggestionsByContent[node.id] || []).length} content draft${(suggestionsByContent[node.id] || []).length !== 1 ? "s" : ""}`}>
                <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
                  <rect x="2.5" y="1.5" width="6" height="8" rx="0.6" fill="none" stroke="currentColor" strokeWidth="1.1" />
                  <rect x="3.5" y="3.5" width="6" height="8" rx="0.6" fill="currentColor" opacity="0.18" stroke="currentColor" strokeWidth="1.1" />
                </svg>
                <span className="rail-pip-num">{(suggestionsByContent[node.id] || []).length}</span>
              </div>
            )}

            {/* Content-only: functionality notes */}
            {node.type === "content" && (functionalityByContent[node.id] || []).length > 0 && (
              <div className="rail-pip" title={`${(functionalityByContent[node.id] || []).length} functionality note${(functionalityByContent[node.id] || []).length !== 1 ? "s" : ""}`}>
                <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
                  <circle cx="6" cy="6" r="4.5" fill="none" stroke="currentColor" strokeWidth="1.2" />
                  <path d="M5.5 4.5 L7.5 6 L5.5 7.5 Z" fill="currentColor" />
                </svg>
                <span className="rail-pip-num">{(functionalityByContent[node.id] || []).length}</span>
              </div>
            )}

            <button className="rail-clear" onClick={onClearSelection} title="Clear selection">
              <svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true">
                <path d="M2 2 L8 8 M8 2 L2 8" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
              </svg>
            </button>
            <button
              className="rail-locate"
              onClick={() => onLocate(node.id)}
              title="Show in sitemap — expands and scrolls to this item"
            >
              <svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true">
                <circle cx="6" cy="6" r="3" fill="none" stroke="currentColor" strokeWidth="1.3" />
                <circle cx="6" cy="6" r="1" fill="currentColor" />
                <path d="M6 1 L6 2.5 M6 9.5 L6 11 M1 6 L2.5 6 M9.5 6 L11 6" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" />
              </svg>
            </button>
          </div>
        )}
      </aside>
    );
  }

  // -------- Expanded panel --------
  if (!node) {
    return (
      <aside className="sidebar">
        <div className="sidebar-header-row">
          <span className="sidebar-eyebrow">Inspector</span>
          <button
            className="iconbtn tiny"
            onClick={onToggleCollapsed}
            title="Collapse inspector"
            aria-label="Collapse inspector"
          >
            <svg width="12" height="12" viewBox="0 0 14 14" aria-hidden="true">
              <path d="M5 2.5 L10 7 L5 11.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
        </div>
        <div className="sidebar-empty">
          <span className="glyph">⌘</span>
          <div style={{ fontFamily: "var(--font-serif)", fontSize: 20, color: "var(--ink-2)", marginBottom: 6 }}>
            Select anything
          </div>
          <div style={{ fontSize: 13, lineHeight: 1.5 }}>
            Click a page, section, or content item to inspect its purpose, owner, AEO targets, comments and links.
          </div>
        </div>
      </aside>
    );
  }

  return (
    <aside className="sidebar">
      <div className="sb-kicker">
        <span className={`type-pill ${typeTone}`}>{isFold ? "fold item" : node.type}</span>
        <span style={{ flex: 1 }}></span>
        <button
          className="iconbtn tiny locate-btn"
          onClick={() => onLocate(node.id)}
          title="Show in sitemap — expands and scrolls to this item"
        >
          <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
            <circle cx="6" cy="6" r="3" fill="none" stroke="currentColor" strokeWidth="1.3" />
            <circle cx="6" cy="6" r="1" fill="currentColor" />
            <path d="M6 1 L6 2.5 M6 9.5 L6 11 M1 6 L2.5 6 M9.5 6 L11 6" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" />
          </svg>
          Locate
        </button>
        <DeleteNodeButton summary={deleteSummary} onConfirm={() => onDeleteNode(node.id)} />
        <button className="iconbtn tiny" onClick={onClearSelection}>Clear</button>
        <button
          className="iconbtn tiny"
          onClick={onToggleCollapsed}
          title="Collapse inspector"
          aria-label="Collapse inspector"
        >
          <svg width="12" height="12" viewBox="0 0 14 14" aria-hidden="true">
            <path d="M5 2.5 L10 7 L5 11.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
      </div>

      <h2 className="sb-title">{node.title}</h2>

      <div className="sb-breadcrumb">
        {breadcrumb.map((b, i) => (
          <span key={b.id}>
            {i > 0 && " / "}
            {i === breadcrumb.length - 1 ? <b>{b.title}</b> : <span style={{ cursor: "pointer", textDecoration: "underline dotted", textUnderlineOffset: 2 }} onClick={() => onNavigate(b.id)}>{b.title}</span>}
          </span>
        ))}
      </div>

      {/* Metadata */}
      <div className="sb-section">
        <div className="sb-section-label">Metadata</div>
        <dl className="sb-meta-grid">
          {node.type === "page" && (
            <>
              <dt>URL</dt><dd style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{node.url}</dd>
              <dt>Status</dt><dd>{window.statusLabel(node.status)}</dd>
              <dt>Owner</dt><dd>{node.owner || "—"}</dd>
              <dt>Children</dt><dd>{sectionCount} sections · {contentCount} content items</dd>
            </>
          )}
          {node.type === "section" && (
            <>
              <dt>Parent</dt><dd style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{pageNode.url}</dd>
              <dt>Status</dt><dd>{window.statusLabel(node.status)}</dd>
              <dt>Owner</dt><dd>{pageNode.owner || "—"}</dd>
              <dt>Children</dt><dd>{(children[node.id] || []).length} content items</dd>
            </>
          )}
          {node.type === "content" && isFold && (
            <>
              <dt>Parent page</dt><dd style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{pageNode.url}</dd>
              <dt>Location</dt><dd>Above the fold · item {node.foldIndex + 1} of {(pageNode.aboveFold || []).length}</dd>
              <dt>Owner</dt><dd>{pageNode.owner || "—"}</dd>
              <dt>Status</dt><dd>{window.statusLabel(pageNode.status)}</dd>
            </>
          )}
          {node.type === "content" && !isFold && (
            <>
              <dt>Parent page</dt><dd style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{pageNode.url}</dd>
              <dt>Section</dt><dd>{nodes[node.sectionId].title}</dd>
              <dt>Owner</dt><dd>{pageNode.owner || "—"}</dd>
              <dt>Status</dt><dd>{window.statusLabel(pageNode.status)}</dd>
            </>
          )}
        </dl>
      </div>

      {/* Summary */}
      {node.summary && (
        <div className="sb-section">
          <div className="sb-section-label">Purpose</div>
          <div className="sb-summary">{node.summary}</div>
        </div>
      )}

      {/* Above the fold */}
      {(() => {
        if (node.type !== "page") return null;
        const foldIds = children[`foldlist:${node.id}`] || [];
        if (foldIds.length === 0) return null;
        return (
          <div className="sb-section">
            <div className="sb-section-label">
              Above the fold
              <span className="count">{foldIds.length} item{foldIds.length !== 1 ? "s" : ""} · click to inspect</span>
            </div>
            <ol className="sb-fold-list">
              {foldIds.map((foldId, i) => {
                const fn = nodes[foldId];
                if (!fn) return null;
                const sgCount = (suggestionsByContent?.[foldId] || []).length;
                const fnCount = (functionalityByContent?.[foldId] || []).length;
                return (
                  <li
                    key={foldId}
                    className="sb-fold-item is-clickable"
                    role="button"
                    tabIndex={0}
                    onClick={() => onNavigate(foldId)}
                    onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onNavigate(foldId); } }}
                  >
                    <span className="sb-fold-num">{String(i + 1).padStart(2, "0")}</span>
                    <span>{fn.title}</span>
                    {(sgCount > 0 || fnCount > 0) && (
                      <span className="fold-pips" style={{ gridColumn: "1/-1", marginTop: 4 }}>
                        {sgCount > 0 && <span className="content-pip pip-sg">{sgCount} draft{sgCount !== 1 ? "s" : ""}</span>}
                        {fnCount > 0 && <span className="content-pip pip-fn">{fnCount} note{fnCount !== 1 ? "s" : ""}</span>}
                      </span>
                    )}
                  </li>
                );
              })}
            </ol>
          </div>
        );
      })()}

      {/* UX direction */}
      {node.ux && (
        <div className="sb-section">
          <div className="sb-section-label">UX direction</div>
          <div className="sb-summary" style={{ fontStyle: "italic" }}>{node.ux}</div>
        </div>
      )}

      {/* AEO */}
      {node.aeo && node.aeo.length > 0 && (
        <div className="sb-section">
          <div className="sb-section-label">AEO targets <span className="count">questions this page should answer</span></div>
          <ul className="sb-aeo">
            {node.aeo.map((q, i) => <li key={i}>{q}</li>)}
          </ul>
        </div>
      )}

      {/* Children list */}
      {node.type !== "content" && (children[node.id] || []).length > 0 && (
        <div className="sb-section">
          <div className="sb-section-label">
            {node.type === "page" ? "Sections" : "Content needs"}
            <span className="count">{(children[node.id] || []).length}</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {(children[node.id] || []).map((cid) => {
              const c = nodes[cid];
              return (
                <button
                  key={cid}
                  className="iconbtn"
                  onClick={() => onNavigate(cid)}
                  style={{ justifyContent: "flex-start", textAlign: "left", padding: "7px 10px", fontSize: 12.5 }}
                >
                  <window.Glyph type={c.type} />
                  <span style={{ flex: 1 }}>{c.title}</span>
                  {c.type === "section" && (
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--muted)" }}>
                      {(children[cid] || []).length}
                    </span>
                  )}
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* Content-only: Suggested content versions */}
      {node.type === "content" && (
        <window.SuggestedContentSection
          submissions={suggestionsByContent[node.id] || []}
          votes={votes}
          onSubmit={(body) => onSubmitSuggestion(node.id, body)}
          onUpvote={(sid) => onUpvoteSuggestion(node.id, sid)}
          onDelete={(sid) => onDeleteSuggestion(node.id, sid)}
          onAddComment={(sid, body) => onAddSuggestionComment(node.id, sid, body)}
          onDeleteComment={(sid, cid) => onDeleteSuggestionComment(node.id, sid, cid)}
        />
      )}

      {/* Content-only: Intended functionality */}
      {node.type === "content" && (
        <window.IntendedFunctionalitySection
          notes={functionalityByContent[node.id] || []}
          nodes={nodes}
          pages={pageNodes || []}
          onAdd={(payload) => onAddFunctionality(node.id, payload)}
          onDelete={(nid) => onDeleteFunctionality(node.id, nid)}
          onAddComment={(nid, body) => onAddFunctionalityComment(node.id, nid, body)}
          onDeleteComment={(nid, cid) => onDeleteFunctionalityComment(node.id, nid, cid)}
          onNavigate={onNavigate}
        />
      )}

      {/* Comments — anchored to the page for now */}
      <div className="sb-section">
        <div className="sb-section-label">
          Comments
          <span className="count">{comments.length}</span>
        </div>
        <div className="comments-list">
          {comments.length === 0 && (
            <div className="comments-empty">No comments yet on this {node.type}. Start the discussion below.</div>
          )}
          {comments.map((c) => (
            <div key={c.id} className="comment">
              <div className="comment-head">
                <span>
                  <span className="comment-author">{c.author}</span>{" "}
                  <span className="comment-role">{c.role}</span>
                </span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                  <span className="comment-date">{c.date}</span>
                  <window.DeleteButton onConfirm={() => onDeleteComment(node.id, c.id)} title="Delete comment" />
                </span>
              </div>
              <div className="comment-body">{c.body}</div>
            </div>
          ))}
        </div>

        <div className="comment-add">
          <textarea
            value={draft}
            placeholder={`Add a comment on “${node.title}”…`}
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && draft.trim()) {
                onAddComment(node.id, draft.trim());
                setDraft("");
              }
            }}
          />
          <div className="comment-add-actions">
            <small>⌘ + Enter to post</small>
            <button
              className="btn-primary"
              disabled={!draft.trim()}
              onClick={() => { onAddComment(node.id, draft.trim()); setDraft(""); }}
            >
              Post comment
            </button>
          </div>
        </div>
      </div>

      {/* Related links */}
      {node.type !== "content" && (
        <div className="sb-section">
          <div className="sb-section-label">Linked from / to</div>
          <div style={{ fontSize: 12.5, color: "var(--muted)", lineHeight: 1.5 }}>
            {node.type === "page" && (
              <>
                <div>· Primary nav <span style={{ color: "var(--ink-2)" }}>{node.url}</span></div>
                <div>· AI Assistant knowledge index (auto-indexed)</div>
                <div>· Sitemap / robots</div>
                <div>· Footer (if utility section)</div>
              </>
            )}
            {node.type === "section" && (
              <>
                <div>· Page TOC anchor #{node.id.split(":").pop()}</div>
                <div>· Cross-page references (manual)</div>
                <div>· Schema.org markup as content block</div>
              </>
            )}
          </div>
        </div>
      )}
    </aside>
  );
}

Object.assign(window, { Sidebar });
