/* ═══════════════════════════════════════════
   Visual components — Gear, GearCluster, ShareCard
   ═══════════════════════════════════════════ */

const { useRef, useState, useEffect } = React;

// Gear silhouette
function Gear({ cx, cy, r, color, opacity = 1, spinning = false, pulseKey = 0 }) {
  const n = 8, inner = r * 0.68, outer = r * 1.15, tw = 0.26;
  let d = "";
  for (let i = 0; i < n; i++) {
    const a = (i / n) * Math.PI * 2, a1 = a - tw, a2 = a + tw;
    d += `${i ? 'L' : 'M'}${cx + inner * Math.cos(a1)},${cy + inner * Math.sin(a1)} L${cx + outer * Math.cos(a1)},${cy + outer * Math.sin(a1)} L${cx + outer * Math.cos(a2)},${cy + outer * Math.sin(a2)} L${cx + inner * Math.cos(a2)},${cy + inner * Math.sin(a2)} `;
  }
  d += "Z";

  // Pulse animation — re-runs every time pulseKey changes
  const [pulseRunning, setPulseRunning] = useState(false);
  useEffect(() => {
    if (pulseKey > 0) {
      setPulseRunning(false);
      const id = requestAnimationFrame(() => setPulseRunning(true));
      const t = setTimeout(() => setPulseRunning(false), 600);
      return () => { cancelAnimationFrame(id); clearTimeout(t); };
    }
  }, [pulseKey]);

  return (
    <g style={{ opacity, transition: "opacity 0.8s ease" }}>
      <g
        style={{
          transformOrigin: `${cx}px ${cy}px`,
          transform: pulseRunning ? "scale(1.08)" : "scale(1)",
          transition: "transform 0.32s cubic-bezier(0.34, 1.56, 0.64, 1)",
        }}
      >
        <path d={d} fill={color}>
          {spinning && (
            <animateTransform
              attributeName="transform"
              type="rotate"
              from={`0 ${cx} ${cy}`}
              to={`${r > 25 ? 360 : -360} ${cx} ${cy}`}
              dur={`${16 + r * 0.3}s`}
              repeatCount="indefinite"
            />
          )}
        </path>
        <circle cx={cx} cy={cy} r={r * 0.28} fill="#FAF8F5" />
      </g>
    </g>
  );
}

const GP = [
  { cx: 85,  cy: 72,  r: 32 }, // prediction
  { cx: 160, cy: 52,  r: 26 }, // emotion
  { cx: 143, cy: 122, r: 28 }, // rumination
  { cx: 52,  cy: 138, r: 24 }, // attribution
  { cx: 218, cy: 100, r: 22 }, // language
  { cx: 200, cy: 155, r: 20 }, // script
];

function GearCluster({ scores, mode = "welcome", highlighted = [], size = 260, pulseMap = {} }) {
  return (
    <svg viewBox="0 0 260 195" style={{ width: "100%", maxWidth: size, margin: "0 auto", display: "block" }}>
      {window.MKEYS.map((k, i) => {
        const p = GP[i];
        let op, spin;
        if (mode === "welcome") {
          op = i < 2 ? 0.35 : 0.12;
          spin = i < 2;
        } else if (mode === "quiz") {
          const raw = ((scores[k] || 0) / window.MAX_S[k]);
          op = 0.10 + raw * 0.78;
          spin = raw > 0.08;
        } else {
          const isTop = highlighted.includes(k);
          op = isTop ? 1 : 0.10;
          spin = isTop;
        }
        return (
          <Gear
            key={k}
            {...p}
            color={window.M[k].color}
            opacity={op}
            spinning={spin}
            pulseKey={pulseMap[k] || 0}
          />
        );
      })}
    </svg>
  );
}

// ─── ShareCard: 1080×1350 (4:5 IG portrait) ───
// Rendered at full size in a hidden offscreen container for export,
// AND shown to user as a scaled preview.
function ShareCard({ results, scores, size = 1080 }) {
  const aspect = 1350 / 1080;
  return (
    <div
      style={{
        width: size,
        height: size * aspect,
        background: "#FAF8F5",
        position: "relative",
        fontFamily: "'Noto Sans TC', sans-serif",
        color: "#3D3530",
        padding: `${size * 0.075}px ${size * 0.075}px`,
        display: "flex",
        flexDirection: "column",
        overflow: "hidden",
      }}
    >
      {/* watermark grid lines — subtle */}
      <div
        style={{
          position: "absolute", inset: 0,
          backgroundImage:
            "linear-gradient(to right, rgba(184,174,164,0.08) 1px, transparent 1px)," +
            "linear-gradient(to bottom, rgba(184,174,164,0.08) 1px, transparent 1px)",
          backgroundSize: `${size * 0.083}px ${size * 0.083}px`,
          pointerEvents: "none",
        }}
      />

      {/* Top brand label */}
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", position: "relative" }}>
        <div style={{
          fontFamily: "'Noto Serif TC', serif", fontSize: size * 0.026,
          fontWeight: 600, letterSpacing: "0.06em", color: "#3D3530"
        }}>
          煩惱的常見機制 <span style={{ marginLeft: 6 }}>⚙</span>
        </div>
        <div style={{ fontSize: size * 0.019, letterSpacing: "0.08em", color: "#A09890" }}>
          MECHANISM QUIZ
        </div>
      </div>
      <div style={{ height: 1, background: "#E8E2DA", margin: `${size * 0.022}px 0 ${size * 0.04}px` }} />

      {/* Headline */}
      <p style={{
        fontFamily: "'Noto Serif TC', serif",
        fontSize: size * 0.039,
        lineHeight: 1.55,
        color: "#6B5E54",
        marginBottom: size * 0.018,
      }}>
        我的煩惱裡，<br />
        <span style={{ color: "#3D3530" }}>這三個齒輪轉得最積極：</span>
      </p>

      {/* Tags */}
      <div style={{ display: "flex", flexWrap: "wrap", gap: size * 0.015, marginBottom: size * 0.025 }}>
        {results.map(k => (
          <span
            key={k}
            style={{
              fontSize: size * 0.032,
              padding: `${size * 0.012}px ${size * 0.028}px`,
              borderRadius: size * 0.05,
              background: window.M[k].color,
              color: "#fff",
              fontWeight: 500,
              letterSpacing: "0.05em",
            }}
          >
            {window.M[k].label}
          </span>
        ))}
      </div>

      {/* Gear cluster — big */}
      <div style={{
        flex: 1, display: "flex", alignItems: "center", justifyContent: "center",
        margin: `${size * 0.015}px 0 ${size * 0.02}px`,
      }}>
        <GearCluster scores={scores} mode="results" highlighted={results} size={size * 0.78} />
      </div>

      {/* Narrative */}
      <p style={{
        fontFamily: "'Noto Serif TC', serif",
        fontSize: size * 0.028,
        lineHeight: 1.85,
        color: "#3D3530",
        textAlign: "left",
        textWrap: "pretty",
        marginBottom: size * 0.04,
      }}>
        {window.buildNarrative(results)}
      </p>

      {/* Footer */}
      <div style={{
        borderTop: "1px solid #E8E2DA",
        paddingTop: size * 0.025,
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <div style={{ fontSize: size * 0.02, color: "#8B7E74", letterSpacing: "0.03em" }}>
          mechanism.seproject.me
        </div>
        <div style={{
          fontSize: size * 0.022, color: "#3D3530", fontWeight: 500,
          display: "flex", alignItems: "center", gap: 6,
        }}>
          你也來測 →
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Gear, GearCluster, ShareCard });
