// TIRADAS · TAROT DEL PENSAMIENTO COMPLEJO (bilingüe ES/EN)
// Dos tiradas signature: una mínima (1 carta) y una de retroalimentación (3 cartas).

const SPREADS = [
  {
    id: 'principio',
    name:   'EL PRINCIPIO',  nameEn: 'THE PRINCIPLE',
    subtitle:   'Una carta · Diagnóstico veloz',
    subtitleEn: 'One card · Swift diagnosis',
    intro:   'Una sola lente para mirar la situación. Útil cuando no buscas resolver — buscas nombrar. La carta no responde la pregunta: la reformula desde el principio que la enmarca.',
    introEn: 'A single lens to look at the situation. Useful when you do not seek to solve — you seek to name. The card does not answer the question: it reframes it from the principle that contains it.',
    positions: [
      { id: 'principio',
        label:   'PRINCIPIO', labelEn: 'PRINCIPLE',
        role:    'La lente desde la cual leer todo lo demás',
        roleEn:  'The lens from which to read everything else',
        x: 0.5, y: 0.5 },
    ],
    edges: [],
    constellation:   'Si es Mayor, el momento toca un arquetipo: estás frente a un principio rector, no una situación. Si es Menor, lo que ocurre se juega en lo concreto del dominio que aparece — léelo en clave situacional.',
    constellationEn: 'If a Major, the moment touches an archetype: you face a governing principle, not a situation. If a Minor, what occurs plays out in the concrete of the domain that appears — read it in situational key.',
    forcedSuits: null,
  },
  {
    id: 'bucle',
    name:   'EL BUCLE',  nameEn: 'THE LOOP',
    subtitle:   'Tres cartas · Retroalimentación',
    subtitleEn: 'Three cards · Feedback',
    intro:   'La salida vuelve como entrada y modifica la siguiente salida. Lo que produces hoy se vuelve la condición de mañana. Esta tirada diagnostica el bucle que ya está operando — para corregirlo, intensificarlo o cortarlo.',
    introEn: 'The output returns as input and modifies the next output. What you produce today becomes the condition of tomorrow. This spread diagnoses the loop already operating — to correct, intensify, or cut it.',
    positions: [
      { id: 'salida',
        label:   'SALIDA',        labelEn: 'OUTPUT',
        role:    'Qué produces ahora en el sistema',
        roleEn:  'What you produce now in the system',
        x: 0.18, y: 0.5 },
      { id: 'retorno',
        label:   'RETORNO',       labelEn: 'RETURN',
        role:    'Cómo regresa esa salida al sistema',
        roleEn:  'How that output returns to the system',
        x: 0.5,  y: 0.5 },
      { id: 'modificacion',
        label:   'MODIFICACIÓN',  labelEn: 'MODIFICATION',
        role:    'Qué cambia en la siguiente vuelta del bucle',
        roleEn:  'What changes in the next turn of the loop',
        x: 0.82, y: 0.5 },
    ],
    edges: [
      { from: 'salida', to: 'retorno' },
      { from: 'retorno', to: 'modificacion' },
      { from: 'modificacion', to: 'salida', curve: 'arc-bottom' },
    ],
    constellation:   'Si las tres cartas comparten palo, el bucle ya se cerró: estás en una dinámica que se sostiene a sí misma. Si una es Mayor, el ciclo toca un principio rector — no solo una situación.',
    constellationEn: 'If the three cards share a suit, the loop has already closed: you are in a dynamic that sustains itself. If one is Major, the cycle touches a governing principle — not just a situation.',
    forcedSuits: null,
  },
];

// ─── DRAW ────────────────────────────────────────────────────────────────
function _shuffle(arr) {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

function drawCards(spread) {
  const allCards = [
    ...MAJORS.map(m => ({...m, kind:'major', suit:'majors'})),
    ...MINORS,
  ];
  if (spread.forcedSuits) {
    return spread.forcedSuits.map(suitKey => {
      const pool = allCards.filter(c => c.suit === suitKey);
      return _shuffle(pool)[0];
    });
  }
  return _shuffle(allCards).slice(0, spread.positions.length);
}

// ─── PATTERNS ────────────────────────────────────────────────────────────
// Devuelve patrones BILINGÜES: cada uno { label:{es,en}, text:{es,en} }
function identifyPatterns(draws, spread) {
  if (!draws || draws.length === 0) return [];
  const patterns = [];

  // Conteo de Mayores
  const mayors = draws.filter(c => c.kind === 'major' || c.suit === 'majors');
  if (mayors.length >= 2) {
    patterns.push({
      label: { es: `${mayors.length} Mayores`, en: `${mayors.length} Majors` },
      text: {
        es: 'La tirada toca arquetipos rectores, no solo situaciones — la pregunta se juega en el plano del principio. Las menores describen cómo se vive lo que las mayores nombran.',
        en: 'The spread touches governing archetypes, not just situations — the question plays out on the plane of principle. The minors describe how what the majors name is lived.',
      },
    });
  } else if (mayors.length === 1) {
    const m = mayors[0];
    patterns.push({
      label: { es: '1 Mayor presente', en: '1 Major present' },
      text: {
        es: `${m.name} aporta el principio que ordena toda la lectura — léelo como clave de las menores.`,
        en: `${m.nameEn || m.name} provides the principle that orders the entire reading — read it as the key to the minors.`,
      },
    });
  } else {
    patterns.push({
      label: { es: 'Sin Mayores', en: 'No Majors' },
      text: {
        es: 'Toda la tirada vive en lo concreto: situaciones, gestos, operadores. Lo arquetípico está implícito — leelo en la combinatoria de los palos.',
        en: 'The whole spread lives in the concrete: situations, gestures, operators. The archetypal is implicit — read it in the combinatorics of the suits.',
      },
    });
  }

  // Palo dominante (entre las menores)
  const suitCounts = {};
  draws.filter(c => c.suit !== 'majors').forEach(c => {
    suitCounts[c.suit] = (suitCounts[c.suit] || 0) + 1;
  });
  const dominantEntry = Object.entries(suitCounts).sort((a,b)=>b[1]-a[1])[0];
  if (dominantEntry && dominantEntry[1] >= 3) {
    const suit = TAROT_SUITS[dominantEntry[0]];
    patterns.push({
      label: { es: `Dominio ${suit.es}`, en: `${suit.en} dominance` },
      text: {
        es: `${dominantEntry[1]} cartas de ${suit.es} — la situación pesa en ${suit.domain.toLowerCase()}.`,
        en: `${dominantEntry[1]} cards of ${suit.en} — the situation weighs in ${suit.domainEn.toLowerCase()}.`,
      },
    });
  } else if (dominantEntry && dominantEntry[1] === 2) {
    const suit = TAROT_SUITS[dominantEntry[0]];
    patterns.push({
      label: { es: `Eje ${suit.es}`, en: `${suit.en} axis` },
      text: {
        es: `Dos cartas de ${suit.es} marcan un eje conceptual — ${(suit.note||'').toLowerCase()}`,
        en: `Two cards of ${suit.en} mark a conceptual axis — ${(suit.noteEn||suit.note||'').toLowerCase()}`,
      },
    });
  }

  // Cartas-figura (cortes 11..14)
  const courts = draws.filter(c => c.kind === 'minor' && c.n >= 11);
  if (courts.length >= 2) {
    patterns.push({
      label: { es: `${courts.length} figuras`, en: `${courts.length} courts` },
      text: {
        es: 'Hay operadores activos: personas, agentes o roles que mueven la situación más que las circunstancias.',
        en: 'There are active operators: people, agents, or roles that move the situation more than the circumstances do.',
      },
    });
  }

  // Ases
  const aces = draws.filter(c => c.kind === 'minor' && c.n === 1);
  if (aces.length >= 1) {
    const plural = aces.length > 1;
    patterns.push({
      label: { es: `${aces.length} ${plural ? 'Ases' : 'As'}`,
               en: `${aces.length} ${plural ? 'Aces' : 'Ace'}` },
      text: {
        es: `Inicios: algo empieza ${plural ? 'en varios dominios' : 'en un dominio'} — semillas todavía sin desarrollo.`,
        en: `Beginnings: something starts ${plural ? 'in several domains' : 'in one domain'} — seeds still undeveloped.`,
      },
    });
  }

  return patterns;
}

Object.assign(window, { SPREADS, drawCards, identifyPatterns });
