// =========================================================
// DESIGN WORKSPACE V2 — Phase 14
// -----------------------------------------------------------------
// Depth cap: Project → Design → Design Item Detail. Three peer
// views (Overview, Designs, Library) sit under a single segmented
// control — never tabs inside tabs.
//
// All items come from pdata.design.{screens, flows, prototypes},
// which remain the canonical source of truth. This file only
// filters and reads. Every card carries a canonical RelatedTo
// chip. Owner + reviewer avatars use the same portrait lookup as
// the rest of the app, so a person keeps identity across screens.
// =========================================================

// -----------------------------------------------------------------
// Small helpers
// -----------------------------------------------------------------

const DV_STATE = {
  'approved':    { tone: 'green', label: 'Approved',    review: 'approve' },
  'in-review':   { tone: 'blue',  label: 'In review',   review: 'review'  },
  'in-progress': { tone: 'gray',  label: 'In progress', review: 'draft'   },
  'planned':     { tone: 'gray',  label: 'Planned',     review: 'draft'   },
  'blocked':     { tone: 'red',   label: 'Blocked',     review: 'blocked' },
  'ready':       { tone: 'green', label: 'Ready',       review: 'approve' },
  'done':        { tone: 'green', label: 'Done',        review: 'approve' },
};

const DV_TYPE = {
  'screen':    { label: 'Screen',    icon: 'palette' },
  'flow':      { label: 'Flow',      icon: 'route'   },
  'prototype': { label: 'Prototype', icon: 'play'    },
  'component': { label: 'Component', icon: 'grid'    },
};

// Pull everything canonical into one list, tagged with its type.
function dvAllItems(pdata) {
  const d = pdata.design || {};
  const screens    = (d.screens    || []).map(s => ({ ...s, _t: 'screen'    }));
  const flows      = (d.flows      || []).map(f => ({ ...f, _t: 'flow'      }));
  const prototypes = (d.prototypes || []).map(p => ({ ...p, _t: 'prototype' }));
  return [...screens, ...flows, ...prototypes];
}

function dvStateChip(state, size = 'sm') {
  const s = DV_STATE[state];
  if (!s) return null;
  return <Label tone={s.tone} dot size={size}>{s.label}</Label>;
}

function dvPortraitFor(name, pdata) {
  const key = (name || '').toLowerCase();
  const p = (pdata.people || {})[key];
  return p?.portrait || null;
}

// -----------------------------------------------------------------
// Realistic screen mocks — production-oriented, not schematic.
// Each accepts a size prop for gallery/detail contexts.
// -----------------------------------------------------------------

function DVMock({ kind, size = 'md' }) {
  // Base viewBox so all mocks scale identically inside their frame.
  const W = 320, H = 200;
  const common = { viewBox: `0 0 ${W} ${H}`, width: '100%', height: '100%', preserveAspectRatio: 'xMidYMid slice' };

  // --- brief-editor: 3-column editorial reader (the flagship) ---
  if (kind === 'brief-editor') {
    return (
      <svg {...common}>
        {/* Sidebar */}
        <rect x="0" y="0" width="48" height={H} fill="#F4F3EF" />
        {[14, 40, 66, 92, 118, 144].map((y, i) => (
          <rect key={i} x="10" y={y} width="28" height="4" rx="1.5"
                fill={i === 2 ? 'rgba(42,133,255,0.55)' : 'rgba(16,16,16,0.14)'} />
        ))}
        {/* Article surface */}
        <rect x="56" y="8" width="192" height="184" rx="10" fill="#FDFDFD" stroke="rgba(16,16,16,0.06)" />
        {/* Article header */}
        <rect x="66" y="18" width="90" height="6"  rx="2" fill="rgba(16,16,16,0.28)" />
        <rect x="66" y="30" width="60" height="4"  rx="1.5" fill="rgba(16,16,16,0.14)" />
        {/* Lead paragraph */}
        <rect x="66" y="46" width="172" height="4" rx="1.5" fill="rgba(16,16,16,0.20)" />
        <rect x="66" y="54" width="160" height="4" rx="1.5" fill="rgba(16,16,16,0.20)" />
        <rect x="66" y="62" width="130" height="4" rx="1.5" fill="rgba(16,16,16,0.20)" />
        {/* Numbered problems block */}
        {[80, 100, 120].map((y, i) => (
          <g key={i}>
            <rect x="66" y={y} width="6"  height="12" rx="1.5" fill="rgba(42,133,255,0.55)" />
            <rect x="78" y={y+2} width="80" height="4"  rx="1.5" fill="rgba(16,16,16,0.24)" />
            <rect x="78" y={y+8} width="140" height="3" rx="1.5" fill="rgba(16,16,16,0.10)" />
          </g>
        ))}
        {/* Business appendix chip row */}
        {[0,1,2,3].map(i => (
          <rect key={i} x={66 + i*38} y={148} width="34" height="20" rx="4"
                fill={['#B1E5FC','#B5E4CA','#FFBC99','#CABDFF'][i]} opacity="0.35" />
        ))}
        {/* Rail */}
        <rect x="256" y="8" width="60" height="184" rx="10" fill="#FBFAF6" stroke="rgba(16,16,16,0.05)" />
        <rect x="262" y="16" width="48" height="42" rx="6" fill="#FDFDFD" stroke="rgba(42,133,255,0.35)" />
        <rect x="266" y="22" width="12" height="3"  rx="1.5" fill="rgba(42,133,255,0.7)" />
        <rect x="266" y="30" width="34" height="5"  rx="1.5" fill="rgba(16,16,16,0.28)" />
        <rect x="266" y="40" width="24" height="3"  rx="1.5" fill="rgba(16,16,16,0.14)" />
        <rect x="266" y="46" width="34" height="8"  rx="4"   fill="rgba(42,133,255,0.15)" />
        {[66, 88, 110, 132, 154, 176].map((y, i) => (
          <g key={i}>
            <rect x="262" y={y} width="48" height="14" rx="4" fill="#FDFDFD" stroke="rgba(16,16,16,0.05)" />
            <rect x="266" y={y+4} width="20" height="3" rx="1.5" fill="rgba(16,16,16,0.24)" />
            <rect x="266" y={y+9} width="34" height="2" rx="1"   fill="rgba(16,16,16,0.10)" />
          </g>
        ))}
      </svg>
    );
  }

  // --- brief-section: focused edit view ---
  if (kind === 'brief-section') {
    return (
      <svg {...common}>
        <rect x="0" y="0" width={W} height={H} fill="#FDFDFD" />
        <rect x="14" y="12" width="120" height="6" rx="2" fill="rgba(16,16,16,0.30)" />
        <rect x="14" y="24" width="80"  height="4" rx="1.5" fill="rgba(16,16,16,0.12)" />
        <rect x="14" y="42" width={W-28} height="120" rx="10" fill="#FBFAF6" stroke="rgba(16,16,16,0.06)" />
        {[52,64,76,88,100,112,124,136,148].map((y, i) => (
          <rect key={i} x="24" y={y} width={i%3===0 ? 260 : (i%3===1 ? 240 : 200)} height="3" rx="1.5"
                fill={i===0 ? 'rgba(42,133,255,0.6)' : 'rgba(16,16,16,0.14)'} />
        ))}
        <rect x="14" y="170" width="90"  height="20" rx="6" fill="#2A85FF" opacity="0.9" />
        <rect x="24" y="177" width="70"  height="6"  rx="2" fill="rgba(255,255,255,0.85)" />
        <rect x="110" y="170" width="80" height="20" rx="6" fill="#FDFDFD" stroke="rgba(16,16,16,0.10)" />
        <rect x="120" y="177" width="60" height="6"  rx="2" fill="rgba(16,16,16,0.30)" />
      </svg>
    );
  }

  // --- decisions-inbox: list of decisions awaiting approval ---
  if (kind === 'decisions-inbox') {
    return (
      <svg {...common}>
        <rect x="0" y="0" width={W} height={H} fill="#FDFDFD" />
        <rect x="14" y="12" width="120" height="6" rx="2" fill="rgba(16,16,16,0.30)" />
        <rect x="14" y="24" width="70"  height="4" rx="1.5" fill="rgba(16,16,16,0.12)" />
        <rect x="220" y="14" width="86" height="14" rx="7" fill="rgba(42,133,255,0.10)" stroke="rgba(42,133,255,0.35)" />
        <rect x="228" y="19" width="70" height="4"  rx="1.5" fill="rgba(42,133,255,0.7)" />
        {[46, 78, 110, 142, 174].map((y, i) => (
          <g key={i}>
            <rect x="14" y={y} width={W-28} height="26" rx="8" fill="#FDFDFD" stroke="rgba(16,16,16,0.08)" />
            <rect x="22" y={y+6}  width="6"   height="14" rx="2"
                  fill={i===0 ? '#EF9D0E' : (i===4 ? '#00A656' : 'rgba(16,16,16,0.14)')} />
            <rect x="34" y={y+6}  width="150" height="5" rx="1.5" fill="rgba(16,16,16,0.28)" />
            <rect x="34" y={y+14} width="120" height="3" rx="1.5" fill="rgba(16,16,16,0.12)" />
            <circle cx="220" cy={y+13} r="6" fill={['#B5E4CA','#B1E5FC','#FFBC99','#CABDFF','#FFD88D'][i]} />
            <circle cx="232" cy={y+13} r="6" fill="rgba(16,16,16,0.08)" />
            <rect x="252" y={y+9} width="46" height="8" rx="4"
                  fill={i===4 ? 'rgba(0,166,86,0.15)' : (i===0 ? 'rgba(239,157,14,0.15)' : 'rgba(16,16,16,0.06)')} />
          </g>
        ))}
      </svg>
    );
  }

  // --- search-overlay: modal with query + results ---
  if (kind === 'search-overlay') {
    return (
      <svg {...common}>
        <rect x="0" y="0" width={W} height={H} fill="#EEEDE9" />
        <rect x="34" y="20" width={W-68} height={H-40} rx="14" fill="#FDFDFD" stroke="rgba(16,16,16,0.10)" />
        <rect x="46" y="34" width={W-92} height="24" rx="8" fill="#F1F1F1" />
        <circle cx="60" cy="46" r="4" fill="none" stroke="rgba(16,16,16,0.4)" strokeWidth="1.5" />
        <line x1="63" y1="49" x2="66" y2="52" stroke="rgba(16,16,16,0.4)" strokeWidth="1.5" />
        <rect x="72" y="43" width="80" height="4" rx="1.5" fill="rgba(16,16,16,0.28)" />
        <rect x="46" y="70" width="30" height="4" rx="1.5" fill="rgba(16,16,16,0.35)" />
        {[80, 100, 120, 140, 160].map((y, i) => (
          <g key={i}>
            <rect x="46" y={y} width={W-92} height="14" rx="4" fill={i===1 ? 'rgba(42,133,255,0.10)' : 'transparent'} />
            <circle cx="56" cy={y+7} r="4" fill="rgba(16,16,16,0.10)" />
            <rect x="66" y={y+3} width="100" height="4" rx="1.5" fill="rgba(16,16,16,0.28)" />
            <rect x="66" y={y+9} width="70"  height="3" rx="1.5" fill="rgba(16,16,16,0.12)" />
            <rect x="230" y={y+5} width="46" height="4" rx="1.5" fill="rgba(16,16,16,0.10)" />
          </g>
        ))}
      </svg>
    );
  }

  // --- command-palette: ⌘K style overlay ---
  if (kind === 'command-palette') {
    return (
      <svg {...common}>
        <rect x="0" y="0" width={W} height={H} fill="#EEEDE9" />
        <rect x="50" y="34" width={W-100} height="128" rx="12" fill="#141414" />
        <rect x="64" y="46" width={W-128} height="20" rx="6" fill="rgba(255,255,255,0.08)" />
        <rect x="76" y="53" width="100" height="4" rx="1.5" fill="rgba(255,255,255,0.85)" />
        {[76, 96, 116, 136].map((y, i) => (
          <g key={i}>
            <rect x="64" y={y} width={W-128} height="14" rx="4" fill={i===0 ? 'rgba(255,255,255,0.10)' : 'transparent'} />
            <rect x="72" y={y+4} width="60"  height="4" rx="1.5" fill="rgba(255,255,255,0.85)" />
            <rect x="140" y={y+4} width="90" height="3" rx="1.5" fill="rgba(255,255,255,0.35)" />
            <rect x="240" y={y+4} width="24" height="6" rx="2" fill="rgba(255,255,255,0.14)" />
          </g>
        ))}
      </svg>
    );
  }

  // --- settings: nav + form list ---
  if (kind === 'settings') {
    return (
      <svg {...common}>
        <rect x="0" y="0" width="80" height={H} fill="#F4F3EF" />
        {[14, 40, 66, 92, 118, 144].map((y, i) => (
          <g key={i}>
            <rect x="10" y={y} width="60" height="20" rx="5" fill={i === 2 ? 'rgba(42,133,255,0.10)' : 'transparent'} />
            <rect x="16" y={y+8} width="40" height="4" rx="1.5" fill={i===2 ? 'rgba(42,133,255,0.7)' : 'rgba(16,16,16,0.28)'} />
          </g>
        ))}
        <rect x="90" y="14" width={W-104} height={H-28} rx="10" fill="#FDFDFD" stroke="rgba(16,16,16,0.05)" />
        <rect x="100" y="24" width="80" height="6" rx="2" fill="rgba(16,16,16,0.30)" />
        {[46, 74, 102, 130, 158].map((y, i) => (
          <g key={i}>
            <rect x="100" y={y} width={W-124} height="20" rx="6" fill="rgba(16,16,16,0.02)" />
            <rect x="108" y={y+8} width="60" height="4" rx="1.5" fill="rgba(16,16,16,0.24)" />
            <rect x="272" y={y+6} width="26" height="8" rx="4" fill={i%2 ? 'rgba(0,166,86,0.30)' : 'rgba(16,16,16,0.15)'} />
            <circle cx={i%2 ? 293 : 279} cy={y+10} r="3" fill="#FDFDFD" />
          </g>
        ))}
      </svg>
    );
  }

  // --- mobile-brief: a phone frame with a brief ---
  if (kind === 'mobile-brief') {
    return (
      <svg {...common}>
        <rect x="0" y="0" width={W} height={H} fill="#EEEDE9" />
        <rect x="112" y="10" width="96" height="180" rx="16" fill="#FDFDFD" stroke="rgba(16,16,16,0.15)" />
        <rect x="128" y="20" width="30" height="3" rx="1.5" fill="rgba(16,16,16,0.14)" />
        <rect x="120" y="34" width="60" height="6" rx="2" fill="rgba(16,16,16,0.30)" />
        <rect x="120" y="44" width="40" height="3" rx="1.5" fill="rgba(16,16,16,0.14)" />
        <rect x="120" y="58" width="80" height="30" rx="6" fill="rgba(202,189,255,0.30)" />
        <rect x="126" y="66" width="50" height="4" rx="1.5" fill="rgba(16,16,16,0.35)" />
        <rect x="126" y="76" width="60" height="3" rx="1.5" fill="rgba(16,16,16,0.20)" />
        {[96, 112, 128, 144, 160].map((y, i) => (
          <g key={i}>
            <rect x="120" y={y} width="80" height="10" rx="3" fill="rgba(16,16,16,0.04)" />
            <rect x="124" y={y+3} width="46" height="3" rx="1.5" fill="rgba(16,16,16,0.24)" />
          </g>
        ))}
        <rect x="120" y="176" width="80" height="10" rx="5" fill="#2A85FF" opacity="0.9" />
      </svg>
    );
  }

  // --- approve-modal: sheet with primary/secondary CTA ---
  if (kind === 'approve-modal') {
    return (
      <svg {...common}>
        <rect x="0" y="0" width={W} height={H} fill="#EEEDE9" />
        <rect x="60" y="30" width={W-120} height={H-60} rx="12" fill="#FDFDFD" stroke="rgba(16,16,16,0.10)" />
        <rect x="72" y="44" width="90" height="6" rx="2" fill="rgba(16,16,16,0.30)" />
        <rect x="72" y="58" width={W-144} height="4" rx="1.5" fill="rgba(16,16,16,0.16)" />
        <rect x="72" y="66" width={W-160} height="4" rx="1.5" fill="rgba(16,16,16,0.16)" />
        <rect x="72" y="82" width={W-144} height="52" rx="8" fill="#FBFAF6" stroke="rgba(0,166,86,0.30)" />
        <rect x="82" y="92" width="50" height="6" rx="2" fill="rgba(0,166,86,0.55)" />
        <rect x="82" y="104" width="140" height="4" rx="1.5" fill="rgba(16,16,16,0.20)" />
        <rect x="82" y="112" width="120" height="4" rx="1.5" fill="rgba(16,16,16,0.20)" />
        <rect x={W-160} y="150" width="70" height="22" rx="6" fill="#FDFDFD" stroke="rgba(16,16,16,0.10)" />
        <rect x={W-152} y="158" width="54" height="6"  rx="2" fill="rgba(16,16,16,0.30)" />
        <rect x={W-84}  y="150" width="70" height="22" rx="6" fill="#00A656" />
        <rect x={W-76}  y="158" width="54" height="6"  rx="2" fill="rgba(255,255,255,0.90)" />
      </svg>
    );
  }

  // --- overview: reused for flow entry/exit steps ---
  if (kind === 'overview') {
    return (
      <svg {...common}>
        <rect x="0" y="0" width={W} height={H} fill="#FDFDFD" />
        <rect x="14" y="12" width="120" height="6" rx="2" fill="rgba(16,16,16,0.28)" />
        <rect x="14" y="24" width="70"  height="4" rx="1.5" fill="rgba(16,16,16,0.12)" />
        <rect x="14" y="40" width={W-28} height="60" rx="8" fill="#FBFAF6" stroke="rgba(16,16,16,0.05)" />
        <rect x="24" y="50" width="60" height="4" rx="1.5" fill="rgba(42,133,255,0.7)" />
        <rect x="24" y="60" width="240" height="3" rx="1.5" fill="rgba(16,16,16,0.14)" />
        <rect x="24" y="68" width="200" height="3" rx="1.5" fill="rgba(16,16,16,0.14)" />
        <rect x="24" y="76" width="160" height="3" rx="1.5" fill="rgba(16,16,16,0.14)" />
        {[112, 138, 164].map((y, i) => (
          <g key={i}>
            <rect x="14" y={y} width="180" height="20" rx="6" fill="#FDFDFD" stroke="rgba(16,16,16,0.06)" />
            <rect x="20" y={y+7} width="60" height="4" rx="1.5" fill="rgba(16,16,16,0.20)" />
            <rect x="204" y={y+6} width={W-218} height="20" rx="6" fill="rgba(16,16,16,0.03)" />
            <rect x="210" y={y+13} width="34" height="4" rx="1.5" fill="rgba(16,16,16,0.14)" />
          </g>
        ))}
      </svg>
    );
  }

  // --- generate: AI-assisted generate panel (calm) ---
  if (kind === 'generate') {
    return (
      <svg {...common}>
        <rect x="0" y="0" width={W} height={H} fill="#FDFDFD" />
        <rect x="14" y="14" width={W-28} height={H-28} rx="10" fill="#FBFAF6" stroke="rgba(16,16,16,0.05)" />
        <rect x="26" y="28" width="80" height="6" rx="2" fill="rgba(16,16,16,0.28)" />
        <rect x="26" y="42" width="150" height="4" rx="1.5" fill="rgba(16,16,16,0.14)" />
        <rect x="26" y="60" width={W-52} height="70" rx="8" fill="#FDFDFD" stroke="rgba(16,16,16,0.06)" />
        {[70, 82, 94, 106].map((y, i) => (
          <rect key={i} x="34" y={y} width={i%2 ? 240 : 260} height="4" rx="1.5" fill="rgba(16,16,16,0.14)" />
        ))}
        <rect x={W-120} y="150" width="98" height="22" rx="6" fill="#141414" />
        <rect x={W-112} y="158" width="70" height="6" rx="2" fill="rgba(255,255,255,0.9)" />
      </svg>
    );
  }

  // fallback — neutral placeholder frame
  return (
    <svg {...common}>
      <rect x="0" y="0" width={W} height={H} fill="#FDFDFD" />
      <rect x="14" y="14" width={W-28} height={H-28} rx="10" fill="#FBFAF6" stroke="rgba(16,16,16,0.05)" />
    </svg>
  );
}

// -----------------------------------------------------------------
// Flow preview — horizontal thumbnails + connectors
// -----------------------------------------------------------------

function DVFlowStrip({ steps, compact = false }) {
  if (!steps || !steps.length) return null;
  return (
    <div className={`dv-flow-strip${compact ? ' dv-flow-strip-compact' : ''}`}>
      {steps.map((step, i) => (
        <React.Fragment key={i}>
          <div className="dv-flow-step">
            <div className="dv-flow-thumb"><DVMock kind={step.kind} /></div>
            <div className="dv-flow-label">
              <span className="dv-flow-num">{String(i + 1).padStart(2, '0')}</span>
              <span>{step.label}</span>
            </div>
          </div>
          {i < steps.length - 1 && (
            <div className="dv-flow-arrow" aria-hidden>
              <svg width="26" height="10" viewBox="0 0 26 10">
                <path d="M0 5 H22 M18 1 L22 5 L18 9" fill="none" stroke="var(--text-tertiary)" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

// -----------------------------------------------------------------
// Gallery card — used across Overview + Designs
// -----------------------------------------------------------------

function DVCard({ item, pdata, onOpen }) {
  const type    = item._t || 'screen';
  const typeMeta = DV_TYPE[type];
  const state   = item.links?.state;
  const ownerPortrait = dvPortraitFor(item.owner, pdata);
  const previewKind = type === 'flow'
    ? (item.steps?.[0]?.kind || 'overview')
    : (type === 'prototype' ? item.previewKind : item.kind);

  return (
    <a
      className="dv-card"
      href={type === 'screen' ? `#/projects/${pdata.id}/design/item/${item.id}` : undefined}
      onClick={(e) => { if (type !== 'screen' && onOpen) { e.preventDefault(); onOpen(item); } }}
    >
      <div className="dv-card-preview">
        <DVMock kind={previewKind} />
        {type === 'flow' && (
          <div className="dv-flow-badge">
            <Icon name="route" size={11} strokeWidth={1.75} />
            <span>{item.steps?.length || 0} steps</span>
          </div>
        )}
        {type === 'prototype' && (
          <div className="dv-flow-badge">
            <Icon name="play" size={11} strokeWidth={1.75} />
            <span>{item.screens || 0} screens</span>
          </div>
        )}
      </div>
      <div className="dv-card-meta">
        <div className="dv-card-title truncate">{item.title}</div>
        <div className="dv-card-row">
          <span className="dv-type-chip">
            <Icon name={typeMeta.icon} size={10} strokeWidth={1.75} />
            <span>{typeMeta.label}</span>
          </span>
          {item.version && <span className="dv-ver">{item.version}</span>}
          {state && dvStateChip(state)}
        </div>
        <div className="dv-card-row dv-card-bottom">
          <div className="dv-owner">
            <Avatar name={item.owner || '?'} size="xs" portrait={ownerPortrait} />
            <span className="truncate">{item.owner || 'Unassigned'}</span>
          </div>
          <span className="dv-updated">{item.updated || ''}</span>
        </div>
        {item.links && <RelatedTo links={item.links} pdata={pdata} compact asSpan />}
      </div>
    </a>
  );
}

// =========================================================
// OVERVIEW
// =========================================================

function DVOverview({ pdata, onNavigate }) {
  const items = dvAllItems(pdata);
  const currentStage = pdata.stages.find(s => s.n === pdata.currentStage);
  const stageDesignItems = items.filter(i => i.links?.stage === pdata.currentStage && i.links?.mission === 'design');
  const requiredItems    = stageDesignItems.filter(i => i.links?.required);
  const requiredDone     = requiredItems.filter(i => ['approved', 'ready', 'done'].includes(i.links?.state)).length;
  const readinessPct     = requiredItems.length ? Math.round((requiredDone / requiredItems.length) * 100) : 100;

  const nextRequired = requiredItems.find(i => !['approved', 'ready', 'done'].includes(i.links?.state));
  const inReview     = stageDesignItems.filter(i => i.links?.state === 'in-review').slice(0, 3);
  const inProgress   = stageDesignItems.filter(i => i.links?.state === 'in-progress');
  const approved     = stageDesignItems.filter(i => i.links?.state === 'approved');

  // Which features (in the current stage) have zero design items?
  const stageFeatures = (pdata.features || []).filter(f => f.stageN === pdata.currentStage);
  const featuresMissing = stageFeatures.filter(f =>
    !items.some(i => i.links?.feature === f.id)
  );

  const recentlyApproved = items
    .filter(i => i.links?.state === 'approved')
    .sort((a, b) => (a.updated || '').localeCompare(b.updated || ''))
    .slice(0, 4);

  return (
    <div className="dv-overview">

      <MGWorkspaceBanner
        kind="design"
        eyebrow="Design · MY GENI"
        title="Every screen carries its context"
        sub="Screens, flows, and prototypes — each connected to the feature, research, and stage that shaped them."
      />

      {/* --- Context / mission strip ------------------------------ */}
      <div className="dv-context">
        <div className="dv-context-left">
          <div className="dv-eyebrow">Current stage</div>
          <div className="dv-context-stage">
            <span className="dv-stage-code mono">S{String(pdata.currentStage).padStart(2, '0')}</span>
            <span className="dv-stage-name">{currentStage?.name}</span>
          </div>
          <div className="dv-context-mission">
            <span>Design Mission ·</span>
            <b>{requiredDone} of {requiredItems.length}</b>
            <span>required Design items complete</span>
          </div>
          {nextRequired && (
            <div className="dv-context-next">
              <span className="dv-eyebrow" style={{ marginRight: 8 }}>Next required</span>
              <a
                href={`#/projects/${pdata.id}/design/item/${nextRequired.id}`}
                className="dv-context-next-link"
                onClick={(e) => { if (nextRequired._t !== 'screen') { e.preventDefault(); onNavigate('designs'); } }}
              >
                {nextRequired.title} <Icon name="chevronRight" size={12} strokeWidth={2} />
              </a>
            </div>
          )}
        </div>

        <div className="dv-context-right">
          <div className="dv-readiness">
            <Ring percent={readinessPct} color="var(--primary-01)" size={72} />
            <div className="dv-readiness-meta">
              <div className="dv-eyebrow">Design readiness</div>
              <div className="dv-readiness-val">
                <span className="mono">{readinessPct}%</span>
                <Label tone={readinessPct === 100 ? 'green' : (readinessPct >= 60 ? 'blue' : 'yellow')} dot size="sm">
                  {readinessPct === 100 ? 'Ready' : (readinessPct >= 60 ? 'On track' : 'Needs work')}
                </Label>
              </div>
              <div className="dv-readiness-sub">for Stage {String(pdata.currentStage).padStart(2, '0')} · {currentStage?.name}</div>
            </div>
          </div>
          <a href={`#/projects/${pdata.id}/plan`} className="btn btn-dark btn-sm">
            <Icon name="stages" size={14} strokeWidth={1.75} />
            <span>View Design Mission</span>
          </a>
        </div>
      </div>

      {/* --- Compact readiness surface: 4 counters + progress bar - */}
      <div className="dv-readiness-strip">
        {[
          { k: 'req',     label: 'Required',   n: requiredItems.length,                     tone: 'neutral' },
          { k: 'approve', label: 'Approved',   n: approved.length,                          tone: 'green'   },
          { k: 'review',  label: 'In review',  n: inReview.length,                          tone: 'blue'    },
          { k: 'progress',label: 'In progress',n: inProgress.length,                        tone: 'gray'    },
          { k: 'missing', label: 'Missing',    n: featuresMissing.length,                   tone: featuresMissing.length ? 'yellow' : 'neutral' },
        ].map(cell => (
          <div className={`dv-rs-cell dv-rs-${cell.tone}`} key={cell.k}>
            <div className="dv-rs-n mono">{cell.n}</div>
            <div className="dv-rs-lbl">{cell.label}</div>
          </div>
        ))}
      </div>

      {/* --- In review now (large tiles) -------------------------- */}
      <div className="ov-section-head" style={{ paddingBottom: 10, marginTop: 20 }}>
        <h3>In review now</h3>
        <a className="link" onClick={() => onNavigate('designs')}>See all designs →</a>
      </div>
      {inReview.length ? (
        <div className="dv-tiles">
          {inReview.map(i => <DVCard item={i} key={i.id} pdata={pdata} />)}
        </div>
      ) : (
        <div className="dv-empty">Nothing waiting for a review right now.</div>
      )}

      {/* --- Recently approved + Features missing design ---------- */}
      <div className="dv-two-col">
        <div>
          <div className="ov-section-head" style={{ paddingBottom: 10 }}>
            <h3>Recently approved</h3>
          </div>
          <div className="dv-strip">
            {recentlyApproved.map(i => (
              <a key={i.id} className="dv-strip-row"
                 href={i._t === 'screen' ? `#/projects/${pdata.id}/design/item/${i.id}` : undefined}
                 onClick={(e) => { if (i._t !== 'screen') { e.preventDefault(); onNavigate('designs'); } }}
              >
                <div className="dv-strip-thumb"><DVMock kind={i.kind || i.previewKind || (i.steps?.[0]?.kind) || 'overview'} /></div>
                <div className="dv-strip-meta">
                  <div className="dv-strip-title truncate">{i.title}</div>
                  <div className="dv-strip-sub">
                    <span>{DV_TYPE[i._t].label}</span>
                    <span className="dot-sep">·</span>
                    <span>{i.version || i.updated}</span>
                    <span className="dot-sep">·</span>
                    <span>{i.owner}</span>
                  </div>
                </div>
                <Label tone="green" dot size="sm">Approved</Label>
              </a>
            ))}
          </div>
        </div>

        <div>
          <div className="ov-section-head" style={{ paddingBottom: 10 }}>
            <h3>Features missing design</h3>
          </div>
          {featuresMissing.length ? (
            <div className="dv-missing">
              {featuresMissing.map(f => (
                <a key={f.id} href={`#/projects/${pdata.id}/features/${f.id}`} className="dv-missing-row">
                  <div className="dv-missing-icon"><Icon name="features" size={14} strokeWidth={1.75} /></div>
                  <div className="dv-missing-body">
                    <div className="dv-missing-title truncate">{f.title}</div>
                    <div className="dv-missing-sub">{f.priority} · {f.owner} · Stage {String(f.stageN).padStart(2,'0')}</div>
                  </div>
                  <Label tone="yellow" size="sm">No design</Label>
                </a>
              ))}
            </div>
          ) : (
            <div className="dv-empty">Every current-stage feature has a design in flight.</div>
          )}
        </div>
      </div>
    </div>
  );
}

// =========================================================
// DESIGNS — visual gallery with filters
// =========================================================

function DVDesigns({ pdata, onOpenFlow }) {
  const items = dvAllItems(pdata);
  const [typeFilter,    setTypeFilter]    = React.useState('all');   // all|screen|flow|prototype
  const [stageFilter,   setStageFilter]   = React.useState('all');
  const [featureFilter, setFeatureFilter] = React.useState('all');
  const [ownerFilter,   setOwnerFilter]   = React.useState('all');
  const [stateFilter,   setStateFilter]   = React.useState('all');

  const stagesInUse = Array.from(new Set(items.map(i => i.links?.stage).filter(Boolean))).sort();
  const featuresInUse = Array.from(new Set(items.map(i => i.links?.feature).filter(Boolean)));
  const owners = Array.from(new Set(items.map(i => i.owner).filter(Boolean)));
  const states = Array.from(new Set(items.map(i => i.links?.state).filter(Boolean)));

  const filtered = items.filter(i => {
    if (typeFilter    !== 'all' && i._t !== typeFilter)                  return false;
    if (stageFilter   !== 'all' && String(i.links?.stage) !== stageFilter) return false;
    if (featureFilter !== 'all' && i.links?.feature !== featureFilter)   return false;
    if (ownerFilter   !== 'all' && i.owner !== ownerFilter)              return false;
    if (stateFilter   !== 'all' && i.links?.state !== stateFilter)       return false;
    return true;
  });

  const clearAll = () => {
    setTypeFilter('all'); setStageFilter('all'); setFeatureFilter('all');
    setOwnerFilter('all'); setStateFilter('all');
  };
  const anyFilterOn = typeFilter !== 'all' || stageFilter !== 'all' || featureFilter !== 'all' || ownerFilter !== 'all' || stateFilter !== 'all';

  return (
    <div className="dv-designs">
      {/* Filter bar */}
      <div className="dv-filters">
        <div className="dv-filter-chips">
          {[
            { k: 'all',       label: 'All',        n: items.length },
            { k: 'screen',    label: 'Screens',    n: items.filter(i => i._t === 'screen').length },
            { k: 'flow',      label: 'Flows',      n: items.filter(i => i._t === 'flow').length },
            { k: 'prototype', label: 'Prototypes', n: items.filter(i => i._t === 'prototype').length },
          ].map(c => (
            <button key={c.k}
                    className={`dv-chip${typeFilter === c.k ? ' active' : ''}`}
                    onClick={() => setTypeFilter(c.k)}>
              {c.label} <span className="dv-chip-n">{c.n}</span>
            </button>
          ))}
        </div>
        <div className="dv-filter-selects">
          <select value={stageFilter} onChange={(e) => setStageFilter(e.target.value)} className="dv-select">
            <option value="all">All stages</option>
            {stagesInUse.map(s => (
              <option key={s} value={String(s)}>Stage {String(s).padStart(2,'0')}</option>
            ))}
          </select>
          <select value={featureFilter} onChange={(e) => setFeatureFilter(e.target.value)} className="dv-select">
            <option value="all">All features</option>
            {featuresInUse.map(fid => {
              const f = pdata.features.find(x => x.id === fid);
              return <option key={fid} value={fid}>{f?.title || fid}</option>;
            })}
          </select>
          <select value={ownerFilter} onChange={(e) => setOwnerFilter(e.target.value)} className="dv-select">
            <option value="all">All owners</option>
            {owners.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
          <select value={stateFilter} onChange={(e) => setStateFilter(e.target.value)} className="dv-select">
            <option value="all">Any status</option>
            {states.map(s => <option key={s} value={s}>{DV_STATE[s]?.label || s}</option>)}
          </select>
          {anyFilterOn && (
            <button className="dv-clear" onClick={clearAll}>Clear</button>
          )}
        </div>
      </div>

      {/* Gallery */}
      {filtered.length ? (
        <div className="dv-grid">
          {filtered.map(item => (
            <DVCard key={item.id} item={item} pdata={pdata} onOpen={onOpenFlow} />
          ))}
        </div>
      ) : (
        <div className="dv-empty dv-empty-large">
          Nothing matches those filters. <button className="link" onClick={clearAll}>Clear all</button>.
        </div>
      )}
    </div>
  );
}

// =========================================================
// DESIGN ITEM DETAIL — Smart Project Brief · Desktop
// =========================================================

function DVItemDetail({ pdata, itemId }) {
  const item = (pdata.design?.screens || []).find(s => s.id === itemId);
  if (!item) {
    return (
      <div className="dv-detail">
        <a href={`#/projects/${pdata.id}/design/designs`} className="dv-back">
          <Icon name="chevronL" size={12} strokeWidth={2} /> <span>Back to Designs</span>
        </a>
        <div className="dv-empty dv-empty-large" style={{ marginTop: 20 }}>
          We couldn't find that design item.
        </div>
      </div>
    );
  }

  const details = pdata.design?.details?.[itemId] || {};
  const state = DV_STATE[item.links?.state];
  const feature = item.links?.feature ? pdata.features.find(f => f.id === item.links.feature) : null;
  const stage = item.links?.stage ? pdata.stages.find(s => s.n === item.links.stage) : null;
  const missionMeta = item.links?.mission ? window.MYGENI_MISSIONS[item.links.mission] : null;

  // Local UI state — kept intentionally simple.
  const [platform, setPlatform] = React.useState(item.platform || 'desktop');
  const versions = details.history || [{ v: item.version || 'v1', date: item.updated, by: item.owner, note: '' }];
  const [version, setVersion] = React.useState(versions[0].v);

  const checklist = details.checklist || [];
  const attachments = details.attachments || [];
  const comments = details.comments || [];

  const doneCount = checklist.filter(c => c.done).length;

  const flow = (pdata.design?.flows || []).find(fl => fl.links?.feature === item.links?.feature);

  return (
    <div className="dv-detail">
      {/* Back link — restrained wayfinding */}
      <a href={`#/projects/${pdata.id}/design/designs`} className="dv-back">
        <Icon name="chevronL" size={12} strokeWidth={2} /> <span>Back to Designs</span>
      </a>

      {/* --- Compact header ---------------------------------------- */}
      <div className="dv-detail-head">
        <div className="dv-detail-head-l">
          <div className="dv-detail-eyebrow">
            <Icon name="palette" size={12} strokeWidth={1.75} />
            <span>Design · Screen</span>
            <span className="dot-sep">·</span>
            <span className="mono">DES-{item.id.toUpperCase()}</span>
          </div>
          <h1 className="dv-detail-title">{item.title}</h1>
          <div className="dv-detail-meta">
            {state && <Label tone={state.tone} dot size="sm">{state.label}</Label>}
            <span className="dv-detail-meta-item">
              <Icon name="clock" size={12} strokeWidth={1.75} />
              <span>Updated {item.updated}</span>
            </span>
            <span className="dv-detail-meta-item">
              <span className="dv-ver dv-ver-big">{version}</span>
            </span>
            {stage && (
              <a href={`#/projects/${pdata.id}/plan`} className="dv-detail-meta-item link">
                <Icon name="stages" size={12} strokeWidth={1.75} />
                <span>Stage {String(stage.n).padStart(2,'0')} · {stage.name}</span>
              </a>
            )}
            {feature && (
              <a href={`#/projects/${pdata.id}/features/${feature.id}`} className="dv-detail-meta-item link">
                <Icon name="features" size={12} strokeWidth={1.75} />
                <span>{feature.title}</span>
              </a>
            )}
            {missionMeta && (
              <span className="dv-detail-meta-item">
                <Icon name={missionMeta.icon} size={12} strokeWidth={1.75} />
                <span>{missionMeta.label}</span>
              </span>
            )}
          </div>
        </div>

        <div className="dv-detail-head-r">
          <div className="dv-detail-people">
            <div className="dv-detail-owner">
              <div className="dv-eyebrow">Owner</div>
              <div className="dv-detail-owner-row">
                <Avatar name={item.owner} size="sm" portrait={dvPortraitFor(item.owner, pdata)} />
                <span>{item.owner}</span>
              </div>
            </div>
            {item.reviewers?.length > 0 && (
              <div className="dv-detail-reviewers">
                <div className="dv-eyebrow">Reviewers</div>
                <div className="dv-detail-reviewer-row">
                  {item.reviewers.map(r => (
                    <span className="dv-reviewer-chip" key={r}>
                      <Avatar name={r} size="xs" portrait={dvPortraitFor(r, pdata)} />
                      <span>{r}</span>
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
          <div className="dv-detail-actions">
            <button className="btn btn-white btn-sm">
              <Icon name="share" size={14} strokeWidth={1.75} /> <span>Share</span>
            </button>
            <button className="btn btn-primary btn-sm">
              <Icon name="check" size={14} strokeWidth={1.75} /> <span>Request review</span>
            </button>
          </div>
        </div>
      </div>

      {/* --- Preview + Rail (main split) --------------------------- */}
      <div className="dv-detail-grid">
        <div className="dv-detail-preview-card">
          {/* Preview toolbar */}
          <div className="dv-preview-bar">
            <div className="dv-preview-bar-l">
              <div className="dv-platform-toggle">
                {['desktop', 'mobile', 'dialog'].map(p => (
                  <button key={p}
                          className={`dv-platform-btn${platform === p ? ' active' : ''}`}
                          onClick={() => setPlatform(p)}>
                    <Icon name={p === 'desktop' ? 'grid' : (p === 'mobile' ? 'phone' : 'stack')} size={12} strokeWidth={1.75} />
                    <span>{p.charAt(0).toUpperCase() + p.slice(1)}</span>
                  </button>
                ))}
              </div>
              <select className="dv-select dv-select-sm" value={version} onChange={(e) => setVersion(e.target.value)}>
                {versions.map(v => <option key={v.v} value={v.v}>{v.v} · {v.date}</option>)}
              </select>
            </div>
            <div className="dv-preview-bar-r">
              <button className="icon-btn icon-btn-sm" title="Zoom out"><Icon name="minus" size={14} strokeWidth={2} /></button>
              <button className="icon-btn icon-btn-sm" title="Zoom in"><Icon name="plus"  size={14} strokeWidth={2} /></button>
              <span className="dv-zoom">100%</span>
              <button className="icon-btn icon-btn-sm" title="Open in inspector"><Icon name="external" size={14} strokeWidth={1.75} /></button>
            </div>
          </div>

          {/* The strongest element on the page */}
          <div className={`dv-preview-frame dv-plat-${platform}`}>
            <div className="dv-preview-inner">
              <DVMock kind={platform === 'mobile' ? 'mobile-brief' : (platform === 'dialog' ? 'approve-modal' : item.kind)} />
            </div>
          </div>

          <div className="dv-preview-caption">
            <span>{item.title}</span>
            <span className="dot-sep">·</span>
            <span>{platform}</span>
            <span className="dot-sep">·</span>
            <span>{version}</span>
          </div>
        </div>

        {/* Rail */}
        <div className="dv-detail-rail">
          {/* Review flow */}
          <div className="dv-rail-card">
            <div className="dv-rail-head">
              <h4>Review</h4>
              {state && <Label tone={state.tone} dot size="sm">{state.label}</Label>}
            </div>
            <div className="dv-review-track">
              {['Draft', 'Ready for review', 'Approved'].map((step, i) => {
                const activeIdx = state?.review === 'approve' ? 2 : (state?.review === 'review' ? 1 : 0);
                const active = i <= activeIdx;
                const now = i === activeIdx;
                return (
                  <div key={i} className={`dv-review-node${active ? ' active' : ''}${now ? ' now' : ''}`}>
                    <span className="dv-review-dot" />
                    <span className="dv-review-lbl">{step}</span>
                  </div>
                );
              })}
            </div>
            <div className="dv-comments">
              {comments.map((c, i) => (
                <div key={i} className={`dv-comment dv-comment-${c.state}`}>
                  <Avatar name={c.by} size="xs" portrait={dvPortraitFor(c.by, pdata)} />
                  <div className="dv-comment-body">
                    <div className="dv-comment-head">
                      <b>{c.by}</b>
                      <span className="dv-comment-when">{c.when}</span>
                      {c.state === 'approve' && <Label tone="green" size="sm">Approve</Label>}
                      {c.state === 'change'  && <Label tone="yellow" size="sm">Requested changes</Label>}
                    </div>
                    <div className="dv-comment-text">{c.text}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Checklist */}
          <div className="dv-rail-card">
            <div className="dv-rail-head">
              <h4>Checklist</h4>
              <span className="dv-count mono">{doneCount}/{checklist.length}</span>
            </div>
            <div className="dv-checklist">
              {checklist.map((c, i) => (
                <div key={i} className={`dv-checklist-row${c.done ? ' done' : ''}`}>
                  <span className="dv-check">
                    {c.done && <Icon name="check" size={11} strokeWidth={2.5} />}
                  </span>
                  <div className="dv-checklist-body">
                    <div className="dv-checklist-title">{c.title}</div>
                    <div className="dv-checklist-meta">
                      <Avatar name={c.owner} size="xs" portrait={dvPortraitFor(c.owner, pdata)} />
                      <span>{c.owner}</span>
                      <span className="dot-sep">·</span>
                      <span>Due {c.due}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Related — canonical */}
          <div className="dv-rail-card">
            <div className="dv-rail-head"><h4>Related</h4></div>
            <div className="dv-related-list">
              {feature && (
                <a href={`#/projects/${pdata.id}/features/${feature.id}`} className="dv-related-row">
                  <Icon name="features" size={14} strokeWidth={1.75} />
                  <span className="truncate">{feature.title}</span>
                  <span className="dv-related-tag mono">FEAT</span>
                </a>
              )}
              {stage && (
                <a href={`#/projects/${pdata.id}/plan`} className="dv-related-row">
                  <Icon name="stages" size={14} strokeWidth={1.75} />
                  <span>Stage {String(stage.n).padStart(2,'0')} · {stage.name}</span>
                  <span className="dv-related-tag mono">S{String(stage.n).padStart(2,'0')}</span>
                </a>
              )}
              {missionMeta && (
                <a href={`#/projects/${pdata.id}/plan`} className="dv-related-row">
                  <Icon name={missionMeta.icon} size={14} strokeWidth={1.75} />
                  <span>{missionMeta.label} Mission</span>
                  <span className="dv-related-tag mono">MSN</span>
                </a>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* --- Attachments strip ------------------------------------- */}
      {attachments.length > 0 && (
        <div className="dv-attach-block">
          <div className="ov-section-head" style={{ paddingBottom: 10 }}>
            <h3>Attachments</h3>
          </div>
          <div className="dv-attach-grid">
            {attachments.map((a, i) => (
              <div key={i} className={`dv-attach dv-attach-${a.color}`}>
                <div className="dv-attach-thumb"><DVAttachThumb kind={a.kind} /></div>
                <div className="dv-attach-meta">
                  <div className="dv-attach-title truncate">{a.title}</div>
                  <div className="dv-attach-sub">{a.meta}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* --- Full flow, if this item is part of one ---------------- */}
      {flow && (
        <div className="dv-flow-block">
          <div className="ov-section-head" style={{ paddingBottom: 10 }}>
            <h3>Flow · {flow.title}</h3>
            <span className="dv-flow-meta">{flow.steps.length} steps · Updated {flow.updated}</span>
          </div>
          <div className="dv-flow-container">
            <DVFlowStrip steps={flow.steps} />
          </div>
        </div>
      )}
    </div>
  );
}

function DVAttachThumb({ kind }) {
  if (kind === 'figma') {
    return (
      <svg viewBox="0 0 40 40" width="100%" height="100%">
        <rect x="6"  y="4"  width="10" height="10" fill="#F24E1E"/>
        <rect x="16" y="4"  width="10" height="10" fill="#FF7262"/>
        <rect x="6"  y="14" width="10" height="10" fill="#A259FF"/>
        <rect x="16" y="14" width="10" height="10" fill="#1ABCFE"/>
        <rect x="6"  y="24" width="10" height="10" fill="#0ACF83"/>
      </svg>
    );
  }
  if (kind === 'pdf') {
    return (
      <svg viewBox="0 0 40 40" width="100%" height="100%">
        <rect x="6" y="4" width="28" height="32" rx="2" fill="#FDFDFD" stroke="rgba(16,16,16,0.14)"/>
        {[10, 14, 18, 22, 26].map((y,i)=><rect key={i} x="10" y={y} width={i%2 ? 18 : 22} height="1.5" rx="0.5" fill="rgba(16,16,16,0.20)"/>)}
        <rect x="20" y="30" width="14" height="6" rx="1" fill="#FF381C" opacity="0.85"/>
      </svg>
    );
  }
  if (kind === 'image') {
    return (
      <svg viewBox="0 0 40 40" width="100%" height="100%">
        <rect x="4" y="6" width="32" height="28" rx="3" fill="#FBFAF6" stroke="rgba(16,16,16,0.10)"/>
        <circle cx="14" cy="16" r="3" fill="#EF9D0E"/>
        <path d="M6 30 L16 20 L24 27 L28 23 L34 30 Z" fill="#B5E4CA"/>
      </svg>
    );
  }
  if (kind === 'video') {
    return (
      <svg viewBox="0 0 40 40" width="100%" height="100%">
        <rect x="4" y="6" width="32" height="28" rx="3" fill="#141414"/>
        <path d="M16 14 L28 20 L16 26 Z" fill="#FDFDFD"/>
      </svg>
    );
  }
  return null;
}

// =========================================================
// LIBRARY — one page with filter chips and scroll sections
// =========================================================

function DVLibrary({ pdata }) {
  const lib = pdata.design?.library || {};
  const [section, setSection] = React.useState('all');

  const sections = [
    { k: 'all',            label: 'All'           },
    { k: 'design-system',  label: 'Design system' },
    { k: 'components',     label: 'Components'    },
    { k: 'icons',          label: 'Icons'         },
    { k: 'illustrations',  label: 'Illustrations' },
    { k: 'assets',         label: 'Assets'        },
  ];
  const show = (k) => section === 'all' || section === k;

  return (
    <div className="dv-library">
      <div className="dv-filters">
        <div className="dv-filter-chips">
          {sections.map(s => (
            <button key={s.k}
                    className={`dv-chip${section === s.k ? ' active' : ''}`}
                    onClick={() => setSection(s.k)}>
              {s.label}
            </button>
          ))}
        </div>
      </div>

      {show('design-system') && <DVDesignSystemSection />}
      {show('components')    && <DVComponentsSection components={lib.components || []} />}
      {show('icons')         && <DVIconsSection count={lib.icons || 0} />}
      {show('illustrations') && <DVIllusSection items={lib.illustrations || []} />}
      {show('assets')        && <DVAssetsSection items={lib.assets || []} />}
    </div>
  );
}

function DVDesignSystemSection() {
  const colors = [
    { k: '--bg-app',      v: '#F1F1F1' },
    { k: '--bg-surface',  v: '#FDFDFD' },
    { k: '--bg-depth',    v: '#EBEBEB' },
    { k: '--bg-highlight',v: '#FBFAF6' },
    { k: '--bg-inset',    v: '#F1F1F1' },
  ];
  const semantic = [
    { k: '--primary-01',  v: '#2A85FF', label: 'Brand'    },
    { k: 'success',       v: '#00A656', label: 'Success'  },
    { k: 'warning',       v: '#EF9D0E', label: 'Warning'  },
    { k: 'danger',        v: '#FF381C', label: 'Danger'   },
    { k: 'accent',        v: '#F52495', label: 'Accent'   },
  ];
  const radii = [
    { k: 'sm',   px: 8  },
    { k: 'md',   px: 12 },
    { k: 'lg',   px: 18 },
    { k: 'xl',   px: 22 },
    { k: '2xl',  px: 26 },
    { k: '3xl',  px: 32 },
  ];
  return (
    <section className="dv-lib-sec">
      <div className="ov-section-head" style={{ paddingBottom: 10 }}><h3>Design system · tokens</h3></div>

      <div className="dv-tokens-grid">
        <div className="dv-token-card">
          <div className="dv-token-label">Surface</div>
          <div className="dv-swatches">
            {colors.map(c => (
              <div className="dv-swatch" key={c.k}>
                <div className="dv-swatch-chip" style={{ background: c.v }} />
                <div className="dv-swatch-meta">
                  <div className="dv-swatch-name mono">{c.k}</div>
                  <div className="dv-swatch-hex mono">{c.v}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="dv-token-card">
          <div className="dv-token-label">Semantic</div>
          <div className="dv-swatches">
            {semantic.map(c => (
              <div className="dv-swatch" key={c.k}>
                <div className="dv-swatch-chip" style={{ background: c.v }} />
                <div className="dv-swatch-meta">
                  <div className="dv-swatch-name">{c.label}</div>
                  <div className="dv-swatch-hex mono">{c.v}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="dv-token-card">
          <div className="dv-token-label">Typography · Inter</div>
          <div className="dv-type-samples">
            <div style={{ fontSize: 40, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1.05 }}>Aa</div>
            <div className="dv-type-scale">
              <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em' }}>Heading · h3</div>
              <div style={{ fontSize: 16, fontWeight: 400, letterSpacing: '-0.015em', color: 'var(--text-secondary)' }}>Body long · 16 / 1.55</div>
              <div style={{ fontSize: 13, fontWeight: 500, letterSpacing: '-0.015em', color: 'var(--text-tertiary)' }}>Small · 13 / 1.5</div>
              <div style={{ fontFamily: 'Georgia', fontStyle: 'italic', fontSize: 18, color: 'var(--text-primary)' }}>"Editorial pull-quote"</div>
            </div>
          </div>
        </div>

        <div className="dv-token-card">
          <div className="dv-token-label">Radius scale</div>
          <div className="dv-radii">
            {radii.map(r => (
              <div className="dv-radius" key={r.k}>
                <div className="dv-radius-chip" style={{ borderRadius: r.px }} />
                <div className="dv-radius-lbl mono">{r.k} · {r.px}px</div>
              </div>
            ))}
          </div>
        </div>

        <div className="dv-token-card">
          <div className="dv-token-label">Elevation</div>
          <div className="dv-elev-samples">
            <div className="dv-elev dv-elev-widget">widget</div>
            <div className="dv-elev dv-elev-depth">depth</div>
            <div className="dv-elev dv-elev-inset">inset</div>
          </div>
        </div>
      </div>
    </section>
  );
}

function DVComponentsSection({ components }) {
  return (
    <section className="dv-lib-sec">
      <div className="ov-section-head" style={{ paddingBottom: 10 }}><h3>Components</h3></div>
      <div className="dv-comp-grid">
        <DVCompPreview title="Button">
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <button className="btn btn-primary btn-sm">Primary</button>
            <button className="btn btn-white btn-sm">Secondary</button>
            <button className="btn btn-dark btn-sm">Dark</button>
            <button className="btn btn-white btn-sm" disabled style={{ opacity: 0.4 }}>Disabled</button>
          </div>
        </DVCompPreview>
        <DVCompPreview title="Label · Chip">
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            <Label tone="green"  dot size="sm">Approved</Label>
            <Label tone="blue"   dot size="sm">In review</Label>
            <Label tone="yellow" dot size="sm">Attention</Label>
            <Label tone="red"    dot size="sm">Blocked</Label>
            <Label tone="gray"   dot size="sm">Draft</Label>
          </div>
        </DVCompPreview>
        <DVCompPreview title="Progress · Ring">
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ flex: 1 }}><ProgressBar value={62} tone="blue" /></div>
            <Ring percent={72} color="var(--primary-01)" size={40} />
          </div>
        </DVCompPreview>
        <DVCompPreview title="Avatar · Stack">
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar name="Alireza Izadi" size="md" />
            <Avatar name="Keyvan"       size="md" />
            <AvatarStack names={['Ali','Ali','Hesam']} max={3} size="sm" />
          </div>
        </DVCompPreview>
        <DVCompPreview title="Input">
          <input className="input" placeholder="Search projects…" style={{ width: '100%' }} />
        </DVCompPreview>
        <DVCompPreview title="Card">
          <div style={{ padding: 12, borderRadius: 16, background: 'var(--bg-surface)', boxShadow: 'var(--shadow-widget)' }}>
            <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>Card surface</div>
            <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>32px radius flagship</div>
          </div>
        </DVCompPreview>
      </div>
    </section>
  );
}

function DVCompPreview({ title, children }) {
  return (
    <div className="dv-comp">
      <div className="dv-comp-title">{title}</div>
      <div className="dv-comp-body">{children}</div>
    </div>
  );
}

function DVIconsSection({ count }) {
  const sample = ['home','projects','features','flask','palette','terminal','wallet','files','settings','search','plus','check','clock','stages','decisions','inbox','person','route','shield','compass','stack','grid','play','bell','share','edit'];
  return (
    <section className="dv-lib-sec">
      <div className="ov-section-head" style={{ paddingBottom: 10 }}>
        <h3>Icons</h3>
        <span className="dv-flow-meta">{count} icons · 1.5px stroke · currentColor</span>
      </div>
      <div className="dv-icons-grid">
        {sample.map(n => (
          <div className="dv-icon-cell" key={n} title={n}>
            <Icon name={n} size={18} strokeWidth={1.6} />
            <span className="dv-icon-name mono">{n}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

function DVIllusSection({ items }) {
  return (
    <section className="dv-lib-sec">
      <div className="ov-section-head" style={{ paddingBottom: 10 }}><h3>Illustrations</h3></div>
      <div className="dv-illus-grid">
        {items.map((i, idx) => (
          <div className="dv-illus" key={idx}>
            <div className="dv-illus-frame">
              <svg viewBox="0 0 120 80" width="100%" height="100%">
                <circle cx="60" cy="42" r="26" fill={['rgba(202,189,255,0.30)','rgba(181,228,202,0.30)','rgba(255,188,153,0.30)','rgba(177,229,252,0.30)'][idx % 4]}/>
                <rect x="42" y="26" width="24" height="30" rx="4" fill="white" stroke="rgba(16,16,16,0.12)"/>
                <rect x="68" y="36" width="18" height="22" rx="3" fill="white" stroke="rgba(16,16,16,0.12)"/>
              </svg>
            </div>
            <div className="dv-illus-name">{i.name}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function DVAssetsSection({ items }) {
  return (
    <section className="dv-lib-sec">
      <div className="ov-section-head" style={{ paddingBottom: 10 }}><h3>Assets</h3></div>
      <div className="dv-assets-row">
        {items.map((a, i) => (
          <div className="dv-asset-tile" key={i}>
            <div className="dv-asset-thumb"><AssetPreview kind={a.kind} /></div>
            <div className="dv-asset-body">
              <div className="dv-asset-name">{a.name}</div>
              <div className="dv-asset-meta">{a.count != null ? `${a.count} items` : 'Reference'}</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// =========================================================
// ROUTER SHELL
// -----------------------------------------------------------------
// Sub-route shape:
//   /design              → subId=null       → Overview
//   /design/designs      → subId='designs'  → Designs gallery
//   /design/library      → subId='library'  → Library
//   /design/item/:id     → subId='item'     → Design Item Detail (sub2=id)
// =========================================================

function DesignWorkspaceV2({ pdata, subId, sub2 }) {
  const isDetail = subId === 'item';
  const view = isDetail
    ? 'item'
    : (subId === 'designs' ? 'designs' : (subId === 'library' ? 'library' : 'overview'));

  const setView = (v) => {
    location.hash = v === 'overview'
      ? `#/projects/${pdata.id}/design`
      : `#/projects/${pdata.id}/design/${v}`;
  };

  return (
    <div className="dv-root" data-screen-label={`Design · ${view}`}>
      {/* Segmented control — hidden on Detail so the item is the focus */}
      {!isDetail && (
        <div className="dv-nav-row">
          <div className="dv-seg" role="tablist" aria-label="Design views">
            {[
              { k: 'overview', label: 'Overview' },
              { k: 'designs',  label: 'Designs'  },
              { k: 'library',  label: 'Library'  },
            ].map(t => (
              <button
                key={t.k}
                role="tab"
                aria-selected={view === t.k}
                className={`dv-seg-btn${view === t.k ? ' active' : ''}`}
                onClick={() => setView(t.k)}
              >
                {t.label}
              </button>
            ))}
          </div>
          <div className="dv-nav-actions">
            <span className="dv-direction">{pdata.design?.direction?.split('.')[0]}.</span>
          </div>
        </div>
      )}

      {view === 'overview' && <DVOverview pdata={pdata} onNavigate={setView} />}
      {view === 'designs'  && <DVDesigns  pdata={pdata} onOpenFlow={() => { /* flows preview inline; no detail page */ }} />}
      {view === 'library'  && <DVLibrary  pdata={pdata} />}
      {view === 'item'     && <DVItemDetail pdata={pdata} itemId={sub2} />}
    </div>
  );
}

Object.assign(window, {
  DesignWorkspaceV2,
  DVMock, DVFlowStrip,
});
