/* global React */
const { useState, useEffect, useRef } = React;

// ============================ ICONS ============================
const Icon = {
  play: (size = 14) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
  ),
  pause: (size = 14) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>
  ),
  arrow: (size = 14) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
  ),
  arrowLeft: (size = 14) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M11 18l-6-6 6-6"/></svg>
  ),
  close: (size = 16) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M18 6L6 18"/></svg>
  ),
  menu: (size = 18) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 6h16M4 12h16M4 18h16"/></svg>
  ),
  apple: () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M17.05 12.04c-.03-3.13 2.55-4.63 2.67-4.71-1.46-2.13-3.73-2.43-4.53-2.46-1.93-.2-3.76 1.13-4.74 1.13-.97 0-2.5-1.1-4.1-1.07-2.11.03-4.06 1.23-5.14 3.11-2.19 3.81-.56 9.45 1.58 12.55 1.05 1.52 2.3 3.23 3.94 3.17 1.58-.07 2.18-1.02 4.09-1.02 1.91 0 2.45 1.02 4.13.99 1.7-.03 2.78-1.55 3.82-3.08 1.2-1.76 1.7-3.47 1.73-3.56-.04-.02-3.31-1.27-3.45-5.04zM14.08 3.7c.87-1.05 1.45-2.51 1.29-3.95-1.25.05-2.76.83-3.65 1.88-.8.93-1.5 2.41-1.31 3.84 1.39.11 2.81-.71 3.67-1.77z"/></svg>
  ),
  spotify: () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.5 17.32c-.22.36-.7.48-1.06.26-2.9-1.77-6.55-2.17-10.85-1.18-.41.09-.83-.16-.92-.57s.16-.83.57-.92c4.7-1.08 8.74-.62 12 1.36.36.22.48.7.26 1.05zm1.47-3.27c-.28.45-.87.59-1.32.31-3.32-2.04-8.39-2.63-12.31-1.44-.5.15-1.03-.13-1.18-.63s.13-1.03.63-1.18c4.49-1.36 10.07-.7 13.88 1.63.45.28.59.87.31 1.32zm.13-3.4c-3.98-2.36-10.55-2.58-14.35-1.43-.6.18-1.23-.16-1.41-.76s.16-1.23.76-1.41c4.37-1.33 11.62-1.07 16.21 1.65.54.32.71 1.02.39 1.56-.32.54-1.02.71-1.56.39z"/></svg>
  ),
  youtube: () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M23.5 6.2c-.3-1-1.1-1.8-2.1-2.1C19.6 3.6 12 3.6 12 3.6s-7.6 0-9.4.5C1.6 4.4.8 5.2.5 6.2 0 8 0 12 0 12s0 4 .5 5.8c.3 1 1.1 1.8 2.1 2.1 1.8.5 9.4.5 9.4.5s7.6 0 9.4-.5c1-.3 1.8-1.1 2.1-2.1.5-1.8.5-5.8.5-5.8s0-4-.5-5.8zM9.6 15.6V8.4l6.3 3.6-6.3 3.6z"/></svg>
  ),
  amazon: () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="11" fill="none" stroke="currentColor" strokeWidth="1.6"/><path d="M7 14.5c2.8 1.7 6.8 1.8 9.7-.1l-.5-.8c-2.4 1.4-5.6 1.4-8.2.1l-1 .8z"/><path d="M16.5 10.5c0-1.5-.7-2.5-2.3-2.5-1.3 0-2.1.6-2.4 1.6l1.4.3c.1-.5.5-.7 1-.7.7 0 .9.4.9 1v.4c-1.4 0-3 .3-3 1.9 0 1.1.8 1.7 1.8 1.7.9 0 1.4-.4 1.7-.9.1.3.2.5.4.7l1.3-.9c-.4-.5-.7-.8-.7-1.6v-1z"/></svg>
  ),
  pocket: () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M21 3H3c-1.1 0-2 .9-2 2v6.5c0 5.8 4.7 10.5 11 10.5s11-4.7 11-10.5V5c0-1.1-.9-2-2-2zm-4.6 8.4l-3.8 3.7c-.3.3-.7.4-1.1.4-.4 0-.8-.2-1.1-.4l-3.8-3.7c-.6-.6-.6-1.5 0-2.1.6-.6 1.5-.6 2.1 0l2.7 2.6 2.7-2.6c.6-.6 1.5-.6 2.1 0 .9.6.9 1.5.2 2.1z"/></svg>
  ),
  rss: () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M6.18 15.64a2.18 2.18 0 0 1 2.18 2.18C8.36 19 7.38 20 6.18 20A2.18 2.18 0 0 1 4 17.82a2.18 2.18 0 0 1 2.18-2.18M4 4.44A15.56 15.56 0 0 1 19.56 20h-2.83A12.73 12.73 0 0 0 4 7.27V4.44m0 5.66a9.9 9.9 0 0 1 9.9 9.9h-2.83A7.07 7.07 0 0 0 4 12.93V10.1z"/></svg>
  ),
  pin: () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5a2.5 2.5 0 0 1 0-5 2.5 2.5 0 0 1 0 5z"/></svg>
  )
};

// ============================ ENCHANTMENT BADGE LOGO ============================
// Circular badge: Zia sun in center, "THE ENCHANTMENT CHRONICLES" curved along
// the top arc, dotted line along the bottom arc, thin outer ring.
const EnchantmentBadge = ({ size = 80, color = "#1E1A18", ring = "#1E1A18" }) => {
  const id = `badge-${Math.random().toString(36).slice(2, 8)}`;
  return (
    <svg viewBox="0 0 200 200" width={size} height={size} aria-label="The Enchantment Chronicles">
      <defs>
        <path id={`${id}-top`} d="M 30 100 A 70 70 0 0 1 170 100" fill="none" />
      </defs>
      {/* outer rings */}
      <circle cx="100" cy="100" r="92" fill="none" stroke={ring} strokeWidth="1.5" />
      <circle cx="100" cy="100" r="86" fill="none" stroke={ring} strokeWidth="0.75" opacity="0.55" />

      {/* top arc title text */}
      <text fontFamily="IM Fell English SC, serif" fontSize="13" fill={color}
        letterSpacing="0.22em" textAnchor="middle">
        <textPath href={`#${id}-top`} startOffset="50%">THE ENCHANTMENT CHRONICLES</textPath>
      </text>

      {/* bottom dotted arc */}
      {Array.from({ length: 24 }).map((_, i) => {
        const a = (205 + (i * 130) / 23) * (Math.PI / 180);
        const r = 78;
        const cx = 100 + r * Math.cos(a);
        const cy = 100 + r * Math.sin(a);
        return <circle key={i} cx={cx} cy={cy} r="1.4" fill={ring} />;
      })}

      {/* central Zia sun */}
      <g transform="translate(60 60)">
        {[0, 90, 180, 270].map(d => (
          <g key={d} transform={`rotate(${d} 40 40)`}>
            <rect x="38.5" y="2" width="3" height="14" fill={color} />
            <rect x="33" y="2" width="3" height="14" fill={color} />
            <rect x="44" y="2" width="3" height="14" fill={color} />
            <rect x="27.5" y="2" width="3" height="14" fill={color} />
          </g>
        ))}
        <circle cx="40" cy="40" r="12" fill="none" stroke={color} strokeWidth="4" />
      </g>
    </svg>
  );
};

// ============================ ZIA SUN ============================
const ZiaSun = ({ size = 40, color }) => {
  const c = color || "#B85C38";
  // Zia: circle in center, 4 rays in 4 cardinal directions, each direction has 4 rays
  const rays = [];
  const dirs = [0, 90, 180, 270];
  for (const d of dirs) {
    rays.push(<g key={d} transform={`rotate(${d} 50 50)`}>
      <rect x="48.2" y="6" width="3.6" height="14" fill={c} />
      <rect x="42.2" y="6" width="3.6" height="14" fill={c} />
      <rect x="54.2" y="6" width="3.6" height="14" fill={c} />
      <rect x="36.2" y="6" width="3.6" height="14" fill={c} />
    </g>);
  }
  return (
    <svg viewBox="0 0 100 100" width={size} height={size} aria-label="Zia sun symbol">
      {rays}
      <circle cx="50" cy="50" r="14" fill="none" stroke={c} strokeWidth="4.5"/>
    </svg>
  );
};

// ============================ TOPO BG ============================
const TopoBackground = () => (
  <svg className="hero-topo" viewBox="0 0 1200 600" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
    <defs>
      <pattern id="topo" x="0" y="0" width="1200" height="600" patternUnits="userSpaceOnUse">
        {Array.from({ length: 18 }).map((_, i) => (
          <path key={i}
            d={`M -50 ${40 + i * 32} Q 200 ${10 + i * 32 + (i%2?20:-20)} 400 ${50 + i * 32} T 800 ${30 + i * 32} T 1250 ${50 + i * 32}`}
            fill="none" stroke="#8E3F22" strokeWidth="0.8" opacity={0.7}/>
        ))}
      </pattern>
    </defs>
    <rect width="1200" height="600" fill="url(#topo)"/>
  </svg>
);

// ============================ DIVIDER ============================
const DividerZia = ({ color }) => (
  <div className="divider-zia">
    <span className="line"></span>
    <ZiaSun size={42} color={color} />
    <span className="line"></span>
  </div>
);

// ============================ EPISODE ART ============================
const EpisodeArt = ({ ep }) => {
  // generate a per-episode SVG: dusk gradient with topographic lines + tag + number
  const palette = {
    "Hard History": "#B85C38",
    "Lincoln County": "#C4A882",
    "This Day in NM": "#3AA8A0",
    "Faith & Frontier": "#3AA8A0",
    "Modern New Mexico": "#B85C38",
    "Ancestral": "#C4A882"
  };
  const accent = palette[ep.tag] || "#3AA8A0";
  return (
    <div className="ep-art">
      <svg className="ep-art-svg" viewBox="0 0 400 250" preserveAspectRatio="xMidYMid slice">
        <defs>
          <linearGradient id={`g${ep.n}`} x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#3B2D5E"/>
            <stop offset="100%" stopColor="#261B45"/>
          </linearGradient>
        </defs>
        <rect width="400" height="250" fill={`url(#g${ep.n})`}/>
        {/* topographic curves */}
        {Array.from({ length: 9 }).map((_, i) => (
          <path key={i}
            d={`M -20 ${110 + i * 16} Q 100 ${90 + i * 16 + (i%2?14:-14)} 200 ${110 + i * 16} T 420 ${100 + i * 16}`}
            fill="none" stroke={accent} strokeWidth="0.7" opacity={0.55 - i * 0.04}/>
        ))}
        {/* mountain silhouette */}
        <path d="M 0 200 L 40 150 L 90 180 L 140 130 L 200 175 L 260 125 L 320 165 L 380 140 L 400 160 L 400 250 L 0 250 Z"
          fill="#1E1A18" opacity="0.55"/>
        {/* zia mark */}
        <g transform="translate(330, 40) scale(0.5)" opacity="0.55">
          <ZiaSun size={50} color={accent}/>
        </g>
      </svg>
      <span className="ep-art-num">№ {String(ep.n).padStart(2, "0")}</span>
    </div>
  );
};

// ============================ NEW MEXICO MAP ============================
// Geographically-accurate outline:
//   Top edge: 37°N (CO border, straight)
//   East edge: 103°W (TX/OK border, straight)
//   South: 32°N from TX border west to El Paso, then steps south to 31.78°N
//          (Gadsden line), then west, then a deeper step to 31.33°N for the
//          bootheel, then west to 109.05°W (AZ border).
//   West edge: 109.05°W (AZ border, straight)
const NewMexicoMap = () => (
  <svg viewBox="0 0 400 440" aria-label="Map of New Mexico">
    <defs>
      <pattern id="hatch" patternUnits="userSpaceOnUse" width="6" height="6" patternTransform="rotate(45)">
        <line x1="0" y1="0" x2="0" y2="6" stroke="#C4A882" strokeWidth="1" opacity="0.4"/>
      </pattern>
    </defs>

    {/* state outline with bootheel in SW corner */}
    <path d="
      M 40 30
      L 360 30
      L 360 365
      L 167 365
      L 167 380
      L 85 380
      L 85 410
      L 40 410
      Z"
      fill="url(#hatch)" stroke="#1E1A18" strokeWidth="2" strokeLinejoin="miter"/>

    {/* Rio Grande — north to south, passing through the Taos gorge then down past Santa Fe & Albuquerque */}
    <path d="M 218 30 Q 220 50 222 70 Q 218 92 208 118 Q 188 142 175 175 Q 164 230 162 290 Q 160 330 162 365"
      fill="none" stroke="#3AA8A0" strokeWidth="2.5" opacity="0.75"/>

    {/* Pecos River — eastern */}
    <path d="M 250 60 Q 260 130 275 210 Q 285 290 295 360"
      fill="none" stroke="#3AA8A0" strokeWidth="1.4" opacity="0.5"/>

    {/* mountain ranges — peaks pointing UP (smaller y = higher) */}
    <g stroke="#1E1A18" strokeWidth="1" fill="none" opacity="0.6" strokeLinejoin="round">
      {/* Sangre de Cristos (north-central) */}
      <path d="M 200 82 L 208 64 L 216 82 L 226 56 L 236 82 L 244 70 L 252 82"/>
      {/* Jemez (NW of center) */}
      <path d="M 142 132 L 150 116 L 158 132 L 166 122 L 174 132"/>
      {/* Sandias (east of Albuquerque) */}
      <path d="M 180 172 L 188 154 L 196 172 L 204 160 L 212 172"/>
      {/* Sacramentos / Capitan (SE of center) */}
      <path d="M 228 278 L 236 260 L 244 278 L 252 264 L 260 278 L 268 268 L 276 278"/>
      {/* Mogollon / Gila (SW) */}
      <path d="M 68 278 L 76 262 L 84 278 L 92 264 L 100 278 L 108 268 L 116 278"/>
    </g>

    {/* city dots */}
    {[
      { x: 222, y: 70,  name: "Taos" },
      { x: 205, y: 118, name: "Santa Fe" },
      { x: 186, y: 105, name: "Los Alamos", side: "left" },
      { x: 167, y: 159, name: "Albuquerque" },
      { x: 322, y: 153, name: "Tucumcari", side: "left" },
      { x: 222, y: 248, name: "White Oaks" },
      { x: 234, y: 296, name: "Lincoln" },
      { x: 280, y: 272, name: "Roswell" },
      { x: 81,  y: 313, name: "Silver City" },
      { x: 160, y: 344, name: "Las Cruces", side: "left" },
      { x: 115, y: 376, name: "Columbus" }
    ].map(c => {
      const left = c.side === "left";
      return (
        <g key={c.name}>
          <circle cx={c.x} cy={c.y} r="3" fill="#B85C38"/>
          <text
            x={left ? c.x - 6 : c.x + 6}
            y={c.y + 3.5}
            textAnchor={left ? "end" : "start"}
            fontFamily="Zilla Slab, serif"
            fontSize="9"
            fill="#1E1A18"
            letterSpacing="0.06em"
          >
            {c.name.toUpperCase()}
          </text>
        </g>
      );
    })}

    {/* state-label cartouche placed in the open NE quadrant */}
    <g>
      <rect x="262" y="38" width="92" height="36" fill="#F5EFE0" stroke="#1E1A18"/>
      <text x="308" y="53" textAnchor="middle" fontFamily="IM Fell English SC, serif" fontSize="9" fill="#1E1A18" letterSpacing="0.12em">TERRITORY OF</text>
      <text x="308" y="68" textAnchor="middle" fontFamily="IM Fell English SC, serif" fontSize="11" fill="#B85C38" letterSpacing="0.08em">NEW MEXICO</text>
    </g>

    {/* compass rose in the southeast — inside the state */}
    <g transform="translate(330, 320)">
      <circle cx="0" cy="0" r="18" fill="#F5EFE0" stroke="#1E1A18" strokeWidth="1"/>
      <path d="M 0 -14 L 3 0 L 0 14 L -3 0 Z" fill="#1E1A18"/>
      <text x="0" y="-22" textAnchor="middle" fontFamily="IM Fell English SC, serif" fontSize="9" fill="#1E1A18">N</text>
    </g>

    {/* scale bar — bottom-left, beneath bootheel */}
    <g transform="translate(40, 428)">
      <line x1="0" y1="0" x2="80" y2="0" stroke="#1E1A18" strokeWidth="1"/>
      <line x1="0" y1="-3" x2="0" y2="3" stroke="#1E1A18"/>
      <line x1="40" y1="-3" x2="40" y2="3" stroke="#1E1A18"/>
      <line x1="80" y1="-3" x2="80" y2="3" stroke="#1E1A18"/>
      <text x="40" y="-7" textAnchor="middle" fontFamily="Zilla Slab, serif" fontSize="8" fill="#1E1A18" letterSpacing="0.2em">100 MI</text>
    </g>
  </svg>
);

// ============================ YUCCA SILHOUETTE (decorative) ============================
const Yucca = ({ size = 80, opacity = 1 }) => (
  <svg viewBox="0 0 80 120" width={size} height={size * 1.5} aria-hidden="true" style={{ opacity }}>
    {/* trunk */}
    <rect x="37" y="70" width="6" height="50" fill="#5A4B42"/>
    {/* radiating sword leaves */}
    {Array.from({ length: 14 }).map((_, i) => {
      const angle = -90 + (i - 7) * 14;
      return <g key={i} transform={`translate(40 72) rotate(${angle})`}>
        <path d="M 0 0 L -2 -36 L 0 -42 L 2 -36 Z" fill="#5A4B42"/>
      </g>;
    })}
    {/* flower stalk */}
    <rect x="39.2" y="20" width="1.6" height="50" fill="#5A4B42"/>
    {/* bells */}
    {[24, 32, 40, 48].map(y => (
      <ellipse key={y} cx="40" cy={y} rx="4" ry="3" fill="#F5EFE0" stroke="#5A4B42" strokeWidth="0.8"/>
    ))}
  </svg>
);

// Expose to window for other Babel scripts
Object.assign(window, { Icon, ZiaSun, EnchantmentBadge, TopoBackground, DividerZia, EpisodeArt, NewMexicoMap, Yucca });
