/* global React */
// =====================================================================
// Shared bits used across all 4 sidebar variations:
//   - Icon set (Lucide-derived, 1.5px stroke)
//   - Method8 logo mark (inline SVG)
//   - Mock "page" rendered on the right side of every artboard so the
//     sidebar is shown in proper context. Deliberately compressed so
//     the sidebar reads as the star of each artboard.
//   - Common dark-active-state token: --m8-active-bg
// All components are pushed onto `window` at the end so other
// <script type="text/babel"> files can pick them up.
// =====================================================================

const { useState } = React;

// ----- Theme context. Each Sidebar provides its own theme; sub-components
//       (NavRow / UserChip / SectionLabel) read from context so dark mode
//       flows through without prop-drilling. -----
const ThemeContext = React.createContext(null);
function useT() { return React.useContext(ThemeContext) || T; }

/* ----- Token shortcuts (match colors_and_type.css) ----- */
const T = {
  bgPage:    "#f5f6f8",
  bgPanel:   "#ffffff",
  bgSubtle:  "#f9fafb",
  bgHover:   "#f2f4f7",
  border:    "#e4e7ec",
  borderSoft:"#eef0f3",
  text:      "#101828",
  text2:     "#344054",
  text3:     "#667085",
  text4:     "#98a2b3",
  brand700:  "#364152", // dark slate — active fill
  brand800:  "#202939",
  blue50:    "#eff8ff",
  blue700:   "#175cd3",
  green500:  "#17b26a",
  green600:  "#079455",
  amber500:  "#f79009",
  amber600:  "#dc6803",
  amber700:  "#b54708",
  red600:    "#d92d20",
  violet50:  "#f4f3ff",
  violet600: "#6938ef",
  violet700: "#5925dc",
  fuchsia50: "#fdf4ff",
  fuchsia600:"#ba24d5",
  sky50:     "#eff8ff",
  sky500:    "#0ba5ec",
  orange50:  "#fef6ee",
  orange600: "#e04f16",
};

/* ----- Method8 wordmark / mark ----- */
function M8Logo({ size = 22, mono = false }) {
  // Infinity-ribbon style: two crossed rounded loops.
  // Sky-blue per design system; mono variant uses currentColor.
  const a = mono ? "currentColor" : "#7CD4FD";
  const b = mono ? "currentColor" : "#36BFFA";
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <path d="M9.5 10C5.4 10 2 12.7 2 16s3.4 6 7.5 6c2.5 0 4.6-1.1 6.5-3l4.5-6c1.9-1.9 4-3 6.5-3 4.1 0 7.5 2.7 7.5 6"
        stroke={a} strokeWidth="3" strokeLinecap="round" transform="translate(-2 0)"/>
      <path d="M22.5 22C26.6 22 30 19.3 30 16s-3.4-6-7.5-6c-2.5 0-4.6 1.1-6.5 3l-4.5 6c-1.9 1.9-4 3-6.5 3"
        stroke={b} strokeWidth="3" strokeLinecap="round" transform="translate(-2 0)"/>
    </svg>
  );
}

/* ----- Icon set ----- */
const stroke = { fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };

const Icon = {
  dashboard: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||18} height={p?.size||18} {...stroke}>
      <rect x="3" y="3" width="7" height="9" rx="1.5"/>
      <rect x="14" y="3" width="7" height="5" rx="1.5"/>
      <rect x="14" y="12" width="7" height="9" rx="1.5"/>
      <rect x="3" y="16" width="7" height="5" rx="1.5"/>
    </svg>
  ),
  assessments: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||18} height={p?.size||18} {...stroke}>
      <path d="M5 4h11l3 3v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Z"/>
      <path d="M8 11h8M8 15h8M8 7h5"/>
    </svg>
  ),
  modules: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||18} height={p?.size||18} {...stroke}>
      <rect x="3" y="4" width="18" height="13" rx="2"/>
      <path d="M8 21h8M12 17v4"/>
    </svg>
  ),
  actions: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||18} height={p?.size||18} {...stroke}>
      <circle cx="12" cy="12" r="9"/>
      <circle cx="12" cy="12" r="5"/>
      <circle cx="12" cy="12" r="1.5" fill="currentColor" stroke="none"/>
    </svg>
  ),
  search: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||16} height={p?.size||16} {...stroke}>
      <circle cx="11" cy="11" r="7"/>
      <path d="m20 20-3.5-3.5"/>
    </svg>
  ),
  chev: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||14} height={p?.size||14} {...stroke}>
      <path d="m9 6 6 6-6 6"/>
    </svg>
  ),
  chevDn: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||14} height={p?.size||14} {...stroke}>
      <path d="m6 9 6 6 6-6"/>
    </svg>
  ),
  caretUpDn: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||14} height={p?.size||14} {...stroke}>
      <path d="m8 9 4-4 4 4M8 15l4 4 4-4"/>
    </svg>
  ),
  plus: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||16} height={p?.size||16} {...stroke}>
      <path d="M12 5v14M5 12h14"/>
    </svg>
  ),
  star: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||14} height={p?.size||14} {...stroke}>
      <path d="m12 4 2.5 5.2 5.7.8-4.1 4 1 5.7L12 17l-5.1 2.7 1-5.7-4.1-4 5.7-.8L12 4Z"/>
    </svg>
  ),
  bell: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||16} height={p?.size||16} {...stroke}>
      <path d="M6 9a6 6 0 1 1 12 0c0 5 2 6 2 6H4s2-1 2-6Z"/>
      <path d="M10 19a2 2 0 0 0 4 0"/>
    </svg>
  ),
  panel: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||18} height={p?.size||18} {...stroke}>
      <rect x="3" y="4" width="18" height="16" rx="2"/>
      <path d="M9 4v16"/>
    </svg>
  ),
  kebab: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||14} height={p?.size||14} fill="currentColor">
      <circle cx="12" cy="5" r="1.5"/>
      <circle cx="12" cy="12" r="1.5"/>
      <circle cx="12" cy="19" r="1.5"/>
    </svg>
  ),
  check: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||14} height={p?.size||14} {...stroke}>
      <path d="m5 12 5 5 9-10"/>
    </svg>
  ),
  lock: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||14} height={p?.size||14} {...stroke}>
      <rect x="5" y="10" width="14" height="10" rx="2"/>
      <path d="M8 10V7a4 4 0 1 1 8 0v3"/>
    </svg>
  ),
  live: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||14} height={p?.size||14} fill="currentColor">
      <circle cx="12" cy="12" r="4"/>
    </svg>
  ),
  clock: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||14} height={p?.size||14} {...stroke}>
      <circle cx="12" cy="12" r="9"/>
      <path d="M12 7v5l3 2"/>
    </svg>
  ),
  inbox: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||16} height={p?.size||16} {...stroke}>
      <path d="M3 13h5l2 3h4l2-3h5"/>
      <path d="M5 5h14l2 8v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-6l2-8Z"/>
    </svg>
  ),
  flame: (p) => (
    <svg viewBox="0 0 24 24" width={p?.size||14} height={p?.size||14} {...stroke}>
      <path d="M12 3s4 4 4 8a4 4 0 0 1-8 0c0-1 .5-2 1-2.5C8 11 7 14 7 16a5 5 0 0 0 10 0c0-5-5-13-5-13Z"/>
    </svg>
  ),
  cmd: () => <span style={{ fontFamily: "ui-sans-serif, system-ui", fontWeight: 500 }}>⌘</span>,
};

/* ----- Avatar dot ----- */
function Avatar({ src, size = 24, status, ring = "#fff" }) {
  return (
    <span style={{
      position: "relative",
      width: size, height: size,
      display: "inline-block", flex: "none",
    }}>
      <img src={src} alt="" style={{
        width: size, height: size, borderRadius: "50%",
        objectFit: "cover", display: "block",
        boxShadow: `0 0 0 2px ${ring}`,
      }}/>
      {status && (
        <span style={{
          position: "absolute", right: -1, bottom: -1,
          width: Math.max(8, size*0.32), height: Math.max(8, size*0.32),
          borderRadius: "50%",
          background: status === "online" ? T.green500
                    : status === "idle"   ? T.amber500
                    : T.text4,
          boxShadow: `0 0 0 2px ${ring}`,
        }}/>
      )}
    </span>
  );
}

/* ----- Avatar stack (3 overlapping) ----- */
function AvatarStack({ srcs, size = 22, ring = "#fff" }) {
  return (
    <span style={{ display: "inline-flex" }}>
      {srcs.map((s, i) => (
        <img key={i} src={s} alt="" style={{
          width: size, height: size, borderRadius: "50%",
          objectFit: "cover",
          boxShadow: `0 0 0 1.5px ${ring}`,
          marginLeft: i === 0 ? 0 : -size*0.32,
          position: "relative", zIndex: srcs.length - i,
        }}/>
      ))}
    </span>
  );
}

/* ----- Section label (small caps eyebrow) ----- */
function SectionLabel({ children, right, style }) {
  const T = useT();
  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "14px 14px 6px",
      font: "600 10px/14px Inter, system-ui",
      letterSpacing: 0.6, textTransform: "uppercase",
      color: T.text4,
      ...style,
    }}>
      <span>{children}</span>
      {right}
    </div>
  );
}

/* =====================================================================
   Right-side mock — a compressed version of the Safety Standard Gap
   Assessment workshop screen. Same across all 4 artboards. Deliberately
   not interactive; we want eyes on the sidebar.
   ===================================================================== */

const ROWS = [
  { n: "1.1", state: "yes",     who: null,     title: "A current, approved Sustainability Policy exists",       badges: ["No"] },
  { n: "1.2", state: "yes",     who: null,     title: "Leadership conducts visible safety walks monthly",        badges: ["Yes","Evidence"] },
  { n: "1.3", state: "yes",     who: null,     title: "Safety walk outcomes are reinforced through coaching",   badges: ["N/A"] },
  { n: "1.4", state: "locked",  who: "marcus", title: "A formal site evacuation programme is integrated",        badges: [] },
  { n: "2.1", state: "yes",     who: null,     title: "A site-wide hazard register is maintained and reviewed", badges: ["Yes","Evidence: No"] },
  { n: "2.2", state: "empty",   who: null,     title: "Pre-task hazard assessments are completed",               badges: [] },
];

function MockWorkspace({ headerLeft, headerRight, condense = false }) {
  return (
    <div style={{
      flex: 1, minWidth: 0,
      display: "flex", flexDirection: "column",
      background: "#fff",
      borderTopRightRadius: 14, borderBottomRightRadius: 14,
      overflow: "hidden",
    }}>
      {/* Header strip */}
      <div style={{
        height: 60, padding: "0 20px",
        display: "flex", alignItems: "center", gap: 14,
        borderBottom: `1px solid ${T.border}`,
        background: "rgba(255,255,255,0.85)",
        flex: "none",
      }}>
        {headerLeft}
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8 }}>
          {headerRight}
        </div>
      </div>

      {/* Body */}
      <div style={{ flex: 1, overflow: "hidden", padding: "20px 24px 0", display: "flex", flexDirection: "column", gap: 14, minHeight: 0 }}>
        {/* Title block */}
        <div style={{
          background: "#fff", border: `1px solid ${T.border}`, borderRadius: 12,
          padding: "16px 18px",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 6 }}>
            <h1 style={{ margin: 0, font: "600 20px/26px Inter", color: T.text }}>Safety Standard Gap Assessment</h1>
            <span style={{
              marginLeft: "auto",
              display: "inline-flex", alignItems: "center", gap: 6,
              padding: "3px 9px", borderRadius: 999,
              background: T.violet50, color: T.violet700,
              font: "500 11px/14px Inter",
            }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: T.violet600 }}/>
              2 questions being edited
            </span>
            <span style={{
              display: "inline-flex", alignItems: "center", gap: 5,
              padding: "3px 9px", borderRadius: 999,
              background: "#fff8ec", color: T.amber700,
              font: "500 11px/14px Inter",
              border: `1px solid #fde2a3`,
            }}>👑 Completer · You</span>
            <AvatarStack srcs={["avatars/av-me.svg","avatars/av-marcus.svg","avatars/av-priya.svg"]} size={22}/>
          </div>
          <div style={{ font: "400 12px/18px Inter", color: T.text3, marginBottom: 12 }}>
            Gold Fields · 10 questions · collaborative workshop
          </div>
          <div style={{ height: 6, background: T.bgHover, borderRadius: 999, overflow: "hidden" }}>
            <div style={{ width: "80%", height: "100%", background: `linear-gradient(90deg, ${T.green500}, ${T.green600})` }}/>
          </div>
          <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 6 }}>
            <span style={{ font: "500 11px/14px Inter", color: T.text3 }}>8 of 10 · <span style={{ color: T.text2 }}>80%</span></span>
          </div>
        </div>

        {/* Two-col workshop */}
        <div style={{ display: "grid", gridTemplateColumns: condense ? "180px 1fr" : "200px 1fr 220px", gap: 14, minHeight: 0, flex: 1 }}>
          {/* Question nav */}
          <div style={{
            background: "#fff", border: `1px solid ${T.border}`, borderRadius: 12, padding: "10px 8px",
            overflow: "hidden",
          }}>
            <div style={{ padding: "4px 8px", font: "600 10px/14px Inter", color: T.text4, letterSpacing: 0.5, textTransform: "uppercase" }}>
              Visible felt leadership
            </div>
            {["1.1","1.2","1.3","1.4"].map(n => (
              <div key={n} style={{
                display: "flex", alignItems: "center", gap: 8,
                padding: "5px 8px", borderRadius: 6,
                font: "400 12px/16px Inter", color: n==="1.4" ? T.text3 : T.text2,
              }}>
                <Icon.check size={11}/>
                <span style={{ font: "500 10px/14px ui-monospace", color: T.text3 }}>{n}</span>
                <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  {n==="1.4" ? "A formal site evacuation…" : "Item " + n}
                </span>
              </div>
            ))}
            <div style={{ padding: "8px 8px 4px", font: "600 10px/14px Inter", color: T.text4, letterSpacing: 0.5, textTransform: "uppercase" }}>
              Hazard identification
            </div>
            {["2.1","2.2","2.3"].map(n => (
              <div key={n} style={{
                display: "flex", alignItems: "center", gap: 8,
                padding: "5px 8px", borderRadius: 6,
                font: "400 12px/16px Inter", color: T.text2,
              }}>
                <Icon.check size={11}/>
                <span style={{ font: "500 10px/14px ui-monospace", color: T.text3 }}>{n}</span>
                <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>Item {n}</span>
              </div>
            ))}
          </div>

          {/* Question list */}
          <div style={{ overflow: "hidden", display: "flex", flexDirection: "column", gap: 8 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 18, padding: "0 2px 8px", borderBottom: `1px solid ${T.border}` }}>
              <span style={{ font: "600 13px/18px Inter", color: T.blue700, paddingBottom: 6, borderBottom: `2px solid ${T.blue700}`, marginBottom: -1 }}>
                Questions <span style={{ marginLeft: 6, padding: "1px 6px", borderRadius: 999, background: T.blue50, font: "600 10px/14px Inter" }}>10</span>
              </span>
              <span style={{ font: "500 13px/18px Inter", color: T.text3 }}>
                Actions <span style={{ marginLeft: 6, padding: "1px 6px", borderRadius: 999, background: T.bgHover, font: "600 10px/14px Inter" }}>5</span>
              </span>
            </div>
            {ROWS.slice(0, 4).map(r => (
              <div key={r.n} style={{
                position: "relative",
                border: `1px solid ${T.border}`, borderRadius: 10,
                padding: "10px 12px 10px 14px", background: "#fff",
              }}>
                {r.state === "locked" && (
                  <span style={{
                    position: "absolute", left: 0, top: 4, bottom: 4, width: 3, borderRadius: 4,
                    background: T.violet600,
                  }}/>
                )}
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <span style={{
                    width: 18, height: 18, borderRadius: 999,
                    background: r.state === "yes" ? "#dcfae6" : r.state === "locked" ? T.violet50 : "#fff",
                    color:      r.state === "yes" ? T.green600 : r.state === "locked" ? T.violet600 : T.text4,
                    display: "grid", placeItems: "center",
                    border: r.state === "empty" ? `1.5px solid ${T.border}` : "none",
                  }}>
                    {r.state === "yes" && <Icon.check size={11}/>}
                    {r.state === "locked" && <Icon.lock size={10}/>}
                  </span>
                  <span style={{ font: "500 10px/14px ui-monospace", color: T.text3 }}>{r.n}</span>
                  <span style={{ flex: 1, minWidth: 0, font: "500 13px/18px Inter", color: T.text, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {r.title}
                  </span>
                  <Icon.chevDn size={14}/>
                </div>
                <div style={{ display: "flex", gap: 6, marginTop: 6, marginLeft: 38 }}>
                  {r.badges.map(b => (
                    <span key={b} style={{
                      padding: "2px 7px", borderRadius: 6,
                      font: "500 11px/14px Inter",
                      background: b === "Yes" ? "#ecfdf3" : b === "No" ? "#fef3f2" : b === "N/A" ? T.blue50 : b === "Evidence: No" ? "#fef3f2" : "#ecfdf3",
                      color:      b === "Yes" ? T.green600 : b === "No" ? T.red600 : b === "N/A" ? T.blue700 : b === "Evidence: No" ? T.red600 : T.green600,
                    }}>{b}</span>
                  ))}
                  {r.state === "locked" && (
                    <span style={{ padding: "2px 7px", borderRadius: 6, font: "500 11px/14px Inter", background: T.violet50, color: T.violet700 }}>Marcus is editing</span>
                  )}
                </div>
              </div>
            ))}
          </div>

          {/* Session rail */}
          {!condense && (
            <div style={{ background: "#fff", border: `1px solid ${T.border}`, borderRadius: 12, padding: "12px 12px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 10 }}>
                <span style={{ width: 7, height: 7, borderRadius: 999, background: T.green500 }}/>
                <span style={{ font: "600 10px/14px Inter", color: T.text4, letterSpacing: 0.5, textTransform: "uppercase" }}>In this session · 4</span>
              </div>
              {[
                { src: "avatars/av-me.svg",     name: "Andrew Matt (you)", sub: "You · viewing list", st: "online" },
                { src: "avatars/av-marcus.svg", name: "Marcus Chen",       sub: "Typing in 1.4",      st: "online" },
                { src: "avatars/av-priya.svg",  name: "Priya Iyer",        sub: "Typing in 2.3",      st: "online" },
                { src: "avatars/av-sarah.svg",  name: "Sarah Mensah",      sub: "Idle · 5m",          st: "idle"  },
              ].map(p => (
                <div key={p.name} style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 0" }}>
                  <Avatar src={p.src} size={26} status={p.st}/>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ font: "500 12px/16px Inter", color: T.text, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.name}</div>
                    <div style={{ font: "400 11px/14px Inter", color: T.text3, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.sub}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* Export to window so sibling Babel files can see them */

// ----- Dark/light palette swap. Returns a "T" with the same keys but
//       repainted for the chosen theme. Variants shadow their global T
//       with the result so dark mode flows through with zero refactor. -----
function makeTheme(dark) {
  if (!dark) return { ...T, dark: false };
  return {
    ...T,
    dark: true,
    bgPage:     "#0d121c",
    bgPanel:    "#0d121c",
    bgSubtle:   "rgba(255,255,255,0.04)",
    bgHover:    "rgba(255,255,255,0.08)",
    border:     "rgba(255,255,255,0.10)",
    borderSoft: "rgba(255,255,255,0.06)",
    text:       "#ffffff",
    text2:      "rgba(255,255,255,0.86)",
    text3:      "rgba(255,255,255,0.56)",
    text4:      "rgba(255,255,255,0.40)",
    brand700:   "#3a4a5e",  // active row in dark — elevated slate
    brand800:   "#0d121c",
    // Slightly less saturated accents so they don't burn on the dark bg
    blue50:     "rgba(46,144,250,0.18)",
    blue700:    "#7cc4ff",
    violet50:   "rgba(122,90,248,0.18)",
    violet600:  "#a78bfa",
    violet700:  "#c4b5fd",
    green500:   "#34d399",
    green600:   "#34d399",
    red600:     "#fb7185",
    amber500:   "#fbbf24",
    amber700:   "#fbbf24",
    sky500:     "#38bdf8",
  };
}

Object.assign(window, { T, makeTheme, ThemeContext, useT, M8Logo, Icon, Avatar, AvatarStack, SectionLabel, MockWorkspace });
