// AUTOMATION PLATFORM — Authoring sub-platform (Visual Editor v2)
// Restructured into 6 primary groups with pill sub-navigation
const { useState: useAuthState } = React;
const Tauth = window.ArbiterTokens;

// Legacy flat views — retained for back-compat
const AUTH_VIEWS = [
  { id: 'designer',    label: 'Visual Designer' },
  { id: 'schemas',     label: 'Event Schemas' },
  { id: 'variants',    label: 'A/B Variants' },
  { id: 'marketplace', label: 'Marketplace' },
];

// Visual Editor v2 — 6 primary groups with pill sub-nav
const VE_GROUPS = [
  { id: 'canvas',      label: 'Canvas Intelligence',   subs: [
    { id: 'designer',   label: 'Designer' },
    { id: 've1',        label: 'Validation' },
    { id: 've2',        label: 'Version history' },
    { id: 've3',        label: 'Subflows' },
    { id: 've4',        label: 'Primitives' },
    { id: 've5',        label: 'Swimlanes' },
  ]},
  { id: 'data',        label: 'Data & Testing',         subs: [
    { id: 've6',        label: 'Variables' },
    { id: 'schemas',    label: 'Schemas' },
    { id: 've7',        label: 'Schema binding' },
    { id: 've8',        label: 'Test harness' },
  ]},
  { id: 'ai',          label: 'AI & Compliance',        subs: [
    { id: 've9',        label: 'Copilot' },
    { id: 've10',       label: 'Optimizer' },
    { id: 've11',       label: 'Compliance overlay' },
  ]},
  { id: 'release',     label: 'Governance & Release',   subs: [
    { id: 've12',       label: 'Collaboration' },
    { id: 've13',       label: 'Publish pipeline' },
    { id: 've14',       label: 'Canary' },
    { id: 've15',       label: 'Variants (canvas)' },
    { id: 'variants',   label: 'A/B Variants (legacy)' },
  ]},
  { id: 'obs',         label: 'Observability & Economics', subs: [
    { id: 've16',       label: 'Heatmap' },
    { id: 've17',       label: 'Incident replay' },
    { id: 've18',       label: 'Cost ledger' },
  ]},
  { id: 'ext',         label: 'Extensibility & UX',     subs: [
    { id: 've19',       label: 'Marketplace drop-ins' },
    { id: 'marketplace',label: 'Template marketplace' },
    { id: 've20',       label: 'Keyboard & A11y' },
  ]},
];

const VE_DEFAULT_SUB = VE_GROUPS.reduce((acc, g) => { acc[g.id] = g.subs[0].id; return acc; }, {});

function ABadge({ color, bg, children, mono = false }) {
  return <span style={{ display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: bg, color, fontFamily: mono ? Tauth.font.mono : Tauth.font.family }}>{children}</span>;
}

// ─── DESIGNER — Enterprise-grade drag-and-drop canvas ─────────────────────────
// Drag palette items onto canvas to add nodes
// Drag existing nodes to reposition (with grid snap)
// Drag from node output handle to another node to create edges
// Canvas: 720px tall · scrollable · 1800px logical width · larger nodes
function AuthDesigner({ data }) {
  const au = window.__au;
  const { useRef: useAuthRef } = React;

  const PALETTE_W   = 88;
  const INSPECTOR_W = 340;
  const CANVAS_H    = 720;
  const CANVAS_W    = 1800;
  const NODE_W      = 180;
  const NODE_H      = 84;
  const GRID        = 16;
  const PAD         = 40;

  const typeStyle = (t) => {
    if (t === 'script')      return { bg: au.limeBg,    color: au.lime,    icon: 'cmd', label: 'SCRIPT' };
    if (t === 'human')       return { bg: au.cobaltBg,  color: au.cobalt,  icon: '◉', label: 'HUMAN' };
    if (t === 'approval')    return { bg: au.amberBg,   color: au.amber,   icon: 'ok', label: 'APPROVAL' };
    if (t === 'integration') return { bg: au.tealBg,    color: au.teal,    icon: '↯', label: 'INTEGRATION' };
    if (t === 'branch')      return { bg: au.violetBg,  color: au.violet,  icon: '◇', label: 'BRANCH' };
    return { bg: Tauth.color.bg.secondary, color: Tauth.color.text.secondary, icon: '●', label: 'STEP' };
  };
  const newLabelForType = (t) => ({
    script: 'New script step', human: 'New human step', approval: 'New approval',
    integration: 'New integration', branch: 'New branch',
  }[t] || 'New step');

  // ── State ────────────────────────────────────────────────────────────────
  const [steps, setSteps] = useAuthState([
    { id: 'step-1', name: 'Research memo',        type: 'script',     x: PAD + 0*200,  y: PAD + 0*120, script: 'SC-014', note: 'Prior-art + case-law extraction' },
    { id: 'step-2', name: 'Outline',              type: 'human',      x: PAD + 1*200,  y: PAD + 0*120, assignee: 'Primary associate', note: 'Partner-approved template' },
    { id: 'step-3', name: 'Draft',                type: 'human',      x: PAD + 2*200,  y: PAD + 0*120, assignee: 'Senior associate',  note: '~30-page brief target' },
    { id: 'step-4', name: 'Cite-check',           type: 'script',     x: PAD + 3*200,  y: PAD + 0*120, script: 'SC-001', note: 'Shepard + Westlaw citator. Retry 5x exp backoff.' },
    { id: 'step-5', name: 'Partner review',       type: 'approval',   x: PAD + 4*200,  y: PAD + 0*120, role: 'Partner',  note: 'Blocking gate. Rejection returns to draft.' },
    { id: 'step-6a',name: 'Client review',        type: 'human',      x: PAD + 5*200,  y: PAD + 0*120, assignee: 'Client contact', note: 'Optional — skipped for internal.' },
    { id: 'step-6b',name: 'Auto-approve trivial', type: 'branch',     x: PAD + 5*200,  y: PAD + 1*120, cond: 'if changes = 0',     note: 'Parallel path for nit-level revisions.' },
    { id: 'step-7', name: 'Revisions',            type: 'human',      x: PAD + 6*200,  y: PAD + 0*120, assignee: 'Drafting associate', note: 'Loop until approval.' },
    { id: 'step-8', name: 'Filing',               type: 'integration',x: PAD + 7*200,  y: PAD + 0*120, integration: 'INT-014 court-filing',     note: 'PACER/ECF upload.' },
    { id: 'step-9', name: 'Service',              type: 'integration',x: PAD + 8*200,  y: PAD + 0*120, integration: 'INT-015 service-of-process', note: 'Serve all parties.' },
  ]);
  const [edges, setEdges] = useAuthState([
    ['step-1','step-2'],['step-2','step-3'],['step-3','step-4'],['step-4','step-5'],
    ['step-5','step-6a'],['step-5','step-6b'],['step-6a','step-7'],['step-6b','step-8'],
    ['step-7','step-8'],['step-8','step-9'],
  ]);
  const [selected, setSelected] = useAuthState('step-4');
  const [drag, setDrag] = useAuthState(null);   // { kind: 'palette'|'move'|'edge', ... }
  const [seq, setSeq] = useAuthState(100);
  const [flash, setFlash] = useAuthState(null);
  const canvasRef = useAuthRef(null);

  const flashMsg = (msg) => { setFlash(msg); setTimeout(() => setFlash(null), 2400); };
  const snap = (v) => Math.round(v / GRID) * GRID;

  const getCanvasRect = () => canvasRef.current?.getBoundingClientRect();
  const clientToCanvas = (clientX, clientY) => {
    const r = getCanvasRect();
    if (!r) return { x: 0, y: 0 };
    return {
      x: clientX - r.left + (canvasRef.current.scrollLeft || 0),
      y: clientY - r.top  + (canvasRef.current.scrollTop  || 0),
    };
  };

  // ── Global mouse-move / mouse-up ─────────────────────────────────────────
  React.useEffect(() => {
    if (!drag) return;
    const onMove = (e) => {
      const pt = clientToCanvas(e.clientX, e.clientY);
      if (drag.kind === 'palette') {
        setDrag({ ...drag, ghostX: pt.x - NODE_W/2, ghostY: pt.y - NODE_H/2 });
      } else if (drag.kind === 'move') {
        const nx = snap(pt.x - drag.offsetX);
        const ny = snap(pt.y - drag.offsetY);
        setSteps(prev => prev.map(s => s.id === drag.nodeId ? { ...s, x: Math.max(0, nx), y: Math.max(0, ny) } : s));
      } else if (drag.kind === 'edge') {
        setDrag({ ...drag, curX: pt.x, curY: pt.y });
      }
    };
    const onUp = (e) => {
      const pt = clientToCanvas(e.clientX, e.clientY);
      if (drag.kind === 'palette') {
        const r = getCanvasRect();
        const inside = r && e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom;
        if (inside) {
          const id = 'step-' + seq;
          const newNode = {
            id, name: newLabelForType(drag.nodeType), type: drag.nodeType,
            x: snap(pt.x - NODE_W/2), y: snap(pt.y - NODE_H/2), note: 'Newly-added step — configure in inspector.',
          };
          setSteps(prev => [...prev, newNode]);
          setSeq(seq + 1);
          setSelected(id);
          flashMsg(`Added ${drag.nodeType} · ${id}`);
        }
      } else if (drag.kind === 'edge') {
        // Find which node the mouse is over (if any)
        const target = steps.find(s => pt.x >= s.x && pt.x <= s.x + NODE_W && pt.y >= s.y && pt.y <= s.y + NODE_H);
        if (target && target.id !== drag.sourceId) {
          const already = edges.some(e => e[0] === drag.sourceId && e[1] === target.id);
          if (!already) {
            setEdges(prev => [...prev, [drag.sourceId, target.id]]);
            flashMsg(`Connected ${drag.sourceId} → ${target.id}`);
          }
        }
      }
      setDrag(null);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
  }, [drag, steps, edges, seq]);

  const startPaletteDrag = (e, type) => {
    e.preventDefault();
    const pt = clientToCanvas(e.clientX, e.clientY);
    setDrag({ kind: 'palette', nodeType: type, ghostX: pt.x - NODE_W/2, ghostY: pt.y - NODE_H/2 });
  };
  const startNodeDrag = (e, node) => {
    e.stopPropagation();
    const pt = clientToCanvas(e.clientX, e.clientY);
    setDrag({ kind: 'move', nodeId: node.id, offsetX: pt.x - node.x, offsetY: pt.y - node.y });
    setSelected(node.id);
  };
  const startEdgeDrag = (e, node) => {
    e.stopPropagation();
    const pt = clientToCanvas(e.clientX, e.clientY);
    setDrag({ kind: 'edge', sourceId: node.id, curX: pt.x, curY: pt.y });
  };
  const deleteSelected = () => {
    if (!selected) return;
    setSteps(prev => prev.filter(s => s.id !== selected));
    setEdges(prev => prev.filter(e => e[0] !== selected && e[1] !== selected));
    flashMsg(`Deleted ${selected}`);
    setSelected(null);
  };

  const sel = steps.find(s => s.id === selected);
  const selStyle = sel ? typeStyle(sel.type) : null;

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.fuchsia}`, background: au.fuchsiaBg }}>
        <div style={{ padding: '14px 18px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '12px', fontWeight: 700, color: au.fuchsia, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Visual workflow designer — MSJ-Opposition-Workflow v14</div>
            <div style={{ fontSize: '11px', color: Tauth.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
              <b>Drag</b> palette items onto the canvas · <b>Drag</b> nodes to reposition (grid-snap) · <b>Drag</b> from the output handle to connect nodes.
            </div>
          </div>
          {flash && (
            <div style={{ padding: '6px 14px', background: `${au.fuchsia}14`, border: `1px solid ${au.fuchsia}55`, borderRadius: '6px', fontSize: '11px', fontWeight: 700, color: au.fuchsia, textTransform: 'uppercase', letterSpacing: '0.06em' }}>▸ {flash}</div>
          )}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: `${PALETTE_W}px 1fr ${INSPECTOR_W}px`, gap: '16px' }}>
        {/* ── LEFT PALETTE ──────────────────────────────────────────────── */}
        <div style={{ ...au.card, height: CANVAS_H + 50 }}>
          <div style={{ padding: '12px 8px', textAlign: 'center', fontSize: '10px', fontWeight: 700, color: Tauth.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', borderBottom: `1px solid ${Tauth.color.border.light}` }}>Add step</div>
          <div style={{ padding: '12px 8px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
            {['script','human','approval','integration','branch'].map(t => {
              const ts = typeStyle(t);
              return (
                <div key={t} onMouseDown={(e) => startPaletteDrag(e, t)}
                  title={`Drag to canvas · ${ts.label}`}
                  style={{
                    padding: '14px 0', borderRadius: '8px',
                    border: `1px solid ${ts.color}44`,
                    background: ts.bg, color: ts.color,
                    fontSize: '20px', fontWeight: 700,
                    textAlign: 'center', cursor: 'grab', userSelect: 'none',
                    transition: 'transform 0.1s ease',
                  }}>
                  {ts.icon}
                  <div style={{ fontSize: '8px', fontWeight: 700, marginTop: '4px', letterSpacing: '0.08em' }}>{ts.label}</div>
                </div>
              );
            })}
          </div>
        </div>

        {/* ── CANVAS ────────────────────────────────────────────────────── */}
        <div style={{ ...au.card, overflow: 'hidden' }}>
          <div style={{ ...au.cardH, padding: '12px 18px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <span style={{ fontSize: '12px', fontWeight: 700 }}>Canvas</span>
              <span style={{ fontFamily: Tauth.font.mono, fontSize: '10px', color: Tauth.color.text.tertiary }}>
                {steps.length} nodes · {edges.length} edges
              </span>
            </div>
            <div style={{ display: 'flex', gap: '8px' }}>
              <button style={au.btnSecondary} onClick={deleteSelected} disabled={!selected}>Delete selected</button>
              <button style={au.btnSecondary}>Validate</button>
              <button style={au.btnSecondary}>Save draft</button>
              <button style={au.btnPrimary}>Request publish</button>
            </div>
          </div>
          <div ref={canvasRef}
            style={{
              position: 'relative', height: `${CANVAS_H}px`, overflow: 'auto',
              background: `radial-gradient(circle, ${Tauth.color.border.light} 1px, transparent 1px)`,
              backgroundSize: '16px 16px', backgroundPosition: '0 0',
              cursor: drag?.kind === 'palette' ? 'copy' : drag?.kind === 'move' ? 'grabbing' : drag?.kind === 'edge' ? 'crosshair' : 'default',
            }}
            onClick={() => setSelected(null)}>
            <svg style={{ position: 'absolute', top: 0, left: 0, width: `${CANVAS_W}px`, height: `${CANVAS_H * 2}px`, pointerEvents: 'none' }}>
              <defs>
                <marker id="arr" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
                  <path d="M 0 0 L 9 4.5 L 0 9 z" fill={au.fuchsia} />
                </marker>
                <marker id="arr-live" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
                  <path d="M 0 0 L 9 4.5 L 0 9 z" fill={au.lime} />
                </marker>
              </defs>
              {edges.map(([from, to], i) => {
                const a = steps.find(s => s.id === from);
                const b = steps.find(s => s.id === to);
                if (!a || !b) return null;
                const x1 = a.x + NODE_W, y1 = a.y + NODE_H/2;
                const x2 = b.x,          y2 = b.y + NODE_H/2;
                const mx = (x1 + x2) / 2;
                return (
                  <path key={i} d={`M ${x1} ${y1} C ${mx} ${y1}, ${mx} ${y2}, ${x2} ${y2}`}
                    fill="none" stroke={au.fuchsia} strokeWidth="1.8" strokeOpacity="0.7" markerEnd="url(#arr)" />
                );
              })}
              {drag?.kind === 'edge' && (() => {
                const src = steps.find(s => s.id === drag.sourceId);
                if (!src) return null;
                const x1 = src.x + NODE_W, y1 = src.y + NODE_H/2;
                const x2 = drag.curX,      y2 = drag.curY;
                const mx = (x1 + x2) / 2;
                return <path d={`M ${x1} ${y1} C ${mx} ${y1}, ${mx} ${y2}, ${x2} ${y2}`}
                  fill="none" stroke={au.lime} strokeWidth="2.2" strokeDasharray="6 4" markerEnd="url(#arr-live)" />;
              })()}
            </svg>

            {/* Nodes */}
            {steps.map(s => {
              const ts = typeStyle(s.type);
              const isSel = selected === s.id;
              return (
                <div key={s.id}
                  onMouseDown={(e) => startNodeDrag(e, s)}
                  onClick={(e) => { e.stopPropagation(); setSelected(s.id); }}
                  style={{
                    position: 'absolute', left: `${s.x}px`, top: `${s.y}px`,
                    width: `${NODE_W}px`, height: `${NODE_H}px`,
                    background: Tauth.color.bg.card,
                    border: `${isSel ? 2 : 1}px solid ${isSel ? ts.color : Tauth.color.border.light}`,
                    borderLeft: `5px solid ${ts.color}`,
                    borderRadius: '8px', padding: '10px 14px',
                    cursor: drag?.kind === 'move' && drag.nodeId === s.id ? 'grabbing' : 'grab',
                    boxShadow: isSel ? `0 6px 18px ${ts.color}44` : `0 2px 6px rgba(0,0,0,0.08)`,
                    fontSize: '12px',
                    display: 'flex', flexDirection: 'column', justifyContent: 'center',
                    userSelect: 'none', transition: 'box-shadow 0.15s ease',
                  }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>
                    <span style={{ color: ts.color, fontWeight: 700, fontSize: '13px' }}>{ts.icon}</span>
                    <span style={{ fontSize: '9px', fontWeight: 700, color: ts.color, textTransform: 'uppercase', letterSpacing: '0.08em' }}>{ts.label}</span>
                  </div>
                  <div style={{ fontSize: '12px', fontWeight: 600, color: Tauth.color.text.primary, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.name}</div>
                  <div style={{ fontSize: '9px', fontFamily: Tauth.font.mono, color: Tauth.color.text.tertiary, marginTop: '2px' }}>{s.id}</div>

                  {/* Input handle (left) */}
                  <div style={{
                    position: 'absolute', left: '-7px', top: '50%', transform: 'translateY(-50%)',
                    width: '12px', height: '12px', borderRadius: '50%',
                    background: Tauth.color.bg.card, border: `2px solid ${ts.color}`,
                  }} />
                  {/* Output handle (right) — drag to create edge */}
                  <div onMouseDown={(e) => startEdgeDrag(e, s)}
                    title="Drag to connect"
                    style={{
                      position: 'absolute', right: '-7px', top: '50%', transform: 'translateY(-50%)',
                      width: '14px', height: '14px', borderRadius: '50%',
                      background: ts.color, border: `2px solid ${Tauth.color.bg.card}`,
                      cursor: 'crosshair',
                      boxShadow: `0 0 0 2px ${ts.color}44`,
                    }} />
                </div>
              );
            })}

            {/* Palette drag ghost */}
            {drag?.kind === 'palette' && (() => {
              const ts = typeStyle(drag.nodeType);
              return (
                <div style={{
                  position: 'absolute', left: `${drag.ghostX}px`, top: `${drag.ghostY}px`,
                  width: `${NODE_W}px`, height: `${NODE_H}px`,
                  background: Tauth.color.bg.card,
                  border: `2px dashed ${ts.color}`, borderLeft: `5px solid ${ts.color}`,
                  borderRadius: '8px', padding: '10px 14px',
                  opacity: 0.7, pointerEvents: 'none',
                  display: 'flex', flexDirection: 'column', justifyContent: 'center',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                    <span style={{ color: ts.color, fontWeight: 700, fontSize: '13px' }}>{ts.icon}</span>
                    <span style={{ fontSize: '9px', fontWeight: 700, color: ts.color, textTransform: 'uppercase', letterSpacing: '0.08em' }}>{ts.label}</span>
                  </div>
                  <div style={{ fontSize: '11px', color: Tauth.color.text.tertiary, marginTop: '4px' }}>Drop here</div>
                </div>
              );
            })()}
          </div>
        </div>

        {/* ── RIGHT INSPECTOR ──────────────────────────────────────────── */}
        <div style={{ ...au.card, height: CANVAS_H + 50, overflow: 'auto' }}>
          <div style={{ ...au.cardH, padding: '12px 18px' }}>Step properties</div>
          {sel ? (
            <div style={{ padding: '16px 18px' }}>
              <div style={{ marginBottom: '14px' }}>
                <ABadge color={selStyle.color} bg={selStyle.bg}>{selStyle.icon} {selStyle.label}</ABadge>
              </div>
              <div style={{ fontSize: '10px', color: Tauth.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', marginBottom: '6px', letterSpacing: '0.08em' }}>Name</div>
              <input value={sel.name}
                onChange={(e) => setSteps(prev => prev.map(x => x.id === sel.id ? { ...x, name: e.target.value } : x))}
                style={{ width: '100%', padding: '8px 12px', fontSize: '13px', border: `1px solid ${Tauth.color.border.light}`, borderRadius: '6px', background: Tauth.color.bg.card, color: Tauth.color.text.primary, fontWeight: 600, marginBottom: '14px', fontFamily: Tauth.font.family, boxSizing: 'border-box' }} />

              <div style={{ fontSize: '10px', color: Tauth.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', marginBottom: '6px', letterSpacing: '0.08em' }}>Node ID</div>
              <input value={sel.id} readOnly style={{ width: '100%', padding: '8px 12px', fontSize: '12px', border: `1px solid ${Tauth.color.border.light}`, borderRadius: '6px', background: Tauth.color.bg.secondary, color: au.fuchsia, fontFamily: Tauth.font.mono, fontWeight: 700, marginBottom: '14px', boxSizing: 'border-box' }} />

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '14px' }}>
                <div>
                  <div style={{ fontSize: '10px', color: Tauth.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', marginBottom: '6px', letterSpacing: '0.08em' }}>X</div>
                  <input value={Math.round(sel.x)} readOnly style={{ width: '100%', padding: '6px 10px', fontSize: '12px', border: `1px solid ${Tauth.color.border.light}`, borderRadius: '5px', background: Tauth.color.bg.secondary, fontFamily: Tauth.font.mono, boxSizing: 'border-box' }} />
                </div>
                <div>
                  <div style={{ fontSize: '10px', color: Tauth.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', marginBottom: '6px', letterSpacing: '0.08em' }}>Y</div>
                  <input value={Math.round(sel.y)} readOnly style={{ width: '100%', padding: '6px 10px', fontSize: '12px', border: `1px solid ${Tauth.color.border.light}`, borderRadius: '5px', background: Tauth.color.bg.secondary, fontFamily: Tauth.font.mono, boxSizing: 'border-box' }} />
                </div>
              </div>

              {sel.script && (<><div style={{ fontSize: '10px', color: Tauth.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', marginBottom: '6px', letterSpacing: '0.08em' }}>Script</div><input value={sel.script} readOnly style={{ width: '100%', padding: '8px 12px', fontSize: '12px', border: `1px solid ${Tauth.color.border.light}`, borderRadius: '6px', background: Tauth.color.bg.secondary, color: au.lime, fontFamily: Tauth.font.mono, fontWeight: 700, marginBottom: '14px', boxSizing: 'border-box' }} /></>)}
              {sel.assignee && (<><div style={{ fontSize: '10px', color: Tauth.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', marginBottom: '6px', letterSpacing: '0.08em' }}>Assignee</div><input value={sel.assignee} readOnly style={{ width: '100%', padding: '8px 12px', fontSize: '12px', border: `1px solid ${Tauth.color.border.light}`, borderRadius: '6px', background: Tauth.color.bg.secondary, color: Tauth.color.text.primary, marginBottom: '14px', boxSizing: 'border-box' }} /></>)}
              {sel.role && (<><div style={{ fontSize: '10px', color: Tauth.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', marginBottom: '6px', letterSpacing: '0.08em' }}>Role</div><input value={sel.role} readOnly style={{ width: '100%', padding: '8px 12px', fontSize: '12px', border: `1px solid ${Tauth.color.border.light}`, borderRadius: '6px', background: Tauth.color.bg.secondary, color: Tauth.color.text.primary, marginBottom: '14px', boxSizing: 'border-box' }} /></>)}
              {sel.integration && (<><div style={{ fontSize: '10px', color: Tauth.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', marginBottom: '6px', letterSpacing: '0.08em' }}>Integration</div><input value={sel.integration} readOnly style={{ width: '100%', padding: '8px 12px', fontSize: '12px', border: `1px solid ${Tauth.color.border.light}`, borderRadius: '6px', background: Tauth.color.bg.secondary, color: au.teal, fontWeight: 700, marginBottom: '14px', boxSizing: 'border-box' }} /></>)}
              {sel.cond && (<><div style={{ fontSize: '10px', color: Tauth.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', marginBottom: '6px', letterSpacing: '0.08em' }}>Condition</div><input value={sel.cond} readOnly style={{ width: '100%', padding: '8px 12px', fontSize: '12px', border: `1px solid ${Tauth.color.border.light}`, borderRadius: '6px', background: Tauth.color.bg.secondary, color: au.violet, fontFamily: Tauth.font.mono, fontWeight: 700, marginBottom: '14px', boxSizing: 'border-box' }} /></>)}

              <div style={{ fontSize: '10px', color: Tauth.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', marginBottom: '6px', letterSpacing: '0.08em' }}>Notes</div>
              <div style={{ fontSize: '12px', color: Tauth.color.text.secondary, lineHeight: 1.6, padding: '10px 12px', background: Tauth.color.bg.secondary, borderRadius: '6px', border: `1px solid ${Tauth.color.border.light}`, marginBottom: '14px' }}>{sel.note || '—'}</div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', paddingTop: '10px', borderTop: `1px solid ${Tauth.color.border.light}` }}>
                <button style={{ ...au.btnSecondary, color: au.crimson, borderColor: `${au.crimson}44` }} onClick={deleteSelected}>Delete node</button>
              </div>
            </div>
          ) : (
            <div style={{ padding: '40px 18px', textAlign: 'center', fontSize: '12px', color: Tauth.color.text.tertiary }}>
              <div style={{ fontSize: '32px', color: Tauth.color.border.medium, marginBottom: '10px' }}>◇</div>
              Click a node to inspect.<br />Drag from palette to add new nodes.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── SCHEMAS ──────────────────────────────────────────────────────────────────
function AuthSchemas({ data }) {
  const au = window.__au;
  const rows = data.eventSchemas;
  const withBreaking = rows.filter(r => r.breaking).length;

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.cobalt}`, background: au.cobaltBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.cobalt, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Event schema registry — {rows.length} events · {withBreaking} with breaking changes</div>
          <div style={{ fontSize: '11px', color: Tauth.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Strongly-typed event contracts with version history, consumer impact, deprecations, and payload validation. Breaking-change detection gates publish.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Schemas</span><span style={au.statValue}>{rows.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Breaking changes</span><span style={{ ...au.statValue, color: withBreaking > 0 ? au.amber : au.emerald }}>{withBreaking}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Total consumers</span><span style={au.statValue}>{rows.reduce((s, r) => s + r.consumers, 0)}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Deprecated fields</span><span style={{ ...au.statValue, color: au.amber }}>{rows.reduce((s, r) => s + r.deprecated, 0)}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Registry</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={au.btnSecondary}>Validate payload</button>
            <button style={au.btnPrimary}>+ Register event</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>ID</th>
              <th style={au.th}>Event</th>
              <th style={au.th}>Version</th>
              <th style={au.th}>Owner</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Consumers</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Fields</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Deprecated</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Tests</th>
              <th style={au.th}>Breaking</th>
              <th style={au.th}>Last changed</th>
              <th style={au.th}>Valid</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(s => (
              <tr key={s.id}>
                <td style={{ ...au.td, fontFamily: Tauth.font.mono, fontWeight: 700, color: au.cobalt }}>{s.id}</td>
                <td style={{ ...au.td, fontFamily: Tauth.font.mono, color: Tauth.color.text.primary, fontWeight: 600 }}>{s.event}</td>
                <td style={{ ...au.td, fontFamily: Tauth.font.mono, fontWeight: 700, color: au.fuchsia }}>{s.version}</td>
                <td style={{ ...au.td, color: Tauth.color.text.secondary, fontSize: '11px' }}>{s.owner}</td>
                <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauth.font.mono, fontWeight: 700 }}>{s.consumers}</td>
                <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauth.font.mono }}>{s.fields}</td>
                <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauth.font.mono, color: s.deprecated > 0 ? au.amber : Tauth.color.text.tertiary }}>{s.deprecated}</td>
                <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauth.font.mono, color: au.emerald }}>{s.tests}</td>
                <td style={au.td}>{s.breaking
                  ? <ABadge color={au.crimson} bg={au.crimsonBg}>! breaking</ABadge>
                  : <ABadge color={au.emerald} bg={au.emeraldBg}>safe</ABadge>}</td>
                <td style={{ ...au.td, fontFamily: Tauth.font.mono, fontSize: '11px', color: Tauth.color.text.tertiary }}>{s.lastChanged}</td>
                <td style={au.td}>{s.valid
                  ? <ABadge color={au.emerald} bg={au.emeraldBg}><Icons.Check size={11}/></ABadge>
                  : <ABadge color={au.crimson} bg={au.crimsonBg}><Icons.X size={11}/></ABadge>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── VARIANTS (A/B) ───────────────────────────────────────────────────────────
function AuthVariants({ data }) {
  const au = window.__au;
  const rows = data.variants;

  const stStyle = (s) => {
    if (s === 'Canary')   return { bg: au.amberBg, color: au.amber };
    if (s === 'Promoted') return { bg: au.emeraldBg, color: au.emerald };
    if (s === 'Ended')    return { bg: Tauth.color.bg.secondary, color: Tauth.color.text.tertiary };
    return { bg: Tauth.color.bg.secondary, color: Tauth.color.text.secondary };
  };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.violet}`, background: au.violetBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.violet, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ A/B variants — canary rollouts for workflow changes</div>
          <div style={{ fontSize: '11px', color: Tauth.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Fork workflows with variable rebinding. Route a % of runs to canary. Compare p95 + success side-by-side. Promote or reject after statistical significance.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Active experiments</span><span style={{ ...au.statValue, color: au.amber }}>{rows.filter(r => r.status === 'Canary').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Promoted (YTD)</span><span style={{ ...au.statValue, color: au.emerald }}>{rows.filter(r => r.status === 'Promoted').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Rejected (YTD)</span><span style={{ ...au.statValue, color: au.crimson }}>{rows.filter(r => r.recommendation === 'Reject').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Runs allocated</span><span style={au.statValue}>{rows.reduce((s, r) => s + r.runsVariant, 0)}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '14px' }}>
        {rows.map(v => {
          const ss = stStyle(v.status);
          const deltaNum = parseFloat(v.delta);
          const deltaColor = isNaN(deltaNum) ? Tauth.color.text.tertiary : deltaNum > 0 ? au.emerald : au.crimson;
          return (
            <div key={v.id} style={{ ...au.card, marginBottom: 0, borderLeft: `3px solid ${ss.color}` }}>
              <div style={{ ...au.cardH, background: ss.bg }}>
                <span><b style={{ fontFamily: Tauth.font.mono, color: au.violet }}>{v.id}</b> · {v.base} vs {v.variant}</span>
                <ABadge color={ss.color} bg="rgba(255,255,255,0.7)">{v.status}</ABadge>
              </div>
              <div style={{ padding: '14px 16px' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '12px' }}>
                  <div style={{ padding: '10px', background: Tauth.color.bg.secondary, borderRadius: '5px', border: `1px solid ${Tauth.color.border.light}` }}>
                    <div style={{ fontSize: '9px', fontWeight: 700, color: Tauth.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>BASELINE</div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: Tauth.color.text.primary }}>{v.base}</div>
                    <div style={{ marginTop: '8px', fontSize: '11px', lineHeight: 1.6 }}>
                      <div><span style={{ color: Tauth.color.text.tertiary }}>Runs:</span> <b style={{ fontFamily: Tauth.font.mono }}>{v.runsBase}</b></div>
                      <div><span style={{ color: Tauth.color.text.tertiary }}>p95:</span> <b style={{ fontFamily: Tauth.font.mono }}>{v.p95Base}</b></div>
                      <div><span style={{ color: Tauth.color.text.tertiary }}>Success:</span> <b style={{ fontFamily: Tauth.font.mono }}>{v.successBase}%</b></div>
                    </div>
                  </div>
                  <div style={{ padding: '10px', background: `${au.violet}0f`, borderRadius: '5px', border: `1px solid ${au.violet}33` }}>
                    <div style={{ fontSize: '9px', fontWeight: 700, color: au.violet, textTransform: 'uppercase', marginBottom: '4px' }}>CANARY ({v.allocationPct}%)</div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: au.violet }}>{v.variant}</div>
                    <div style={{ marginTop: '8px', fontSize: '11px', lineHeight: 1.6 }}>
                      <div><span style={{ color: Tauth.color.text.tertiary }}>Runs:</span> <b style={{ fontFamily: Tauth.font.mono }}>{v.runsVariant}</b></div>
                      <div><span style={{ color: Tauth.color.text.tertiary }}>p95:</span> <b style={{ fontFamily: Tauth.font.mono }}>{v.p95Variant}</b></div>
                      <div><span style={{ color: Tauth.color.text.tertiary }}>Success:</span> <b style={{ fontFamily: Tauth.font.mono }}>{v.successVariant}%</b></div>
                    </div>
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 12px', background: Tauth.color.bg.secondary, borderRadius: '5px', border: `1px solid ${Tauth.color.border.light}` }}>
                  <div>
                    <span style={{ fontSize: '10px', color: Tauth.color.text.tertiary, textTransform: 'uppercase', fontWeight: 700, marginRight: '6px' }}>Δ Success:</span>
                    <span style={{ fontFamily: Tauth.font.mono, fontSize: '14px', fontWeight: 700, color: deltaColor }}>{v.delta}</span>
                  </div>
                  <div>
                    <span style={{ fontSize: '10px', color: Tauth.color.text.tertiary, textTransform: 'uppercase', fontWeight: 700, marginRight: '6px' }}>Recommend:</span>
                    <ABadge color={v.recommendation === 'Promote' ? au.emerald : v.recommendation === 'Reject' ? au.crimson : au.amber}
                            bg={v.recommendation === 'Promote' ? au.emeraldBg : v.recommendation === 'Reject' ? au.crimsonBg : au.amberBg}>
                      {v.recommendation}
                    </ABadge>
                  </div>
                </div>
                {v.status === 'Canary' && (
                  <div style={{ display: 'flex', gap: '6px', marginTop: '10px' }}>
                    <button style={{ ...au.btnPrimary, background: au.emerald }}>Promote variant</button>
                    <button style={au.btnSecondary}>Increase allocation</button>
                    <button style={{ ...au.btnSecondary, color: au.crimson }}>Abort</button>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── MARKETPLACE ──────────────────────────────────────────────────────────────
function AuthMarketplace({ data }) {
  const au = window.__au;
  const rows = data.marketplaceTemplates;
  const totalInstalls = rows.reduce((s, r) => s + r.installs, 0);
  const avgRating = (rows.reduce((s, r) => s + r.rating * r.ratings, 0) / Math.max(1, rows.reduce((s, r) => s + r.ratings, 0))).toFixed(2);

  const stars = (n) => {
    const full = Math.floor(n);
    const half = n - full >= 0.5;
    return '●'.repeat(full) + (half ? '⯨' : '') + '○'.repeat(5 - full - (half ? 1 : 0));
  };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.emerald}`, background: au.emeraldBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.emerald, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Template marketplace — {rows.length} templates · {totalInstalls} installs · avg * {avgRating}</div>
          <div style={{ fontSize: '11px', color: Tauth.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Publish, discover, and fork workflow templates across teams. Ratings, version pinning, tenant scoping, and certification tags.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Published</span><span style={au.statValue}>{rows.filter(r => r.status === 'Published').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Drafts</span><span style={au.statValue}>{rows.filter(r => r.status === 'Draft').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Total installs</span><span style={{ ...au.statValue, color: au.emerald }}>{totalInstalls}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Avg rating</span><span style={{ ...au.statValue, color: au.amber }}>* {avgRating}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px' }}>
        {rows.map(t => (
          <div key={t.id} style={{ ...au.card, marginBottom: 0, display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: '12px 14px', borderBottom: `1px solid ${Tauth.color.border.light}` }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
                <span style={{ fontFamily: Tauth.font.mono, fontWeight: 700, color: au.fuchsia, fontSize: '10px' }}>{t.id}</span>
                {t.certified && <ABadge color={au.emerald} bg={au.emeraldBg}>ok certified</ABadge>}
                {t.status === 'Draft' && <ABadge color={Tauth.color.text.tertiary} bg={Tauth.color.bg.secondary}>draft</ABadge>}
              </div>
              <div style={{ fontSize: '13px', fontWeight: 700, color: Tauth.color.text.primary, marginBottom: '4px', lineHeight: 1.3 }}>{t.name}</div>
              <div style={{ fontSize: '10px', color: Tauth.color.text.tertiary }}>{t.publisher} · v{t.version}</div>
            </div>
            <div style={{ padding: '10px 14px', flex: 1 }}>
              <div style={{ fontSize: '11px', color: au.amber, fontWeight: 700, marginBottom: '4px' }}>{stars(t.rating)} <span style={{ color: Tauth.color.text.tertiary, fontWeight: 400 }}>({t.ratings})</span></div>
              <div style={{ fontSize: '11px', color: Tauth.color.text.secondary, marginBottom: '8px' }}><b>{t.installs}</b> installs</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px' }}>
                {t.tenants.map(ten => <ABadge key={ten} color={au.cobalt} bg={au.cobaltBg}>{ten}</ABadge>)}
              </div>
            </div>
            <div style={{ padding: '10px 14px', borderTop: `1px solid ${Tauth.color.border.light}`, display: 'flex', gap: '6px' }}>
              <button style={{ ...au.btnPrimary, flex: 1, background: au.fuchsia }}>Install</button>
              <button style={au.btnSecondary}>Fork</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── ROOT ─────────────────────────────────────────────────────────────────────
function AutoAuthoring({ data }) {
  const au = window.__au;
  const Thelp = window.ArbiterTokens;
  const [activeGroup, setActiveGroup] = useAuthState('canvas');
  const [subByGroup, setSubByGroup] = useAuthState(VE_DEFAULT_SUB);

  const group = VE_GROUPS.find(g => g.id === activeGroup);
  const activeSub = subByGroup[activeGroup];

  const groupAccent = {
    canvas: au.fuchsia, data: au.amber, ai: au.lime,
    release: au.emerald, obs: au.crimson, ext: au.teal,
  }[activeGroup] || au.lime;

  const renderSub = () => {
    switch (activeSub) {
      // Legacy views
      case 'designer':    return <AuthDesigner    data={data} />;
      case 'schemas':     return <AuthSchemas     data={data} />;
      case 'variants':    return <AuthVariants    data={data} />;
      case 'marketplace': return <AuthMarketplace data={data} />;
      // VE1-VE20
      case 've1':  return <window.VE1ValidationGutter />;
      case 've2':  return <window.VE2VersionHistory />;
      case 've3':  return <window.VE3Subflows />;
      case 've4':  return <window.VE4Primitives />;
      case 've5':  return <window.VE5Swimlanes />;
      case 've6':  return <window.VE6VariableGraph />;
      case 've7':  return <window.VE7SchemaBinding />;
      case 've8':  return <window.VE8TestHarness />;
      case 've9':  return <window.VE9Copilot />;
      case 've10': return <window.VE10Optimizer />;
      case 've11': return <window.VE11ComplianceOverlay />;
      case 've12': return <window.VE12Collaboration />;
      case 've13': return <window.VE13ApprovalPipeline />;
      case 've14': return <window.VE14Canary />;
      case 've15': return <window.VE15Variants />;
      case 've16': return <window.VE16Heatmap />;
      case 've17': return <window.VE17IncidentReplay />;
      case 've18': return <window.VE18CostLedger />;
      case 've19': return <window.VE19MarketplaceDropIns />;
      case 've20': return <window.VE20KeyboardA11y />;
      default:     return <AuthDesigner data={data} />;
    }
  };

  // Primary-tab style aligned with AutoTokens.tab convention
  const primaryTabStyle = (active) => ({
    padding: '10px 16px', fontSize: '12px', fontWeight: active ? 700 : 500,
    color: active ? groupAccent : Thelp.color.text.tertiary,
    cursor: 'pointer', border: 'none', background: 'none',
    borderBottom: active ? `2px solid ${groupAccent}` : '2px solid transparent',
    fontFamily: Thelp.font.family, transition: 'all 0.15s', marginBottom: '-1px', whiteSpace: 'nowrap',
  });

  // Pill sub-tab style
  const subTabStyle = (active) => ({
    padding: '6px 12px', fontSize: '11px', fontWeight: active ? 700 : 500,
    color: active ? '#fff' : Thelp.color.text.secondary,
    background: active ? groupAccent : 'transparent',
    border: `1px solid ${active ? groupAccent : Thelp.color.border.light}`,
    borderRadius: '6px', cursor: 'pointer',
    letterSpacing: '0.02em', whiteSpace: 'nowrap',
    fontFamily: Thelp.font.family,
  });

  return (
    <div>
      {/* PRIMARY GROUP TABS */}
      <div style={{ display: 'flex', gap: '0', borderBottom: `1px solid ${Thelp.color.border.light}`, background: Thelp.color.bg.card, padding: '0 0', marginBottom: '14px', overflowX: 'auto' }}>
        {VE_GROUPS.map(g => (
          <button key={g.id} onClick={() => setActiveGroup(g.id)} style={primaryTabStyle(activeGroup === g.id)}>
            {g.label}
          </button>
        ))}
      </div>

      {/* PILL SUB-TABS */}
      {group && (
        <div style={{ display: 'flex', gap: '6px', marginBottom: '14px', flexWrap: 'wrap', padding: '8px 10px', background: Thelp.color.bg.secondary, border: `1px solid ${Thelp.color.border.light}`, borderRadius: '6px' }}>
          {group.subs.map(s => (
            <button key={s.id} onClick={() => setSubByGroup({ ...subByGroup, [group.id]: s.id })}
              style={subTabStyle(activeSub === s.id)}>
              {s.label}
            </button>
          ))}
        </div>
      )}

      {/* CONTENT */}
      {renderSub()}
    </div>
  );
}

window.AutoAuthoring     = AutoAuthoring;
window.AuthDesigner      = AuthDesigner;
window.AuthSchemas       = AuthSchemas;
window.AuthVariants      = AuthVariants;
window.AuthMarketplace   = AuthMarketplace;
