const { useState, useMemo, useCallback } = React;
const T = window.ArbiterTokens;

const extColor = (ext) => ({ PDF: '#C23030', DOCX: '#2563EB', XLSX: '#1B7A4A', MSG: '#B8860B' }[ext] || T.color.text.tertiary);
const statusColor = (s) => ({ Draft: T.color.status.warning, Final: T.color.status.active, Filed: T.color.accent.blue, Review: '#6B21A8' }[s] || T.color.status.pending);
const confColor = (c) => c?.includes('Highly') ? T.color.status.critical : c?.includes('AEO') ? T.color.status.critical : c === 'Internal' ? T.color.status.pending : T.color.text.tertiary;

// ── DOCUMENT DETAIL SLIDE-OUT ──
function DocDetailPanel({ doc, onClose, onNavigate }) {
  const [tab, setTab] = useState('info');
  const [commentText, setCommentText] = useState('');
  const [comments, setComments] = useState(doc?.comments || []);

  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);

  React.useEffect(() => { setComments(doc?.comments || []); setTab('info'); }, [doc?.id]);

  if (!doc) return null;

  const addComment = () => {
    if (!commentText.trim()) return;
    setComments(prev => [...prev, { id: 'c-' + Date.now(), author: 'M. Kirkland', time: 'Just now', text: commentText, resolved: false }]);
    setCommentText('');
  };

  const linkedTasks = (doc.linkedTasks || []).map(id => window.TASKS?.find(t => t.id === id)).filter(Boolean);
  const linkedDeadlines = (doc.linkedDeadlines || []).map(id => window.DOCKET_DEADLINES?.find(d => d.id === id)).filter(Boolean);

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(10,22,40,0.3)', zIndex: 100, display: 'flex', justifyContent: 'flex-end' }} onClick={onClose}>
      <div style={{ width: '520px', maxWidth: '100vw', background: T.color.bg.card, height: '100%', overflow: 'auto', boxShadow: '-4px 0 24px rgba(10,22,40,0.12)', animation: 'slideInRight 0.2s ease-out' }} onClick={e => e.stopPropagation()}>
        {/* Header */}
        <div style={{ padding: '16px 20px', borderBottom: `1px solid ${T.color.border.light}` }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '8px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <span style={{ fontSize: '9px', fontWeight: 700, padding: '2px 6px', borderRadius: '3px', background: `${extColor(doc.ext)}10`, color: extColor(doc.ext) }}>{doc.ext}</span>
              {doc.locked && <span style={{ fontSize: '9px', fontWeight: 700, color: T.color.status.warning, letterSpacing: '0.04em' }} title={`Locked by ${doc.lockedBy}`}>LOCKED</span>}
              {doc.starred && <span style={{ fontSize: '12px', color: '#D4A017' }}><Icons.Star size={11}/></span>}
            </div>
            <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: '18px', color: T.color.text.tertiary, cursor: 'pointer' }}>×</button>
          </div>
          <div style={{ fontSize: T.font.size.lg, fontWeight: T.font.weight.bold, color: T.color.text.primary, lineHeight: 1.3, marginBottom: '8px' }}>{doc.name}</div>
          <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
            <span style={{ ...window.sharedStyles.tag, background: `${statusColor(doc.status)}14`, color: statusColor(doc.status) }}>{doc.status}</span>
            <span style={{ ...window.sharedStyles.tag, background: T.color.bg.secondary, color: T.color.text.secondary }}>{doc.type}</span>
            {doc.confidentiality && doc.confidentiality !== 'Public' && (
              <span style={{ ...window.sharedStyles.tag, background: `${confColor(doc.confidentiality)}10`, color: confColor(doc.confidentiality) }}>{doc.confidentiality}</span>
            )}
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', borderBottom: `1px solid ${T.color.border.light}`, padding: '0 20px', overflowX: 'auto' }}>
          {[
            {id:'info',label:'Details'},
            {id:'preview',label:'Preview'},
            {id:'versions',label:`Versions (${doc.versions?.length || 0})`},
            {id:'comments',label:`Comments (${comments.length})`},
            {id:'permissions',label:'Permissions'},
            {id:'holds',label:'Holds'},
            {id:'related',label:'Related'},
            {id:'ai',label:'AI'},
            {id:'links',label:'Links'},
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: '8px 12px', fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, border: 'none', background: 'none',
              color: tab === t.id ? T.color.text.primary : T.color.text.tertiary,
              borderBottom: tab === t.id ? `2px solid ${T.color.navy800}` : '2px solid transparent',
              cursor: 'pointer', fontFamily: T.font.family, marginBottom: '-1px', whiteSpace: 'nowrap',
            }}>{t.label}</button>
          ))}
        </div>

        <div style={{ padding: '16px 20px' }}>
          {/* INFO TAB */}
          {tab === 'info' && (
            <div>
              <div style={{ display: 'grid', gridTemplateColumns: '110px 1fr', gap: '6px 12px', fontSize: T.font.size.sm, marginBottom: '20px' }}>
                {[
                  ['Matter', doc.matter],
                  ['Author', doc.author],
                  ['Created', new Date(doc.created).toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'})],
                  ['Modified', new Date(doc.modified).toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'})],
                  ['Size', doc.size],
                  ['Confidentiality', doc.confidentiality || 'None'],
                  ['Locked', doc.locked ? `Yes — ${doc.lockedBy}` : 'No'],
                ].map(([label, val], i) => (
                  <React.Fragment key={i}>
                    <span style={{ color: T.color.text.tertiary, fontWeight: T.font.weight.medium, fontSize: T.font.size.xs, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps }}>{label}</span>
                    <span style={{ color: T.color.text.primary }}>{val}</span>
                  </React.Fragment>
                ))}
              </div>
              {/* Tags */}
              {doc.tags?.length > 0 && (
                <div style={{ marginBottom: '16px' }}>
                  <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '6px' }}>Tags</div>
                  <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                    {doc.tags.map((tag, i) => (
                      <span key={i} style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '10px', background: T.color.accent.blueBg, color: T.color.accent.blue, fontWeight: 500 }}>{tag}</span>
                    ))}
                  </div>
                </div>
              )}
              {/* Permissions */}
              <div style={{ marginBottom: '16px' }}>
                <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '6px' }}>Access</div>
                <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                  {(doc.permissions || []).map((p, i) => {
                    const initials = window.ASSIGNEE_INITIALS?.[p] || p.charAt(0);
                    const color = window.ASSIGNEE_COLORS?.[p] || T.color.navy500;
                    return (
                      <span key={i} title={p} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '26px', height: '26px', borderRadius: '50%', background: `${color}18`, color: color, fontSize: '10px', fontWeight: 600 }}>{initials}</span>
                    );
                  })}
                </div>
              </div>
              {/* Activity */}
              <div>
                <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '6px' }}>Activity</div>
                {(doc.activity || []).map((a, i) => (
                  <div key={i} style={{ display: 'flex', gap: '8px', padding: '5px 0', fontSize: T.font.size.sm, borderBottom: i < doc.activity.length - 1 ? `1px solid ${T.color.border.light}` : 'none' }}>
                    <span style={{ fontWeight: T.font.weight.medium, color: T.color.text.primary, minWidth: '80px' }}>{a.action}</span>
                    <span style={{ color: T.color.text.secondary, flex: 1 }}>{a.user}</span>
                    <span style={{ color: T.color.text.tertiary, fontFamily: T.font.mono, fontSize: T.font.size.xs }}>{a.time}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* PREVIEW TAB */}
          {tab === 'preview' && (
            <div>
              <div style={{ background: T.color.bg.secondary, border: `1px dashed ${T.color.border.medium}`, borderRadius: T.radius.md, padding: '20px', minHeight: '280px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
                <span style={{ fontSize: '36px', color: extColor(doc.ext), fontWeight: 700, marginBottom: '8px' }}>{doc.ext}</span>
                <div style={{ fontSize: T.font.size.sm, fontWeight: T.font.weight.semibold, color: T.color.text.primary, marginBottom: '4px' }}>{doc.name}</div>
                <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, marginBottom: '14px' }}>{doc.size} · {doc.versions?.length || 1} version(s)</div>
                <button style={{ padding: '8px 16px', fontSize: '12px', fontWeight: 600, border: 'none', background: '#2563EB', color: '#fff', borderRadius: '6px', cursor: 'pointer' }}>Open full preview</button>
              </div>
              <div style={{ marginTop: '14px', padding: '10px 12px', background: T.color.bg.secondary, border: `1px solid ${T.color.border.light}`, borderRadius: '6px', fontSize: '11px', color: T.color.text.secondary, lineHeight: 1.55 }}>
                <div style={{ fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Extracted text (excerpt)</div>
                Lorem ipsum placeholder for the rendered first-page text of the document. In production this would be streamed from the OCR pipeline or the document service's extraction API.
              </div>
            </div>
          )}

          {/* PERMISSIONS TAB */}
          {tab === 'permissions' && (
            <div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '8px', alignItems: 'center', marginBottom: '10px' }}>
                <div style={{ fontSize: T.font.size.sm, fontWeight: T.font.weight.semibold }}>Access list ({(doc.permissions || []).length})</div>
                <button style={{ padding: '4px 10px', fontSize: '11px', fontWeight: 600, border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, borderRadius: '6px', cursor: 'pointer' }}>+ Add</button>
              </div>
              {(doc.permissions || []).map((p, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 10px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm }}>
                  <span style={{ fontWeight: T.font.weight.medium }}>{p}</span>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    <span style={{ ...window.sharedStyles.tag, background: 'rgba(5,150,105,0.12)', color: '#059669' }}>Edit</span>
                    <button style={{ padding: '2px 8px', fontSize: '10px', fontWeight: 600, border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, borderRadius: '4px', cursor: 'pointer', color: T.color.text.tertiary }}>Revoke</button>
                  </div>
                </div>
              ))}
              <div style={{ marginTop: '14px', padding: '10px', background: T.color.bg.secondary, borderRadius: '6px', fontSize: '11px', color: T.color.text.secondary }}>
                <div style={{ fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Confidentiality</div>
                {doc.confidentiality || 'Internal'} · Inherits from folder
              </div>
            </div>
          )}

          {/* HOLDS TAB */}
          {tab === 'holds' && (() => {
            const holds = (window.DOC_LEGAL_HOLDS || []).filter(h => h.matter && doc.matter?.includes(h.matter.split(' ')[0]) && h.status === 'Active');
            const retention = (window.DOC_RETENTION_POLICIES || []).find(r => r.appliesTo?.includes('all') || r.appliesTo?.includes(doc.status?.toLowerCase()));
            return (
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '8px' }}>Active holds affecting this document</div>
                {holds.length === 0 ? (
                  <div style={{ padding: '14px', background: T.color.bg.secondary, borderRadius: '6px', fontSize: '12px', color: T.color.text.tertiary }}>No active legal holds apply to this document.</div>
                ) : holds.map(h => (
                  <div key={h.id} style={{ padding: '10px 12px', background: 'rgba(185,28,28,0.06)', border: '1px solid rgba(185,28,28,0.2)', borderRadius: '6px', marginBottom: '8px' }}>
                    <div style={{ fontSize: '12px', fontWeight: 700, color: '#B91C1C' }}>{h.name}</div>
                    <div style={{ fontSize: '11px', color: T.color.text.secondary, marginTop: '3px' }}>Issued {h.issued} · Owner {h.owner} · {h.custodians} custodians</div>
                  </div>
                ))}
                {retention && (
                  <div style={{ marginTop: '14px' }}>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Retention policy</div>
                    <div style={{ padding: '10px', background: T.color.bg.secondary, borderRadius: '6px', fontSize: '11px' }}>
                      <div style={{ fontWeight: 700 }}>{retention.name}</div>
                      <div style={{ color: T.color.text.tertiary, marginTop: '2px' }}>{retention.action} after {retention.durationYrs != null ? `${retention.durationYrs} year(s)` : 'permanent'} · Trigger: {retention.trigger}</div>
                    </div>
                  </div>
                )}
              </div>
            );
          })()}

          {/* RELATED TAB (doc→doc graph) */}
          {tab === 'related' && (() => {
            const rels = (window.DOC_RELATIONSHIPS || []).filter(r => r.from === doc.id || r.to === doc.id);
            const typeColor = { cites: '#2563EB', 'parent-of': '#7C3AED', supersedes: '#B45309', 'reply-to': '#059669', 'attached-to': '#6B7280', 'relates-to': '#0EA5E9' };
            return (
              <div>
                {rels.length === 0 ? (
                  <div style={{ padding: '14px', background: T.color.bg.secondary, borderRadius: '6px', fontSize: '12px', color: T.color.text.tertiary }}>No related documents.</div>
                ) : rels.map((r, i) => {
                  const otherId = r.from === doc.id ? r.to : r.from;
                  const other = window.DOC_ITEMS.find(d => d.id === otherId);
                  const direction = r.from === doc.id ? '→' : '←';
                  if (!other) return null;
                  return (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 12px', borderBottom: `1px solid ${T.color.border.light}` }}>
                      <span style={{ fontSize: '10px', fontWeight: 700, padding: '3px 8px', borderRadius: '4px', background: `${typeColor[r.type] || '#6B7280'}18`, color: typeColor[r.type] || '#6B7280', textTransform: 'uppercase', letterSpacing: '0.04em', minWidth: '80px', textAlign: 'center' }}>{direction} {r.type}</span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: '12px', fontWeight: 600, color: T.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{other.name}</div>
                        <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{r.note}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            );
          })()}

          {/* AI INSIGHTS TAB */}
          {tab === 'ai' && (() => {
            const insight = window.DOC_AI_INSIGHTS?.[doc.id];
            if (!insight) return (<div style={{ padding: '14px', background: T.color.bg.secondary, borderRadius: '6px', fontSize: '12px', color: T.color.text.tertiary }}>AI analysis pending. Document has not been processed yet.</div>);
            return (
              <div>
                <div style={{ padding: '12px', background: 'rgba(124,58,237,0.06)', border: '1px solid rgba(124,58,237,0.2)', borderRadius: '6px', marginBottom: '12px' }}>
                  <div style={{ fontSize: '10px', fontWeight: 700, color: '#7C3AED', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>AI summary · {insight.readTimeMin} min read</div>
                  <div style={{ fontSize: '12px', color: T.color.text.primary, lineHeight: 1.5 }}>{insight.summary}</div>
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <div style={{ fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Key points</div>
                  {insight.keyPoints.map((k, i) => (<div key={i} style={{ fontSize: '12px', color: T.color.text.secondary, padding: '3px 0' }}>• {k}</div>))}
                </div>
                {insight.autoTags?.length > 0 && (
                  <div style={{ marginBottom: '12px' }}>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Suggested tags</div>
                    <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                      {insight.autoTags.map((t, i) => (<span key={i} style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '10px', background: 'rgba(124,58,237,0.12)', color: '#7C3AED' }}>+ {t}</span>))}
                    </div>
                  </div>
                )}
                {insight.piiFlags?.length > 0 && insight.piiFlags.some(p => p.count > 0) && (
                  <div style={{ marginBottom: '12px', padding: '10px', background: 'rgba(185,28,28,0.06)', border: '1px solid rgba(185,28,28,0.2)', borderRadius: '6px' }}>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: '#B91C1C', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>PII / PHI detection</div>
                    {insight.piiFlags.filter(p => p.count > 0).map((p, i) => (
                      <div key={i} style={{ fontSize: '11px', color: T.color.text.secondary, padding: '2px 0' }}>• {p.count}× {p.type} {p.note && <span style={{ color: T.color.text.tertiary }}>— {p.note}</span>}</div>
                    ))}
                  </div>
                )}
                {insight.clauses?.length > 0 && (
                  <div style={{ marginBottom: '12px' }}>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Extracted clauses</div>
                    {insight.clauses.map((c, i) => {
                      const riskColor = c.risk === 'high' ? '#B91C1C' : c.risk === 'medium' ? '#B45309' : '#059669';
                      return (
                        <div key={i} style={{ padding: '8px 10px', background: T.color.bg.secondary, borderRadius: '6px', marginBottom: '4px' }}>
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2px' }}>
                            <span style={{ fontSize: '11px', fontWeight: 700, color: T.color.text.primary }}>{c.name}</span>
                            <span style={{ fontSize: '9px', padding: '2px 6px', borderRadius: '3px', background: `${riskColor}18`, color: riskColor, fontWeight: 700, textTransform: 'uppercase' }}>{c.risk}</span>
                          </div>
                          <div style={{ fontSize: '11px', color: T.color.text.secondary }}>{c.text}</div>
                        </div>
                      );
                    })}
                  </div>
                )}
                {insight.duplicates?.length > 0 && (
                  <div style={{ marginBottom: '8px', padding: '8px 10px', background: 'rgba(180,83,9,0.08)', border: '1px solid rgba(180,83,9,0.2)', borderRadius: '6px' }}>
                    <div style={{ fontSize: '11px', fontWeight: 700, color: '#B45309', marginBottom: '4px' }}>Potential duplicate</div>
                    {insight.duplicates.map((d, i) => {
                      const other = window.DOC_ITEMS.find(x => x.id === d.docId);
                      return (<div key={i} style={{ fontSize: '11px', color: T.color.text.secondary }}>• {Math.round(d.confidence * 100)}% overlap with {other?.name} — {d.overlap}</div>);
                    })}
                  </div>
                )}
              </div>
            );
          })()}

          {/* VERSIONS TAB */}
          {tab === 'versions' && (
            <div>
              {(doc.versions || []).map((v, i) => (
                <div key={i} style={{ padding: '10px 0', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '12px', alignItems: 'start' }}>
                  <div style={{ width: '36px', height: '36px', borderRadius: T.radius.md, background: i === 0 ? `${T.color.accent.blue}10` : T.color.bg.secondary, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: T.font.size.xs, fontWeight: 700, color: i === 0 ? T.color.accent.blue : T.color.text.tertiary, flexShrink: 0, fontFamily: T.font.mono }}>v{v.v}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: T.font.size.sm, fontWeight: T.font.weight.medium, color: T.color.text.primary }}>{v.notes}</div>
                    <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, marginTop: '2px' }}>{v.author} · {v.date} · {v.size}</div>
                  </div>
                  {i === 0 && <span style={{ ...window.sharedStyles.tag, background: T.color.status.activeBg, color: T.color.status.active }}>Current</span>}
                </div>
              ))}
            </div>
          )}

          {/* COMMENTS TAB */}
          {tab === 'comments' && (
            <div>
              <div style={{ marginBottom: '16px' }}>
                <textarea value={commentText} onChange={e => setCommentText(e.target.value)} placeholder="Add a comment..." style={{ width: '100%', minHeight: '52px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '8px 10px', fontSize: T.font.size.sm, fontFamily: T.font.family, color: T.color.text.primary, background: T.color.bg.primary, outline: 'none', resize: 'vertical', boxSizing: 'border-box' }} />
                <button onClick={addComment} style={{ ...window.sharedStyles.btn, ...window.sharedStyles.btnPrimary, marginTop: '6px' }}>Post Comment</button>
              </div>
              {comments.map(c => {
                const initials = window.ASSIGNEE_INITIALS?.[c.author] || c.author.charAt(0);
                const color = window.ASSIGNEE_COLORS?.[c.author] || T.color.navy500;
                return (
                  <div key={c.id} style={{ padding: '10px 0', borderBottom: `1px solid ${T.color.border.light}` }}>
                    <div style={{ display: 'flex', gap: '8px', alignItems: 'start' }}>
                      <span style={{ width: '24px', height: '24px', borderRadius: '50%', background: `${color}18`, color: color, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: '10px', fontWeight: 600, flexShrink: 0 }}>{initials}</span>
                      <div style={{ flex: 1 }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '3px' }}>
                          <span style={{ fontSize: T.font.size.sm, fontWeight: T.font.weight.semibold, color: T.color.text.primary }}>{c.author}</span>
                          <span style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{c.time}</span>
                        </div>
                        <div style={{ fontSize: T.font.size.sm, color: T.color.text.secondary, lineHeight: 1.5 }}>{c.text}</div>
                        {c.resolved && <span style={{ fontSize: T.font.size.xs, color: T.color.status.active, marginTop: '4px', display: 'inline-block' }}>ok Resolved</span>}
                      </div>
                    </div>
                  </div>
                );
              })}
              {comments.length === 0 && <div style={{ padding: '20px', textAlign: 'center', color: T.color.text.tertiary, fontSize: T.font.size.sm }}>No comments yet</div>}
            </div>
          )}

          {/* LINKS TAB */}
          {tab === 'links' && (
            <div>
              {linkedTasks.length > 0 && (
                <div style={{ marginBottom: '16px' }}>
                  <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '8px' }}>Linked Tasks</div>
                  {linkedTasks.map(t => {
                    const sc = { 'To Do': T.color.status.pending, 'In Progress': T.color.accent.blue, 'In Review': T.color.status.warning, 'Done': T.color.status.active };
                    return (
                      <div key={t.id} onClick={() => { onClose(); onNavigate && onNavigate('tasks'); }} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '8px', borderRadius: T.radius.sm, cursor: 'pointer', background: T.color.bg.secondary, marginBottom: '6px', border: `1px solid ${T.color.border.light}` }}>
                        <span style={{ width: '24px', height: '24px', borderRadius: T.radius.sm, background: `${T.color.accent.blue}10`, color: T.color.accent.blue, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '11px', fontWeight: 700, flexShrink: 0 }}></span>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: T.font.size.sm, fontWeight: T.font.weight.medium, color: T.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.title}</div>
                          <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{t.assignee} · Due {new Date(t.dueDate).toLocaleDateString('en-US',{month:'short',day:'numeric'})}</div>
                        </div>
                        <span style={{ ...window.sharedStyles.tag, background: `${sc[t.status]}14`, color: sc[t.status] }}>{t.status}</span>
                      </div>
                    );
                  })}
                </div>
              )}
              {linkedDeadlines.length > 0 && (
                <div style={{ marginBottom: '16px' }}>
                  <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '8px' }}>Linked Deadlines</div>
                  {linkedDeadlines.map(dl => (
                    <div key={dl.id} onClick={() => { onClose(); onNavigate && onNavigate('calendar'); }} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '8px', borderRadius: T.radius.sm, cursor: 'pointer', background: T.color.bg.secondary, marginBottom: '6px', border: `1px solid ${T.color.border.light}` }}>
                      <span style={{ width: '24px', height: '24px', borderRadius: T.radius.sm, background: 'rgba(217,119,6,0.08)', color: '#D97706', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '11px', fontWeight: 700, flexShrink: 0 }}>▦</span>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: T.font.size.sm, fontWeight: T.font.weight.medium, color: T.color.text.primary }}>{dl.label}</div>
                        <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{dl.matter} · {new Date(dl.date).toLocaleDateString('en-US',{month:'short',day:'numeric'})}</div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
              {doc.matterId && (
                <div>
                  <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '8px' }}>Matter</div>
                  <div onClick={() => { onClose(); const m = window.MATTERS?.find(x => x.id === doc.matterId); if (m && onNavigate) onNavigate('matter', doc.matterId); }}
                    style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '8px', borderRadius: T.radius.sm, cursor: 'pointer', background: T.color.bg.secondary, border: `1px solid ${T.color.border.light}` }}>
                    <span style={{ width: '24px', height: '24px', borderRadius: T.radius.sm, background: `${T.color.navy500}10`, color: T.color.navy500, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '11px', fontWeight: 700, flexShrink: 0 }}>◰</span>
                    <div>
                      <div style={{ fontSize: T.font.size.sm, fontWeight: T.font.weight.medium, color: T.color.text.primary }}>{doc.matter}</div>
                      <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{doc.matterId}</div>
                    </div>
                  </div>
                </div>
              )}
              {linkedTasks.length === 0 && linkedDeadlines.length === 0 && !doc.matterId && (
                <div style={{ padding: '20px', textAlign: 'center', color: T.color.text.tertiary, fontSize: T.font.size.sm }}>No linked items</div>
              )}
            </div>
          )}
        </div>

        {/* Actions footer */}
        <div style={{ padding: '12px 20px', borderTop: `1px solid ${T.color.border.light}`, display: 'flex', gap: '8px' }}>
          <button style={{ ...window.sharedStyles.btn, ...window.sharedStyles.btnPrimary, flex: 1, justifyContent: 'center' }}>Open Document</button>
          <button style={window.sharedStyles.btn}>Download</button>
          <button style={window.sharedStyles.btn}>Share</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DocDetailPanel, extColor, statusColor, confColor });
