// Reading section — single, three-card, Celtic Cross
const { useState: uR, useEffect: eR, useRef: rR } = React;

const SPREADS = {
  single: {
    label: 'Single Card Pull',
    description: 'One card for a quick daily insight',
    positions: [{ label: 'Your Card', x: 0, y: 0 }]
  },
  three: {
    label: 'Three Card Spread',
    description: 'Past · Present · Future',
    positions: [
      { label: 'Past', x: 0, y: 0 },
      { label: 'Present', x: 0, y: 0 },
      { label: 'Future', x: 0, y: 0 }
    ]
  },
  celtic: {
    label: 'Celtic Cross',
    description: 'The full 10-card reading',
    positions: [
      { label: '1. Present Situation' },
      { label: '2. The Challenge' },
      { label: '3. The Past' },
      { label: '4. The Future' },
      { label: '5. Above / Conscious' },
      { label: '6. Below / Subconscious' },
      { label: '7. Your Approach' },
      { label: '8. External Influences' },
      { label: '9. Hopes & Fears' },
      { label: '10. Outcome' }
    ]
  }
};

window.ReadingSection = function ReadingSection({ cards }) {
  const [spread, setSpread] = uR(null);
  const [drawn, setDrawn] = uR([]);
  const [shuffling, setShuffling] = uR(false);
  const [phase, setPhase] = uR('choose'); // choose | stage | complete

  const startSpread = (key) => {
    const s = SPREADS[key];
    const shuffled = [...cards].sort(() => Math.random() - 0.5);
    const picked = shuffled.slice(0, s.positions.length).map(c => ({
      card: c, reversed: Math.random() < 0.25, flipped: false
    }));
    setSpread(key);
    setDrawn(picked);
    setShuffling(true);
    setPhase('stage');
    setTimeout(() => setShuffling(false), 1400);
  };

  const flipCard = (idx) => {
    setDrawn(d => {
      const next = [...d];
      if (!next[idx].flipped) {
        next[idx] = { ...next[idx], flipped: true };
        burstParticles(idx);
      }
      // check all flipped
      if (next.every(x => x.flipped)) setPhase('complete');
      return next;
    });
  };

  const reset = () => {
    setSpread(null); setDrawn([]); setPhase('choose');
  };

  const burstParticles = (idx) => {
    const slot = document.querySelector(`[data-slot="${idx}"]`);
    if (!slot) return;
    for (let i = 0; i < 18; i++) {
      const p = document.createElement('div');
      p.className = 'burst-particle';
      const ang = (i / 18) * Math.PI * 2;
      const dist = 60 + Math.random() * 40;
      p.style.setProperty('--dx', `calc(-50% + ${Math.cos(ang) * dist}px)`);
      p.style.setProperty('--dy', `calc(-50% + ${Math.sin(ang) * dist}px)`);
      p.style.animationDelay = (Math.random() * 0.2) + 's';
      slot.appendChild(p);
      setTimeout(() => p.remove(), 1500);
    }
  };

  return React.createElement('section', { className: 'reading-section section' },
    React.createElement('h3', { className: 'section-title' }, 'Get a Reading'),
    phase === 'choose' && React.createElement('div', null,
      React.createElement('p', { style: { fontStyle: 'italic', maxWidth: 640, margin: '0 auto', color: 'rgba(239,230,211,0.8)' } },
        'Breathe. Hold your question in mind. Then choose how the cards shall speak.'),
      React.createElement('div', { className: 'spread-options' },
        Object.entries(SPREADS).map(([k, s]) =>
          React.createElement('div', { key: k, className: 'spread-option', onClick: () => startSpread(k) },
            React.createElement('h4', null, s.label),
            React.createElement('p', null, s.description)
          )
        )
      )
    ),
    phase !== 'choose' && spread && React.createElement(SpreadStage, {
      spreadKey: spread, drawn, shuffling, onFlip: flipCard, phase, onReset: reset
    })
  );
};

function SpreadStage({ spreadKey, drawn, shuffling, onFlip, phase, onReset }) {
  const positions = SPREADS[spreadKey].positions;
  const isCeltic = spreadKey === 'celtic';

  return React.createElement('div', { className: 'reading-stage' },
    React.createElement('div', {
      style: { display: 'flex', gap: '1rem', justifyContent: 'center', marginBottom: '1.5rem', flexWrap: 'wrap' }
    },
      React.createElement('span', {
        style: { fontFamily: 'var(--font-mystic)', color: 'var(--gold)', letterSpacing: '0.2em', textTransform: 'uppercase', fontSize: '0.9rem' }
      }, SPREADS[spreadKey].label),
      React.createElement('button', { className: 'icon-btn', onClick: onReset }, '↺ New Reading')
    ),
    shuffling && React.createElement('p', {
      style: { textAlign: 'center', fontStyle: 'italic', color: 'var(--gold-bright)', letterSpacing: '0.15em' }
    }, '✦ The cards are shuffling… ✦'),
    !shuffling && React.createElement('p', {
      style: { textAlign: 'center', fontStyle: 'italic', color: 'rgba(239,230,211,0.7)', marginBottom: '1.5rem' }
    }, phase === 'complete' ? 'The reading is revealed below ↓' : 'Click each card to reveal its message'),
    isCeltic
      ? React.createElement(CelticGrid, { drawn, positions, onFlip, shuffling })
      : React.createElement(LinearGrid, { drawn, positions, onFlip, shuffling }),
    phase === 'complete' && React.createElement(Interpretation, { drawn, positions })
  );
}

function LinearGrid({ drawn, positions, onFlip, shuffling }) {
  return React.createElement('div', { className: 'reading-grid' },
    positions.map((pos, i) => React.createElement(ReadingSlot, {
      key: i, idx: i, pos, drawn: drawn[i], onFlip, shuffling
    }))
  );
}

function CelticGrid({ drawn, positions, onFlip, shuffling }) {
  // Celtic cross layout: positions 0-5 form cross, 6-9 form right column
  const layout = [
    { i: 0, col: 2, row: 2 }, // center
    { i: 1, col: 2, row: 2, rotate: 90, offset: true }, // crossing
    { i: 2, col: 2, row: 3 }, // below
    { i: 3, col: 1, row: 2 }, // left (past)
    { i: 4, col: 2, row: 1 }, // top
    { i: 5, col: 3, row: 2 }, // right (future)
    { i: 6, col: 4, row: 4 },
    { i: 7, col: 4, row: 3 },
    { i: 8, col: 4, row: 2 },
    { i: 9, col: 4, row: 1 },
  ];
  return React.createElement('div', {
    className: 'celtic-grid',
    style: {
      display: 'grid',
      gridTemplateColumns: 'repeat(4, 120px)',
      gridTemplateRows: 'repeat(4, 190px)',
      gap: '0.8rem',
      justifyContent: 'center',
      margin: '1.5rem auto',
      position: 'relative'
    }
  },
    layout.map(L => React.createElement('div', {
      key: L.i,
      style: {
        gridColumn: L.col, gridRow: L.row,
        position: 'relative',
        transform: L.rotate ? `rotate(${L.rotate}deg) translate(0, ${L.offset ? '8px' : '0'})` : 'none',
        zIndex: L.rotate ? 2 : 1,
      }
    },
      React.createElement(ReadingSlot, {
        idx: L.i,
        pos: positions[L.i],
        drawn: drawn[L.i],
        onFlip,
        shuffling,
        compact: true
      })
    ))
  );
}

function ReadingSlot({ idx, pos, drawn, onFlip, shuffling, compact }) {
  if (!drawn) return null;
  return React.createElement('div', { className: 'reading-slot', 'data-slot': idx, style: compact ? { width: 'auto' } : null },
    !compact && React.createElement('div', { className: 'slot-label' }, pos.label),
    React.createElement('div', {
      className: 'mini-card' + (drawn.flipped ? ' flipped' : ' drawable') + (drawn.reversed ? ' reversed' : ''),
      onClick: () => !shuffling && !drawn.flipped && onFlip(idx),
      style: {
        opacity: shuffling ? 0 : 1,
        transform: shuffling ? `translateY(-${20 + idx * 4}px) rotate(${(idx % 2 === 0 ? 1 : -1) * (10 + idx * 2)}deg)` : '',
        transition: `all ${shuffling ? 0.8 + idx * 0.05 : 0.5}s cubic-bezier(.3, .9, .3, 1)`,
      }
    },
      React.createElement('div', { className: 'mini-card-inner' },
        React.createElement('div', { className: 'back' }, React.createElement(window.CardBack)),
        React.createElement('div', { className: 'front' },
          React.createElement('div', { className: 'card-face', style: { padding: '6px 4px' } },
            React.createElement('div', { className: 'card-art' }, React.createElement(window.CardArt, { card: drawn.card })),
            React.createElement('div', { className: 'card-name', style: { fontSize: '0.65rem' } }, drawn.card.name)
          )
        )
      )
    ),
    compact && React.createElement('div', { className: 'slot-label', style: { fontSize: '0.6rem', marginTop: '0.3rem', minHeight: 'auto' } }, pos.label)
  );
}

function Interpretation({ drawn, positions }) {
  return React.createElement('div', { className: 'reading-interp' },
    React.createElement('h3', {
      style: { fontFamily: 'var(--font-mystic)', color: 'var(--gold-bright)', letterSpacing: '0.2em', textAlign: 'center', marginBottom: '1.5rem' }
    }, '✦  Your Reading  ✦'),
    drawn.map((d, i) => {
      const reading = d.reversed ? d.card.reversed : d.card.upright;
      return React.createElement('div', { key: i, className: 'interp-block' },
        React.createElement('h4', null,
          positions[i].label + ' — ', React.createElement('span', { style: { color: 'var(--parchment)', fontFamily: 'var(--font-name)' } }, d.card.name)
        ),
        React.createElement('div', null,
          React.createElement('span', { className: 'pos' }, d.reversed ? 'Reversed' : 'Upright'),
          React.createElement('span', { style: { fontStyle: 'italic', color: 'rgba(239,230,211,0.7)' } }, d.card.keywords.slice(0, 3).join(' · '))
        ),
        React.createElement('p', null, reading.general),
        React.createElement('p', { style: { marginTop: '0.5rem', color: 'rgba(244,208,111,0.9)', fontStyle: 'italic' } }, '✦ ' + reading.advice)
      );
    })
  );
}
