// Feeling Wheel — SVG component
// Gottman/Willcox 6-core structure with secondary descriptors.
// Palette is derived from the Sanctuary Ridge sage family, slightly hue-shifted
// per core so the six are distinguishable without breaking the brand.

const WHEEL_PALETTE = {
  // [wedge bg, secondary tint target, text color]
  JOYFUL:   { core: "#D9C49A", text: "#3A2E12" },
  POWERFUL: { core: "#7E8C6A", text: "#1F2614" },
  PEACEFUL: { core: "#A8B69E", text: "#26301E" },
  SAD:      { core: "#7E8995", text: "#1A2128" },
  MAD:      { core: "#A87862", text: "#34170A" },
  SCARED:   { core: "#8C8595", text: "#221D2A" },
};

// Mix two hex colors. amount=0 returns a, 1 returns b.
function mixHex(a, b, amount) {
  const ar = parseInt(a.slice(1,3), 16), ag = parseInt(a.slice(3,5), 16), ab = parseInt(a.slice(5,7), 16);
  const br = parseInt(b.slice(1,3), 16), bg = parseInt(b.slice(3,5), 16), bb = parseInt(b.slice(5,7), 16);
  const m = (x,y) => Math.round(x + (y - x) * amount);
  return `rgb(${m(ar,br)}, ${m(ag,bg)}, ${m(ab,bb)})`;
}

function d2r(d) { return (d * Math.PI) / 180; }
function polar(cx, cy, r, deg) {
  const a = d2r(deg);
  return [cx + r * Math.cos(a), cy + r * Math.sin(a)];
}
// Path for an annular wedge between r1 and r2, from startDeg to endDeg (cw).
function annularWedge(cx, cy, r1, r2, startDeg, endDeg) {
  const [x1, y1] = polar(cx, cy, r2, startDeg);
  const [x2, y2] = polar(cx, cy, r2, endDeg);
  const [x3, y3] = polar(cx, cy, r1, endDeg);
  const [x4, y4] = polar(cx, cy, r1, startDeg);
  const large = endDeg - startDeg > 180 ? 1 : 0;
  return `M ${x1} ${y1} A ${r2} ${r2} 0 ${large} 1 ${x2} ${y2} L ${x3} ${y3} A ${r1} ${r1} 0 ${large} 0 ${x4} ${y4} Z`;
}

function FeelingWheel({
  size = 560,
  // "color" (multi-hue), "mono" (sage only), or "ink" (dark + cream)
  mode = "color",
  showCenter = true,
  centerTitle = "Feeling",
  centerSub = "Wheel",
  ring = "var(--sr-cream)", // stroke between wedges
}) {
  const cores = window.SR_CONTENT.emotions.cores;
  const cx = size / 2, cy = size / 2;

  // Radii (proportional)
  const rHub   = size * 0.085;   // empty center disc / title hub
  const rCore  = size * 0.27;    // outer of core ring
  const rSec   = size * 0.46;    // outer of secondary ring
  const rLblC  = (rHub + rCore) / 2;
  const rLblS  = (rCore + rSec) / 2;

  // Cream target for tinting
  const cream = "#ECE7DC";

  // Generate wedges
  const wedges = [];
  const labels = [];

  // Pre-computed mono ring (warm sage tints, evenly spaced around the wheel)
  const MONO_RING = ["#9AA68A", "#8B987C", "#A6AF98", "#7E8B75", "#94A286", "#B0B9A4"];

  cores.forEach((core, ci) => {
    const start = -90 + ci * 60;
    const end = start + 60;
    const pal = WHEEL_PALETTE[core.key];

    let coreFill, secFillBase, textColor;
    if (mode === "color") {
      coreFill    = pal.core;
      secFillBase = pal.core;
      textColor   = pal.text;
    } else if (mode === "mono") {
      coreFill    = MONO_RING[ci];
      secFillBase = coreFill;
      textColor   = "#1F2A1B";
    } else { // ink
      coreFill    = "#2E3829";
      secFillBase = "#6C7567";
      textColor   = cream;
    }

    // Core wedge
    wedges.push({
      d: annularWedge(cx, cy, rHub, rCore, start, end),
      fill: coreFill,
    });
    const cmid = (start + end) / 2;
    const [lx, ly] = polar(cx, cy, rLblC, cmid);
    labels.push({
      x: lx, y: ly,
      rot: cmid,
      text: core.key.charAt(0) + core.key.slice(1).toLowerCase(),
      kind: "core",
      color: textColor,
    });

    // Secondary wedges
    const span = 60 / core.descriptors.length;
    core.descriptors.forEach((desc, di) => {
      const s = start + di * span;
      const e = s + span;
      // alternating subtle tint within a core for readability
      const tintAmt = mode === "color" ? (0.55 + (di % 2) * 0.08)
                    : mode === "mono"  ? (0.60 + (di % 2) * 0.06)
                    : (0.0  + (di % 2) * 0.10);
      const fill = mixHex(secFillBase, cream, tintAmt);
      wedges.push({ d: annularWedge(cx, cy, rCore, rSec, s, e), fill });
      const m = (s + e) / 2;
      const [tx, ty] = polar(cx, cy, rLblS, m);
      labels.push({
        x: tx, y: ty, rot: m,
        text: desc,
        kind: "secondary",
        color: mode === "ink" ? "#2E3829" : textColor,
      });
    });
  });

  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size}
         style={{ display: "block" }} aria-label="Feeling Wheel">
      {/* Outer ring stroke */}
      <circle cx={cx} cy={cy} r={rSec + 0.5} fill="none" stroke="var(--sr-sage-haze)" strokeWidth="0.75" />

      {/* Wedges */}
      <g>
        {wedges.map((w, i) => (
          <path key={i} d={w.d} fill={w.fill} stroke={ring} strokeWidth="1.2" strokeLinejoin="round" />
        ))}
      </g>

      {/* Labels */}
      {labels.map((l, i) => {
        const flip = l.rot > 90 && l.rot < 270;
        const rot = flip ? l.rot + 180 : l.rot;
        // Core labels: scale down for longer words so POWERFUL / PEACEFUL fit
        // inside their wedge arcs at the inner-ring radius.
        const coreFsBase = l.kind === "core"
          ? (l.text.length >= 7 ? size * 0.022 : size * 0.028)
          : size * 0.017;
        const fs = coreFsBase;
        const fw = l.kind === "core" ? 600 : 500;
        const ls = l.kind === "core"
          ? (l.text.length >= 7 ? "0.08em" : "0.16em")
          : "0.02em";
        const txt = l.kind === "core" ? l.text.toUpperCase() : l.text;
        return (
          <text key={`l${i}`} x={l.x} y={l.y}
                fill={l.color}
                fontFamily='"Montserrat", system-ui, sans-serif'
                fontSize={fs} fontWeight={fw} letterSpacing={ls}
                textAnchor="middle" dominantBaseline="central"
                transform={`rotate(${rot} ${l.x} ${l.y})`}>
            {txt}
          </text>
        );
      })}

      {/* Center hub */}
      {showCenter && (
        <g>
          <circle cx={cx} cy={cy} r={rHub} fill="var(--sr-cream)" stroke="var(--sr-sage-haze)" strokeWidth="0.75" />
          <text x={cx} y={cy - rHub * 0.18}
                fill="var(--sr-sage-mid)"
                fontFamily='"Cormorant Garamond", serif'
                fontStyle="italic" fontSize={size * 0.046} fontWeight="400"
                textAnchor="middle" dominantBaseline="central">
            {centerTitle}
          </text>
          <text x={cx} y={cy + rHub * 0.32}
                fill="var(--sr-sage-mid)"
                fontFamily='"Cormorant Garamond", serif'
                fontStyle="italic" fontSize={size * 0.046} fontWeight="400"
                textAnchor="middle" dominantBaseline="central">
            {centerSub}
          </text>
        </g>
      )}
    </svg>
  );
}

Object.assign(window, { FeelingWheel });
