// Top bar + selection toolbar for the board screen.

function BoardTopBar({
  palette, role, locked, contributorCount, zoom, setZoom,
  onCompose, onStartDoodle, onOpenAdmin, onReveal,
  recipientName, team,
}) {
  const displayName = recipientName || "Gill Tan";
  const initial = (displayName.trim()[0] || "G").toUpperCase();
  const firstName = displayName.split(/\s+/)[0] || displayName;
  const isMobile = useIsMobile();
  return (
    <>
      {/* Recipient context card — desktop only, centered horizontally on
          the viewport so it reads as the page title rather than being
          tucked behind the switcher. Title and meta share one row so the
          card matches the height of the switcher and the action group. */}
      {!isMobile && (
        <div style={{
          position: "absolute",
          top: 14, left: "50%", transform: "translateX(-50%)",
          display: "flex", alignItems: "center", gap: 12,
          padding: "6px 14px 6px 6px",
          background: "rgba(255,255,255,0.86)",
          border: "1px solid var(--line)",
          borderRadius: 14, boxShadow: "var(--shadow-1)",
          backdropFilter: "blur(14px) saturate(140%)",
          WebkitBackdropFilter: "blur(14px) saturate(140%)",
          zIndex: 20,
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 8,
            background: palette.notes[0],
            display: "grid", placeItems: "center",
            fontFamily: "var(--serif)", fontSize: 17, fontStyle: "italic",
            transform: "rotate(-4deg)", flex: "none",
          }}>{initial}</div>
          {/* Baseline-align so the serif title and the sans meta hang on the
              same text line despite their different font sizes. */}
          <div style={{ display: "flex", alignItems: "baseline", gap: 8, lineHeight: 1 }}>
            <span style={{ fontFamily: "var(--serif)", fontSize: 17, letterSpacing: "-0.005em" }}>
              For <em>{displayName}</em>
            </span>
            <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>·</span>
            <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{team || "Atlas Design"}</span>
            <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>·</span>
            <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{contributorCount} contributors</span>
            <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>·</span>
            <span style={{ fontSize: 11.5, color: locked ? palette.accent : "var(--ink-3)" }}>
              {locked ? "Locked" : "Open for notes"}
            </span>
          </div>
        </div>
      )}

      {/* Action group — pinned to the right; recipient card sits centered
          above (or wraps below, on mobile). No forced height so the row
          aligns at the same top line as the switcher and recipient card. */}
      <div style={{
        position: "absolute",
        top: isMobile ? 60 : 14,
        left: isMobile ? 8 : "auto",
        right: isMobile ? 8 : 14,
        display: "flex", gap: 8, alignItems: "center",
        flexWrap: "wrap", justifyContent: "flex-end",
        zIndex: 20,
      }}>
        {role === "admin" && (
          <button className="btn btn-soft" onClick={onOpenAdmin} title="Manage">
            <IconAdmin size={13} />{!isMobile && <span>Manage</span>}
          </button>
        )}
        {role !== "recipient" && !locked && onStartDoodle && (
          <button className="btn btn-soft" onClick={onStartDoodle} title="Sketch directly on the board">
            <IconPen size={13} />{!isMobile && <span>Doodle</span>}
          </button>
        )}
        {role !== "recipient" && !locked && (
          <button className="btn btn-coral" onClick={onCompose}>
            <IconPlus size={14} /> {isMobile ? "Note" : "Add a note"}
          </button>
        )}
        {role === "admin" && locked && (
          <button className="btn btn-coral" onClick={onReveal}>
            <IconGift size={14} /> {isMobile ? "Send" : `Send to ${firstName}`}
          </button>
        )}
      </div>
    </>
  );
}

function SelectionToolbar({ note, zoom, pan, onDelete, onChange, onEdit, onVisibilityChange, onReorder, palette, isAdmin }) {
  // Project the note's top-center from world coords through the stage's
  // pan/zoom into screen space. There's no longer a rotated paper to
  // unwrap — notes live directly in world space.
  const worldX = note.x + note.w / 2;
  const worldY = note.y;
  const cx = worldX * zoom + pan.x;
  const cy = worldY * zoom + pan.y;

  const COLORS = palette.notes;
  const isPublic = note.visibility === "public";
  // Sticker clusters are decorative; doodles are sketched on the board (no
  // modal) — neither has an edit form.
  const canEditInModal = note.type !== "sticker-cluster" && note.type !== "doodle";

  return (
    <div style={{
      position: "absolute",
      left: cx, top: cy - 56,
      transform: "translate(-50%, 0)",
      background: "#fff", border: "1px solid var(--line)",
      borderRadius: 12, padding: 6, boxShadow: "var(--shadow-2)",
      display: "flex", gap: 4, alignItems: "center",
      zIndex: 30,
    }}>
      {note.type !== "photo" && note.type !== "gif" && note.type !== "sticker-cluster" && (
        <>
          <div style={{ display: "flex", gap: 4, padding: "0 4px" }}>
            {COLORS.slice(0, 6).map((c) => (
              <button key={c} onClick={() => onChange({ color: c })} style={{
                width: 18, height: 18, borderRadius: "50%",
                background: c, border: note.color === c ? "1.5px solid var(--ink)" : "1px solid rgba(31,27,23,0.1)",
                cursor: "pointer", padding: 0,
              }} />
            ))}
            <CustomColorButton
              value={note.color}
              onPick={(hex) => onChange({ color: hex })}
              style={{ width: 18, height: 18, borderRadius: "50%" }}
            />
          </div>
          <Divider />
        </>
      )}
      <ToolBtn title="Rotate -" onClick={() => onChange({ rot: (note.rot || 0) - 6 })}>
        <IconRotate size={13} style={{ transform: "scaleX(-1)" }} />
      </ToolBtn>
      <ToolBtn title="Rotate +" onClick={() => onChange({ rot: (note.rot || 0) + 6 })}>
        <IconRotate size={13} />
      </ToolBtn>
      {note.type !== "sticker-cluster" && note.type !== "doodle" && (
        <>
          <Divider />
          <ToolBtn
            title="Smaller text"
            onClick={() => {
              const next = Math.max(0.7, Math.round(((note.fontScale || 1) - 0.1) * 10) / 10);
              onChange({ fontScale: next });
            }}
          >
            <span style={{
              fontFamily: "var(--serif)", fontWeight: 600,
              fontSize: 11, lineHeight: 1, letterSpacing: "-0.02em",
            }}>A−</span>
          </ToolBtn>
          <ToolBtn
            title="Larger text"
            onClick={() => {
              const next = Math.min(2, Math.round(((note.fontScale || 1) + 0.1) * 10) / 10);
              onChange({ fontScale: next });
            }}
          >
            <span style={{
              fontFamily: "var(--serif)", fontWeight: 600,
              fontSize: 15, lineHeight: 1, letterSpacing: "-0.02em",
            }}>A+</span>
          </ToolBtn>
        </>
      )}
      {onReorder && (
        <>
          <Divider />
          <ToolBtn title="Send to back" onClick={() => onReorder(note.id, "back")}>
            <IconSendToBack size={13} />
          </ToolBtn>
          <ToolBtn title="Send backward" onClick={() => onReorder(note.id, "backward")}>
            <IconMoveBackward size={13} />
          </ToolBtn>
          <ToolBtn title="Bring forward" onClick={() => onReorder(note.id, "forward")}>
            <IconMoveForward size={13} />
          </ToolBtn>
          <ToolBtn title="Bring to front" onClick={() => onReorder(note.id, "front")}>
            <IconBringToFront size={13} />
          </ToolBtn>
        </>
      )}
      {onEdit && canEditInModal && (
        <>
          <Divider />
          <ToolBtn title="Edit note" onClick={onEdit}>
            <IconPen size={13} />
          </ToolBtn>
        </>
      )}
      {isAdmin && onVisibilityChange && (
        <>
          <Divider />
          <ToolBtn
            title={isPublic ? "Make private (self)" : "Reveal to everyone (public)"}
            onClick={() => onVisibilityChange(isPublic ? "self" : "public")}
            active={isPublic}
          >
            {isPublic ? <IconEye size={13} /> : <IconEyeOff size={13} />}
          </ToolBtn>
        </>
      )}
      <Divider />
      <ToolBtn title="Delete" onClick={onDelete} danger>
        <IconTrash size={13} />
      </ToolBtn>
    </div>
  );
}

function Divider() {
  return <span style={{ width: 1, height: 18, background: "var(--line)" }} />;
}

function ToolBtn({ children, onClick, title, danger, active }) {
  const baseBg = active ? "rgba(232,126,90,0.12)" : "transparent";
  return (
    <button onClick={onClick} title={title} style={{
      appearance: "none", border: 0, background: baseBg,
      width: 28, height: 28, borderRadius: 7, cursor: "pointer",
      color: danger ? "#C0563D" : (active ? "var(--coral)" : "var(--ink)"),
      display: "grid", placeItems: "center",
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = active ? "rgba(232,126,90,0.18)" : "rgba(31,27,23,0.05)"}
    onMouseLeave={(e) => e.currentTarget.style.background = baseBg}>
      {children}
    </button>
  );
}

Object.assign(window, { BoardTopBar, SelectionToolbar });
