/* === US tile-grid map with dual-dimension rendering ===
   Choropleth fill = program maturity
   Overlay (hatch + ring + corner dot) = legislative activity this session
*/

const FILL = {
  "live":    "var(--navy)",
  "enacted": "var(--navy-soft)",
  "none":    "var(--surface-3)",
};
const FILL_LIGHT = {
  "live":    false,
  "enacted": false,
  "none":    true,
};

function USTileMap({ onSelectState, selectedState, mapStyle = "tile", showHatch = true }) {
  const layout = window.TILE_LAYOUT;
  const tile = 52; // px per cell
  const gap = 4;
  const cols = 11;
  const rows = 8;
  const pad = 14;
  const W = pad * 2 + cols * (tile + gap) - gap;
  const H = pad * 2 + rows * (tile + gap) - gap;

  const [hover, setHover] = React.useState(null);

  const cell = (col, row) => ({
    x: pad + col * (tile + gap),
    y: pad + row * (tile + gap),
  });

  return (
    <div style={{ position: "relative" }}>
      <svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label="US states by program maturity and legislative activity">
        <defs>
          <pattern id="hatch-active" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="6" stroke="var(--accent)" strokeWidth="2" />
          </pattern>
          <pattern id="hatch-recent" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="6" stroke="var(--accent)" strokeWidth="1" strokeDasharray="1.5 2.5" opacity=".6" />
          </pattern>
        </defs>

        {Object.entries(layout).map(([abbr, pos]) => {
          const j = window.JURISDICTIONS[abbr];
          if (!j) return null;
          const { x, y } = cell(pos.col, pos.row);
          const fill = FILL[j.program] || "var(--surface-3)";
          const light = FILL_LIGHT[j.program] === false;
          const isActive = j.legActivity === "active" || j.legActivity === "enacted-session";
          const isRecent = j.legActivity === "recent";
          const isEnactedSession = j.legActivity === "enacted-session";
          const sel = selectedState === abbr;
          return (
            <g
              key={abbr}
              className={`us-state ${sel ? "us-state--active" : ""}`}
              transform={`translate(${x} ${y})`}
              onMouseEnter={(e) => setHover({ abbr, x: x + tile + 14, y: y - 6 })}
              onMouseLeave={() => setHover(null)}
              onClick={() => onSelectState && onSelectState(abbr)}
            >
              <rect className="us-state__shape" width={tile} height={tile} rx="6" fill={fill} stroke="var(--border)" strokeWidth="0.5" />
              {showHatch && isActive ? <rect width={tile} height={tile} rx="6" className="overlay-hatch" /> : null}
              {showHatch && isRecent ? <rect width={tile} height={tile} rx="6" fill="url(#hatch-recent)" /> : null}
              {isEnactedSession ? (
                <g>
                  {/* corner triangle marker */}
                  <path d={`M ${tile - 14} 0 L ${tile} 0 L ${tile} 14 Z`} fill="var(--accent)" />
                </g>
              ) : null}
              <text className={`us-state__label ${light ? "us-state__label--light" : ""}`}
                    x={tile / 2} y={tile / 2 + 3} textAnchor="middle">
                {abbr}
              </text>
              {j.trifecta ? (
                <circle cx={tile - 8} cy={tile - 8} r={3.5}
                        fill={j.trifecta === "R" ? "var(--red)" : "var(--navy)"}
                        stroke="white" strokeWidth="1"
                        title={`${j.trifecta === "R" ? "R" : "D"}-trifecta state`} />
              ) : null}
            </g>
          );
        })}

        {/* Federal layer — placed in the empty top-center band of the Economist layout */}
        <g transform={`translate(${cell(2, 0).x} ${cell(2, 0).y})`}>
          <rect width={tile * 3 + gap * 2} height={tile * 0.7} rx="6"
                fill="var(--surface)" stroke="var(--border-strong)" strokeDasharray="3 3" />
          <text x={(tile * 3 + gap * 2) / 2} y={tile * 0.45}
                textAnchor="middle"
                style={{ font: "500 10px/1 var(--mono)", fill: "var(--ink-2)", letterSpacing: ".1em" }}>
            FEDERAL
          </text>
        </g>
      </svg>

      {hover ? (
        <MapTip abbr={hover.abbr} x={hover.x} y={hover.y} />
      ) : null}
    </div>
  );
}

function MapTip({ abbr, x, y }) {
  const j = window.JURISDICTIONS[abbr];
  const name = window.STATE_NAMES[abbr] || abbr;
  if (!j) return null;
  const programLabel = { live: "Active program (live)", enacted: "Enacted — implementation", none: "No program" }[j.program];
  const legLabel = {
    "enacted-session": "Enacted this session",
    "active": "Active legislation",
    "recent": "Recent legislation",
    "none": "No legislation this session",
  }[j.legActivity];
  return (
    <div className="map-tip" style={{ left: x, top: y }}>
      <div className="map-tip__hd">{name}</div>
      <div className="map-tip__row">
        <span style={{ color: "var(--ink)" }}>{programLabel}</span>
        {j.label ? <span>· {j.label}</span> : null}
      </div>
      <div className="map-tip__row">
        <span style={{ color: "var(--accent)" }}>{legLabel}</span>
        {j.trifecta ? <span style={{ color: j.trifecta === "R" ? "var(--red)" : "var(--navy)" }}>· {j.trifecta}-trifecta</span> : null}
      </div>
    </div>
  );
}

function MapLegend({ showTrifecta = true }) {
  return (
    <div className="map-toolbar__legend">
      <div className="legend-row-group">
        <span className="eyebrow legend-row-group__label">Program</span>
        <span className="legend-row"><span className="legend-swatch" style={{ background: "var(--navy)" }}></span>Live</span>
        <span className="legend-row"><span className="legend-swatch" style={{ background: "var(--navy-soft)" }}></span>Enacted · implementing</span>
        <span className="legend-row"><span className="legend-swatch" style={{ background: "var(--surface-3)" }}></span>None</span>
      </div>
      <div className="legend-row-group">
        <span className="eyebrow legend-row-group__label">Legislation</span>
        <span className="legend-row">
          <span className="legend-swatch" style={{
            background: "var(--surface-3)",
            backgroundImage: "repeating-linear-gradient(-45deg, var(--accent) 0 2px, transparent 2px 6px)",
            borderColor: "var(--border)"
          }}></span>
          Active this session
        </span>
        <span className="legend-row">
          <span className="legend-swatch" style={{
            background: "var(--surface-3)",
            backgroundImage: "repeating-linear-gradient(-45deg, color-mix(in oklch, var(--accent) 50%, transparent) 0 1px, transparent 1px 4px)",
            borderColor: "var(--border)"
          }}></span>
          Recent (prior session)
        </span>
        <span className="legend-row">
          <span className="legend-swatch" style={{ background: "var(--accent)", clipPath: "polygon(60% 0, 100% 0, 100% 40%)", border: "1px solid var(--border)" }}></span>
          Enacted this session
        </span>
      </div>
    </div>
  );
}

function TrifectaLegend() {
  return (
    <div style={{
      display: "inline-flex", alignItems: "center", gap: 8,
      fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)",
      letterSpacing: ".02em",
    }}>
      <span className="eyebrow" style={{ marginRight: 2 }}>Trifecta</span>
      <span style={{
        width: 8, height: 8, background: "var(--navy)", borderRadius: 99,
        border: "1px solid white", boxShadow: "0 0 0 1px var(--border)", display: "inline-block",
      }}></span>
      <span style={{
        width: 8, height: 8, background: "var(--red)", borderRadius: 99,
        border: "1px solid white", boxShadow: "0 0 0 1px var(--border)", display: "inline-block",
        marginLeft: -2,
      }}></span>
    </div>
  );
}

Object.assign(window, { USTileMap, MapTip, MapLegend, TrifectaLegend });
