/* Compass — branded SVG compass rose.
 *
 * Replaces the legacy PNG (which lived in /assets/compass.png) with an
 * inline SVG so we can:
 *   - render at any pixel ratio crisply,
 *   - tint stroke/fill via CSS (currentColor),
 *   - add an interactive "reset to north" affordance.
 *
 * The dial (everything rotatable) lives in a single <g> that takes the
 * bearing transform. The outer ring + tick marks stay fixed so the
 * user always sees a stable bezel and only the needle / N-marker spins.
 *
 * onReset is fired on click — MapStage calls map.easeTo({ bearing: 0 })
 * which animates the bearing back to 0 and triggers the existing
 * `rotate` listener that drives this component's `bearing` prop.
 */
function Compass({ bearing = 0, onReset }) {
  const aligned = Math.abs(((bearing % 360) + 360) % 360) < 0.5;

  return (
    <div className="compass-container">
      <button
        type="button"
        className={"compass-btn" + (aligned ? " aligned" : "")}
        onClick={onReset}
        aria-label="Réorienter vers le nord"
        title="Réorienter vers le nord"
      >
        {/* Fixed bezel: outer ring + cardinal ticks. Does NOT rotate. */}
        <svg className="compass-bezel" viewBox="0 0 64 64" aria-hidden="true">
          <circle cx="32" cy="32" r="30" className="cmp-ring-outer"/>
          <circle cx="32" cy="32" r="26" className="cmp-ring-inner"/>
          {/* 16-step tick ring */}
          {Array.from({ length: 16 }).map((_, i) => {
            const a = (i * 360) / 16;
            const long = i % 4 === 0;
            return (
              <line
                key={i}
                x1="32" y1={long ? 4.5 : 6}
                x2="32" y2={long ? 9 : 8}
                className={long ? "cmp-tick-major" : "cmp-tick-minor"}
                transform={`rotate(${a} 32 32)`}
              />
            );
          })}
        </svg>

        {/* Rotating dial: needle (red north / pale south) + N glyph. */}
        <svg
          className="compass-dial"
          viewBox="0 0 64 64"
          aria-hidden="true"
          style={{ transform: `rotate(${-bearing}deg)` }}
        >
          {/* Cardinal N letter, sits just inside the bezel */}
          <text x="32" y="15.5" className="cmp-cardinal" textAnchor="middle">N</text>

          {/* Compass needle — two-triangle diamond, cognac/orange north,
              pale beige south. Drawn around (32,32). */}
          <polygon points="32,16 36,32 32,30 28,32"  className="cmp-needle-n"/>
          <polygon points="32,48 36,32 32,34 28,32"  className="cmp-needle-s"/>

          {/* Centre hub */}
          <circle cx="32" cy="32" r="2.4" className="cmp-hub"/>
        </svg>
      </button>
    </div>
  );
}

window.Compass = Compass;
