/* RC-PAGE-031 — Pivot resolver.
   Encodes how dimension pairs relate (1:1, 1:N parent→child, N:1 child→parent, N:N crosstab),
   and exposes resolvePivot(orderedDims) so the View By picker can preview the resolution strategy.

   Relationship grammar (relative to an ordered pair A → B, A outer, B inner):
   - 'child'   — B is a child/sub-attribute of A (1 A has N Bs). Natural nesting.
                 e.g. Brand → ASIN, Campaign → Ad Group, Country → Marketplace.
   - 'parent'  — B is a parent of A (N As share 1 B). The nesting inverts: we'll
                 still render A → B but each B header is redundant. We warn.
   - 'peer'    — A and B are independent attributes of the same row (1 ASIN has 1 Category
                 AND 1 Brand — a row can belong to both). Rendered as crosstab or flat group.
   - 'cross'   — A and B are fully many-to-many (ASIN × Keyword, SKU × Marketplace). Expected
                 and fine; the table pivots.

   Registry is intentionally small — covers the dims we actually ship. Unknowns fall back
   to 'cross' (safe default: assume many-to-many).
*/

const DIM_HIERARCHY = {
  // Retail
  'Brand':       { children: ['ASIN', 'SKU', 'Parent ASIN'], parents: [] },
  'Parent ASIN': { children: ['ASIN'], parents: ['Brand', 'Category'] },
  'ASIN':        { children: ['SKU'], parents: ['Parent ASIN', 'Brand', 'Category'] },
  'SKU':         { children: [], parents: ['ASIN', 'Brand'] },
  'Category':    { children: ['Subcategory', 'Brand', 'Parent ASIN', 'ASIN'], parents: [] },
  'Subcategory': { children: ['ASIN', 'Brand'], parents: ['Category'] },
  'Marketplace': { children: [], parents: ['Country'] },
  'Country':     { children: ['Marketplace'], parents: [] },
  // SP Ads
  'Campaign':   { children: ['Ad Group', 'Keyword', 'Targeting', 'Placement'], parents: ['Portfolio'] },
  'Portfolio':  { children: ['Campaign'], parents: [] },
  'Ad Group':   { children: ['Keyword', 'Targeting', 'Ad'], parents: ['Campaign'] },
  'Keyword':    { children: [], parents: ['Ad Group', 'Campaign'] },
  'Targeting':  { children: [], parents: ['Ad Group', 'Campaign'] },
  'Placement':  { children: [], parents: ['Campaign'] },
  'Ad':         { children: [], parents: ['Ad Group'] },
  'Match Type': { children: [], parents: ['Keyword'] },
  // Peer attributes — orthogonal facets of a product
  'Color':   { peers: ['Size', 'Material'], children: [], parents: [] },
  'Size':    { peers: ['Color', 'Material'], children: [], parents: [] },
  'Material':{ peers: ['Color', 'Size'], children: [], parents: [] },
};

function relation(a, b) {
  if (a === b) return 'identity';
  const A = DIM_HIERARCHY[a];
  const B = DIM_HIERARCHY[b];
  if (!A || !B) return 'cross';
  if (A.children && A.children.includes(b)) return 'child';
  if (A.parents  && A.parents.includes(b))  return 'parent';
  if (A.peers    && A.peers.includes(b))    return 'peer';
  return 'cross';
}

/* resolvePivot([A, B, C, ...]) — returns a resolution plan and an array of per-chip
   indicators the picker can render. Per-chip indicator is computed relative to the
   PREVIOUS chip in the chain (i=0 has no indicator since there's no outer dim yet). */
function resolvePivot(ordered) {
  if (!Array.isArray(ordered) || ordered.length === 0) {
    return { strategy: 'empty', chips: [], warnings: [] };
  }
  const chips = ordered.map((dim, i) => {
    if (i === 0) return { dim, relation: 'root', tone: 'neutral', label: 'Outer group' };
    const prev = ordered[i - 1];
    const rel = relation(prev, dim);
    switch (rel) {
      case 'child':
        return { dim, relation: rel, tone: 'good', label: `Nested under ${prev}`,
                 detail: `Each ${prev} expands into its ${dim}s.` };
      case 'parent':
        return { dim, relation: rel, tone: 'warn', label: `Parent of ${prev}`,
                 detail: `${dim} is higher than ${prev} — the nesting is inverted. Consider swapping.` };
      case 'peer':
        return { dim, relation: rel, tone: 'info', label: `Crosstab with ${prev}`,
                 detail: `${dim} and ${prev} are independent attributes. Shown as a crosstab.` };
      case 'identity':
        return { dim, relation: rel, tone: 'warn', label: 'Duplicate dimension',
                 detail: 'Same dimension twice — the second level will collapse.' };
      case 'cross':
      default:
        return { dim, relation: rel, tone: 'neutral', label: `Pivoted with ${prev}`,
                 detail: `${dim} × ${prev} pivot — every combination will appear as its own row.` };
    }
  });
  const warnings = chips.filter(c => c.tone === 'warn').map(c => c.detail);
  // Strategy summary for the picker footer.
  let strategy = 'nested';
  if (ordered.length === 1) strategy = 'single';
  else if (chips.slice(1).every(c => c.relation === 'child')) strategy = 'nested';
  else if (chips.slice(1).every(c => c.relation === 'cross' || c.relation === 'peer')) strategy = 'crosstab';
  else strategy = 'mixed';
  return { strategy, chips, warnings };
}

/* Badge glyph + color per relation. Kept tiny so it fits beside the chip number. */
const RELATION_STYLES = {
  root:     { glyph: '·',  tint: 'var(--rc-text-mute)'   , label: 'Outer' },
  child:    { glyph: '↳',  tint: 'var(--rc-green)'       , label: 'Nested' },
  parent:   { glyph: '↰',  tint: 'var(--rc-amber)'       , label: 'Inverted' },
  peer:     { glyph: '⊞',  tint: 'var(--rc-chart-2)'     , label: 'Crosstab' },
  cross:    { glyph: '×',  tint: 'var(--rc-chart-1)'     , label: 'Pivot' },
  identity: { glyph: '=',  tint: 'var(--rc-amber)'       , label: 'Dup' },
};

Object.assign(window, { DIM_HIERARCHY, resolvePivot, RELATION_STYLES });
