// mandala.jsx — 5-ring natal mandala (3 visual variants)
// Rings (outer → inner):
//   5 Òrìṣà (outermost) · 4 Manāzil · 3 Baḥrä · 2 Ifá · 1 Sba (innermost)
// Click any sector → scroll to that layer's section.

const DECAN_HI = ["𓇳","𓃀","𓇼","𓈖","𓅓","𓎡","𓏏","𓊪","𓂀","𓋴","𓃹","𓆓"];
const GEEZ_NUMS = ["፩","፪","፫","፬","፭","፮","፯","፰","፱","፲","፲፩","፲፪"];
const ARABIC_LETTERS = ["ا","ب","ت","ث","ج","ح","خ","د","ذ","ر","ز","س"];
const COWRIE = "⌣";

function polar(cx, cy, r, deg){
  const rad = (deg - 90) * Math.PI / 180;
  return [cx + r*Math.cos(rad), cy + r*Math.sin(rad)];
}
function arcPath(cx, cy, rOuter, rInner, a0, a1){
  const [x1,y1] = polar(cx, cy, rOuter, a0);
  const [x2,y2] = polar(cx, cy, rOuter, a1);
  const [x3,y3] = polar(cx, cy, rInner, a1);
  const [x4,y4] = polar(cx, cy, rInner, a0);
  const large = (a1 - a0) > 180 ? 1 : 0;
  return `M ${x1} ${y1} A ${rOuter} ${rOuter} 0 ${large} 1 ${x2} ${y2} L ${x3} ${y3} A ${rInner} ${rInner} 0 ${large} 0 ${x4} ${y4} Z`;
}

const PLANETS = [
  { id: "sun",     sym: "☉", label: "SUN"  },
  { id: "moon",    sym: "☽", label: "MOON" },
  { id: "mercury", sym: "☿", label: "MERC" },
  { id: "venus",   sym: "♀", label: "VEN"  },
  { id: "mars",    sym: "♂", label: "MARS" },
  { id: "jupiter", sym: "♃", label: "JUP"  },
  { id: "saturn",  sym: "♄", label: "SAT"  },
  { id: "asc",     sym: "Asc", label: "ASC"  }
];

function Mandala({ chart, style, breathing, onHover, onLeave, drawOn }) {
  // style: 'dense' | 'austere' | 'lithograph'
  const cx = 400, cy = 400;
  const R = {
    r5o: 390, r5i: 350,  // Orisha
    r4o: 350, r4i: 300,  // Manazil
    r3o: 300, r3i: 250,  // Bahere
    r2o: 250, r2i: 200,  // Ifa
    r1o: 200, r1i: 110,  // Sba
    center: 100
  };

  const handleEnter = (e, data) => onHover && onHover(e, data);
  const scrollToLayer = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  // Dense = heavier fills/textures; Austere = thin lines only; Lithograph = mixed textures
  const isDense = style === 'dense';
  const isAust  = style === 'austere';
  const isLith  = style === 'lithograph';

  // Ring 1: Sba — 36 decans, 10° each
  const sbaSectors = Array.from({length: 36}, (_, i) => {
    const a0 = i*10, a1 = a0+10;
    const mid = a0 + 5;
    const [tx, ty] = polar(cx, cy, (R.r1o + R.r1i)/2, mid);
    return (
      <g key={`sba-${i}`}>
        <path
          d={arcPath(cx, cy, R.r1o, R.r1i, a0, a1)}
          fill={isDense ? (i%2 ? "rgba(212,175,55,.06)" : "rgba(212,175,55,.02)") : (isLith && i%3===0 ? "rgba(212,175,55,.04)" : "transparent")}
          stroke="rgba(212,175,55,.35)"
          strokeWidth={isAust ? 0.4 : 0.6}
          className="sba-sector"
          onClick={() => scrollToLayer('sba')}
          onMouseEnter={(e) => handleEnter(e, { name: `Decan ${i+1}`, lit: `${a0}°–${a1}°`, gloss: `Sba · ring of 36 ten-degree decans of the ecliptic` })}
          onMouseLeave={onLeave}
          style={{ cursor: 'pointer' }}
        />
        {(isDense || isLith) && i%3===0 && (
          <text x={tx} y={ty+6} textAnchor="middle" fontFamily="var(--hieroglyph)" fontSize="14" fill="rgba(212,175,55,.7)" pointerEvents="none">
            {DECAN_HI[i%12]}
          </text>
        )}
      </g>
    );
  });

  // Ring 2: Ifá — 16 major odù (each is 22.5°)
  const ifaSectors = Array.from({length: 16}, (_, i) => {
    const a0 = i*22.5, a1 = a0+22.5;
    const mid = a0 + 11.25;
    const [tx, ty] = polar(cx, cy, (R.r2o + R.r2i)/2, mid);
    // Draw binary 4-mark pattern for each sector
    const bits = [(i>>3)&1, (i>>2)&1, (i>>1)&1, i&1];
    return (
      <g key={`ifa-${i}`}>
        <path
          d={arcPath(cx, cy, R.r2o, R.r2i, a0, a1)}
          fill={isDense ? "rgba(245,241,230,.025)" : "transparent"}
          stroke="rgba(212,175,55,.3)"
          strokeWidth={isAust ? 0.4 : 0.6}
          onClick={() => scrollToLayer('ifa')}
          onMouseEnter={(e) => handleEnter(e, { name: `Odù ${i+1}/16`, lit: `binary ${bits.join('')}`, gloss: `Ifá · 256-figure divination corpus · 16 major patterns` })}
          onMouseLeave={onLeave}
          style={{ cursor: 'pointer' }}
        />
        {/* 4-mark binary rendered as tiny rects */}
        <g transform={`translate(${tx}, ${ty})`} pointerEvents="none">
          {bits.map((b, j) => (
            b === 1
              ? <rect key={j} x={-6} y={-14 + j*7} width="12" height="3" fill="rgba(212,175,55,.75)" />
              : (<g key={j}>
                  <rect x={-6} y={-14 + j*7} width="4" height="3" fill="rgba(212,175,55,.75)" />
                  <rect x={ 2} y={-14 + j*7} width="4" height="3" fill="rgba(212,175,55,.75)" />
                </g>)
          ))}
        </g>
      </g>
    );
  });

  // Ring 3: Baḥrä — 12 liturgical months, Ge'ez numerals
  const bahereSectors = Array.from({length: 12}, (_, i) => {
    const a0 = i*30, a1 = a0+30;
    const mid = a0 + 15;
    const [tx, ty] = polar(cx, cy, (R.r3o + R.r3i)/2, mid);
    const redAccent = isDense && (i===0 || i===3 || i===7);
    return (
      <g key={`bah-${i}`}>
        <path
          d={arcPath(cx, cy, R.r3o, R.r3i, a0, a1)}
          fill={redAccent ? "rgba(178,58,58,.08)" : (isDense ? "rgba(245,241,230,.02)" : "transparent")}
          stroke={redAccent ? "rgba(178,58,58,.55)" : "rgba(212,175,55,.3)"}
          strokeWidth={isAust ? 0.4 : 0.6}
          onClick={() => scrollToLayer('bahere')}
          onMouseEnter={(e) => handleEnter(e, { name: `Month ${i+1}`, lit: GEEZ_NUMS[i], gloss: `Baḥrä Ḥasab · Ethiopian liturgical reckoning` })}
          onMouseLeave={onLeave}
          style={{ cursor: 'pointer' }}
        />
        <text x={tx} y={ty+6} textAnchor="middle" fontFamily="var(--ethiopic)" fontSize="16" fill={redAccent ? "#B23A3A" : "rgba(212,175,55,.75)"} pointerEvents="none">
          {GEEZ_NUMS[i]}
        </text>
      </g>
    );
  });

  // Ring 4: Manāzil — 28 lunar mansions, arranged with tiny crescents
  const manzilSectors = Array.from({length: 28}, (_, i) => {
    const a0 = (360/28)*i, a1 = a0 + 360/28;
    const mid = a0 + (360/56);
    const [tx, ty] = polar(cx, cy, (R.r4o + R.r4i)/2, mid);
    return (
      <g key={`man-${i}`}>
        <path
          d={arcPath(cx, cy, R.r4o, R.r4i, a0, a1)}
          fill={isDense && i%2===0 ? "rgba(212,175,55,.04)" : "transparent"}
          stroke="rgba(212,175,55,.32)"
          strokeWidth={isAust ? 0.4 : 0.6}
          onClick={() => scrollToLayer('manzil')}
          onMouseEnter={(e) => handleEnter(e, { name: `Manzil ${i+1}`, lit: ARABIC_LETTERS[i%12], gloss: `Manāzil al-Qamar · 28 lunar mansions · Indian Ocean navigation` })}
          onMouseLeave={onLeave}
          style={{ cursor: 'pointer' }}
        />
        {(isDense || isLith) && (
          // little crescent
          <g transform={`translate(${tx} ${ty})`} pointerEvents="none">
            <path d="M -4 -5 A 5 5 0 1 0 -4 5 A 3.5 3.5 0 1 1 -4 -5 Z" fill="rgba(212,175,55,.55)"/>
          </g>
        )}
      </g>
    );
  });

  // Ring 5: Òrìṣà — 7 day-guardians (for weekdays), split sectors
  const ORISHA_DAYS = [
    { nm: "Èṣù",      day: "Sun" },
    { nm: "Ọbàtálá",  day: "Mon" },
    { nm: "Ògún",     day: "Tue" },
    { nm: "Ọbàtálá",  day: "Wed" },
    { nm: "Ṣàngó",    day: "Thu" },
    { nm: "Ọ̀ṣun",     day: "Fri" },
    { nm: "Babalú",   day: "Sat" }
  ];
  const orishaSectors = ORISHA_DAYS.map((o, i) => {
    const a0 = (360/7)*i, a1 = a0 + 360/7;
    const mid = a0 + (360/14);
    const [tx, ty] = polar(cx, cy, (R.r5o + R.r5i)/2, mid);
    return (
      <g key={`ori-${i}`}>
        <path
          d={arcPath(cx, cy, R.r5o, R.r5i, a0, a1)}
          fill={isDense ? (i%2 ? "rgba(212,175,55,.06)" : "transparent") : "transparent"}
          stroke="rgba(212,175,55,.4)"
          strokeWidth={isAust ? 0.5 : 0.8}
          onClick={() => scrollToLayer('orisha')}
          onMouseEnter={(e) => handleEnter(e, { name: o.nm, lit: o.day, gloss: `Òrìṣà · day-guardian lineage · diasporic re-weave` })}
          onMouseLeave={onLeave}
          style={{ cursor: 'pointer' }}
        />
        <text x={tx} y={ty-3} textAnchor="middle" fontFamily="var(--serif)" fontStyle="italic" fontSize="13" fill="rgba(245,241,230,.85)" pointerEvents="none" letterSpacing="-0.01em">
          {o.nm}
        </text>
        <text x={tx} y={ty+12} textAnchor="middle" fontFamily="var(--mono)" fontSize="8" fill="rgba(212,175,55,.65)" pointerEvents="none" letterSpacing="0.12em">
          {o.day.toUpperCase()}
        </text>
      </g>
    );
  });

  // Planet dots on Ring 1 (decans)
  const planetDots = PLANETS.map((p) => {
    const lon = chart.absolute_longitudes[p.id];
    if (lon === undefined) return null;
    const rDot = (R.r1o + R.r1i) / 2;
    const [px, py] = polar(cx, cy, rDot, lon);
    const [lx, ly] = polar(cx, cy, rDot - 32, lon);
    return (
      <g key={`pl-${p.id}`}>
        <circle cx={px} cy={py} r="5" fill="var(--gold)" stroke="var(--navy)" strokeWidth="1.5"/>
        <circle cx={px} cy={py} r="10" fill="none" stroke="rgba(212,175,55,.3)" strokeWidth="0.5"/>
        <text x={lx} y={ly+4} textAnchor="middle" fontFamily="var(--serif)" fontSize="14" fill="var(--gold)" pointerEvents="none">
          {p.sym}
        </text>
      </g>
    );
  });

  // Zodiac / 12-gate grid lines
  const gridLines = Array.from({length: 12}, (_, i) => {
    const a = i*30;
    const [x1,y1] = polar(cx, cy, R.center, a);
    const [x2,y2] = polar(cx, cy, R.r5o, a);
    return <line key={`gl-${i}`} x1={x1} y1={y1} x2={x2} y2={y2} stroke="rgba(245,241,230,.06)" strokeWidth="0.5"/>;
  });

  // Cardinal markers (12 / 3 / 6 / 9 o'clock)
  const cardinals = [
    { a: 0,   label: "ASC" },
    { a: 90,  label: "DSC" },
    { a: 180, label: "IC" },
    { a: 270, label: "MC" }
  ].map((c, i) => {
    const [x, y] = polar(cx, cy, R.r5o + 18, c.a);
    return (
      <text key={i} x={x} y={y+4} textAnchor="middle" fontFamily="var(--mono)" fontSize="9" fill="var(--gold)" letterSpacing="0.18em">{c.label}</text>
    );
  });

  return (
    <svg viewBox="0 0 800 820" className={`mandala-svg ${breathing ? 'breathing' : ''}`}>
      <defs>
        <radialGradient id="mg-core" cx="50%" cy="50%">
          <stop offset="0%" stopColor="rgba(212,175,55,.35)"/>
          <stop offset="100%" stopColor="rgba(212,175,55,0)"/>
        </radialGradient>
        <radialGradient id="mg-lith" cx="50%" cy="50%">
          <stop offset="0%" stopColor="rgba(19,27,46,0)"/>
          <stop offset="90%" stopColor="rgba(212,175,55,.08)"/>
          <stop offset="100%" stopColor="rgba(212,175,55,0)"/>
        </radialGradient>
      </defs>

      {isLith && <circle cx={cx} cy={cy} r={R.r5o} fill="url(#mg-lith)"/>}

      <g className="ring-group" style={{ transformBox: 'fill-box', transformOrigin: 'center' }}>
        {/* Grid lines behind */}
        {gridLines}

        {/* Rings outer → inner so hovers stack sensibly */}
        <g>{orishaSectors}</g>
        <g>{manzilSectors}</g>
        <g>{bahereSectors}</g>
        <g>{ifaSectors}</g>
        <g>{sbaSectors}</g>

        {/* Ring dividers */}
        {[R.r5o, R.r5i, R.r4i, R.r3i, R.r2i, R.r1i].map((r, i) => (
          <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke="rgba(212,175,55,.5)" strokeWidth={i===0 ? 1.2 : 0.6}/>
        ))}

        {/* Planet dots */}
        {planetDots}

        {/* Center */}
        <circle cx={cx} cy={cy} r={R.center} fill="url(#mg-core)"/>
        <circle cx={cx} cy={cy} r={R.center} fill="none" stroke="rgba(212,175,55,.55)" strokeWidth="0.8"/>
        <circle cx={cx} cy={cy} r="4" fill="var(--gold)"/>
        <circle cx={cx} cy={cy} r="12" fill="none" stroke="var(--gold)" strokeWidth="0.8"/>
        <text x={cx} y={cy-40} textAnchor="middle" fontFamily="var(--mono)" fontSize="9" fill="var(--gold)" letterSpacing="0.22em">⊕ BORN</text>
        <text x={cx} y={cy+52} textAnchor="middle" fontFamily="var(--serif)" fontStyle="italic" fontSize="13" fill="rgba(245,241,230,.78)">{chart.label.toLowerCase()}</text>
        <text x={cx} y={cy+68} textAnchor="middle" fontFamily="var(--mono)" fontSize="8" fill="rgba(245,241,230,.42)" letterSpacing="0.12em">{chart.birthIso}</text>

        {/* Cardinals */}
        {cardinals}

        {/* 12-o'clock ring labels in native script */}
        <text x={cx} y={R.center-32} textAnchor="middle" fontFamily="var(--hieroglyph)" fontSize="14" fill="var(--gold)">𓋴𓃀</text>
        <text x={cx} y={R.r1i-8}  textAnchor="middle" fontFamily="var(--mono)" fontSize="8" fill="rgba(212,175,55,.7)" letterSpacing="0.2em">SBA</text>
        <text x={cx} y={R.r2i-8}  textAnchor="middle" fontFamily="var(--mono)" fontSize="8" fill="rgba(212,175,55,.7)" letterSpacing="0.2em">IFÁ</text>
        <text x={cx} y={R.r3i-8}  textAnchor="middle" fontFamily="var(--ethiopic)" fontSize="11" fill="rgba(212,175,55,.8)">ባሕረ</text>
        <text x={cx} y={R.r4i-8}  textAnchor="middle" fontFamily="var(--arabic)" fontSize="12" fill="rgba(212,175,55,.8)">منازل</text>
        <text x={cx} y={R.r5i-8}  textAnchor="middle" fontFamily="var(--mono)" fontSize="8" fill="rgba(212,175,55,.8)" letterSpacing="0.2em">ÒRÌṢÀ</text>
      </g>
    </svg>
  );
}

window.Mandala = Mandala;
