/* Garbashala — shared visual components (icons, motifs, decorations) */

/* Handwrite — wraps Tegaki's <tegaki-renderer> custom element to draw text
   stroke-by-stroke in Caveat. Falls back to plain styled text if Tegaki
   hasn't registered yet (the upgrade fires automatically on definition). */
const Handwrite = ({
  children, className = "", style = {},
  color = "var(--terracotta)", size = 22,
  speed = 1, delay = 0, loop = false,
}) => {
  const text = React.Children.toArray(children).filter((c) => typeof c === "string" || typeof c === "number").join("");
  const fontFamily = (typeof window !== "undefined" && window.TEGAKI_FONT) || "Caveat Tegaki 3dc76002";
  const props = {
    className: `hand-write ${className}`.trim(),
    text,
    font: fontFamily,
    speed: String(speed),
    delay: String(delay),
    style: {
      fontFamily: "var(--font-handwrite)",
      color,
      fontSize: size,
      lineHeight: 1.05,
      display: "inline-block",
      verticalAlign: "baseline",
      ...style,
    },
  };
  if (loop) props.loop = "";
  return React.createElement("tegaki-renderer", props, text);
};

if (typeof document !== "undefined" && !document.getElementById("handwrite-keys")) {
  const s = document.createElement("style");
  s.id = "handwrite-keys";
  s.textContent = `
    @keyframes inkFade {
      0% { opacity: 0; transform: translateY(2px) rotate(-1deg); }
      100% { opacity: 1; transform: translateY(0) rotate(0); }
    }
    /* hide the SEO/readable text-content fallback once tegaki has rendered
       its shadow-DOM canvas; the engine's :host content sits in shadow root */
    tegaki-renderer:defined { font-size: inherit; }
  `;
  document.head.appendChild(s);
}

const Diya = ({ size = 40, lit = true }) => (
  <svg viewBox="0 0 60 60" width={size} height={size} fill="none">
    {lit && (
      <>
        <ellipse cx="30" cy="14" rx="6" ry="11" fill="#E8A33D" opacity="0.5">
          <animate attributeName="ry" values="11;13;11" dur="1.5s" repeatCount="indefinite" />
        </ellipse>
        <path d="M30 26 Q 26 18 28 10 Q 30 4 32 10 Q 34 18 30 26Z" fill="#C4502A">
          <animate attributeName="d" values="M30 26 Q 26 18 28 10 Q 30 4 32 10 Q 34 18 30 26Z;M30 26 Q 26 19 27 11 Q 30 5 33 11 Q 34 19 30 26Z;M30 26 Q 26 18 28 10 Q 30 4 32 10 Q 34 18 30 26Z" dur="1.5s" repeatCount="indefinite" />
        </path>
        <path d="M30 23 Q 28 18 30 14 Q 32 18 30 23Z" fill="#FFE08A" />
      </>
    )}
    <path d="M10 32 Q 30 28 50 32 L 46 44 Q 30 47 14 44 Z" fill="#9C3A1C" />
    <path d="M10 32 Q 30 28 50 32" stroke="#5C2018" strokeWidth="1.5" fill="none" />
    <path d="M14 44 Q 30 47 46 44" stroke="#5C2018" strokeWidth="1.5" fill="none" />
    <line x1="22" y1="35" x2="38" y2="35" stroke="#E8A33D" strokeWidth="0.7" opacity="0.5" />
  </svg>
);

const Chakra = ({ size = 200, color = "var(--terracotta)", spokes = 16 }) => {
  const lines = Array.from({ length: spokes }).map((_, i) => {
    const a = (i / spokes) * Math.PI * 2;
    const x1 = 50 + Math.cos(a) * 30;
    const y1 = 50 + Math.sin(a) * 30;
    const x2 = 50 + Math.cos(a) * 48;
    const y2 = 50 + Math.sin(a) * 48;
    return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={color} strokeWidth="0.5" />;
  });
  return (
    <svg viewBox="0 0 100 100" width={size} height={size} fill="none">
      <g className="orbit-slow" style={{ transformOrigin: "50px 50px" }}>
        <circle cx="50" cy="50" r="49" stroke={color} strokeWidth="0.5" strokeDasharray="2 3" />
        <circle cx="50" cy="50" r="42" stroke={color} strokeWidth="0.4" opacity="0.5" />
        {lines}
        <circle cx="50" cy="50" r="30" stroke={color} strokeWidth="0.6" />
        <circle cx="50" cy="50" r="22" stroke={color} strokeWidth="0.4" strokeDasharray="1 2" />
      </g>
      <g className="orbit-rev" style={{ transformOrigin: "50px 50px" }}>
        <circle cx="50" cy="50" r="14" stroke={color} strokeWidth="0.5" />
        {Array.from({ length: 8 }).map((_, i) => {
          const a = (i / 8) * Math.PI * 2;
          return (
            <circle key={i} cx={50 + Math.cos(a) * 14} cy={50 + Math.sin(a) * 14} r="1.2" fill={color} />
          );
        })}
      </g>
    </svg>
  );
};

const Foot = ({ side = "L", color = "#C4502A", size = 60, opacity = 1, rotate = 0 }) => {
  const flip = side === "R" ? "scale(-1, 1)" : "";
  return (
    <svg viewBox="0 0 50 70" width={size} height={size * 1.4} style={{ transform: `${flip} rotate(${rotate}deg)`, opacity }}>
      <g fill={color}>
        <ellipse cx="25" cy="55" rx="13" ry="13" />
        <ellipse cx="22" cy="32" rx="11" ry="14" />
        <ellipse cx="14" cy="14" rx="4.5" ry="6" />
        <ellipse cx="22" cy="11" rx="3.2" ry="4.5" />
        <ellipse cx="28" cy="11.5" rx="2.8" ry="4" />
        <ellipse cx="33" cy="13" rx="2.4" ry="3.5" />
        <ellipse cx="37" cy="15" rx="2" ry="3" />
      </g>
      <text x="25" y="58" textAnchor="middle" fill="white" fontFamily="var(--font-display)" fontStyle="italic" fontSize="14" fontWeight="700">{side}</text>
    </svg>
  );
};

const Feather = ({ size = 100, rotate = 0 }) => (
  <svg viewBox="0 0 60 120" width={size * 0.5} height={size} style={{ transform: `rotate(${rotate}deg)` }}>
    <path d="M30 110 Q 30 60 30 20" stroke="#5C2018" strokeWidth="1.2" fill="none" />
    <ellipse cx="30" cy="20" rx="14" ry="20" fill="#2E3957" />
    <ellipse cx="30" cy="22" rx="10" ry="14" fill="#7A8B5C" />
    <ellipse cx="30" cy="22" rx="6" ry="9" fill="#E8A33D" />
    <ellipse cx="30" cy="20" rx="3" ry="5" fill="#5C2018" />
    {Array.from({ length: 12 }).map((_, i) => (
      <g key={i}>
        <line x1="30" y1={50 + i * 5} x2={20 - i * 0.5} y2={56 + i * 4} stroke="#7A8B5C" strokeWidth="0.6" />
        <line x1="30" y1={50 + i * 5} x2={40 + i * 0.5} y2={56 + i * 4} stroke="#7A8B5C" strokeWidth="0.6" />
      </g>
    ))}
  </svg>
);

const Marigold = ({ size = 60, color = "#E8A33D" }) => (
  <svg viewBox="0 0 60 60" width={size} height={size}>
    <g style={{ transformOrigin: "30px 30px" }}>
      {Array.from({ length: 12 }).map((_, i) => {
        const a = (i / 12) * 360;
        return <ellipse key={i} cx="30" cy="14" rx="5" ry="10" fill={color} opacity="0.85" transform={`rotate(${a} 30 30)`} />;
      })}
      {Array.from({ length: 8 }).map((_, i) => {
        const a = (i / 8) * 360 + 22;
        return <ellipse key={`b-${i}`} cx="30" cy="20" rx="4" ry="7" fill="#C4502A" opacity="0.9" transform={`rotate(${a} 30 30)`} />;
      })}
      <circle cx="30" cy="30" r="4" fill="#5C2018" />
    </g>
  </svg>
);

const HandDivider = ({ width = 600 }) => (
  <svg viewBox="0 0 600 30" width={width} height={30 * (width / 600)} preserveAspectRatio="none">
    <path d="M0 15 Q 30 6 60 15 T 120 15 T 180 15 T 240 15 T 300 15 T 360 15 T 420 15 T 480 15 T 540 15 T 600 15"
          stroke="var(--terracotta)" strokeWidth="1.4" fill="none" strokeLinecap="round" />
    <circle cx="300" cy="15" r="4" fill="var(--marigold)" stroke="var(--terracotta)" strokeWidth="1" />
    <circle cx="100" cy="15" r="2" fill="var(--terracotta)" />
    <circle cx="500" cy="15" r="2" fill="var(--terracotta)" />
    <circle cx="200" cy="15" r="1.5" fill="var(--maroon)" />
    <circle cx="400" cy="15" r="1.5" fill="var(--maroon)" />
  </svg>
);

const NumberStamp = ({ n, color = "var(--terracotta)" }) => (
  <span style={{
    display: "inline-flex", width: 36, height: 36, borderRadius: "50%",
    border: `1.8px solid ${color}`, color,
    alignItems: "center", justifyContent: "center",
    fontFamily: "var(--font-display)", fontStyle: "italic", fontWeight: 700, fontSize: 18,
    background: "var(--paper)",
    boxShadow: "1px 1px 0 var(--ink)",
  }}>{n}</span>
);

const DrawPath = ({ d, stroke = "var(--terracotta)", strokeWidth = 2, fill = "none", duration = 1.6, delay = 0, ...rest }) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current) return;
    const len = ref.current.getTotalLength?.() || 1000;
    ref.current.style.setProperty("--len", len);
    ref.current.style.strokeDasharray = len;
    ref.current.style.strokeDashoffset = len;
    ref.current.style.animation = `drawPath ${duration}s ${delay}s ease-out forwards`;
  }, [d]);
  return <path ref={ref} d={d} stroke={stroke} strokeWidth={strokeWidth} fill={fill} strokeLinecap="round" {...rest} />;
};

const GarbashalaLogo = ({ size = 28, accent = "var(--terracotta)", ink = "var(--ink)", showSub = true }) => (
  <a className="garbashala-logo" href="#/" style={{ display: "inline-flex", alignItems: "center", gap: 10, textDecoration: "none" }}>
    <img
      src="/assets/logo.png"
      alt="Garba Shala"
      width={size * 1.6}
      height={size * 1.6}
      style={{ display: "block", objectFit: "contain" }}
    />
    <span style={{ display: "inline-flex", flexDirection: "column", lineHeight: 0.9 }}>
      <span style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: size, color: ink, letterSpacing: "-0.01em" }}>
        garba shala
      </span>
      {showSub && (
        <span style={{ fontFamily: "var(--font-handwrite)", fontSize: size * 0.45, color: accent, marginTop: 4 }}>
          a garba step library
        </span>
      )}
    </span>
  </a>
);

const Difficulty = ({ level = 1, max = 5 }) => (
  <span style={{ display: "inline-flex", gap: 3, alignItems: "center" }}>
    {Array.from({ length: max }).map((_, i) => (
      <span key={i} style={{
        width: 14, height: 5, borderRadius: 1,
        background: i < level ? "var(--terracotta)" : "transparent",
        border: "1px solid var(--terracotta)",
      }} />
    ))}
  </span>
);

const NavBar = ({ active = "home" }) => (
  <header className="site-nav" style={{
    display: "flex", alignItems: "center", justifyContent: "space-between",
    padding: "20px 48px",
    borderBottom: "1px dashed rgba(42,24,16,0.3)",
    flexWrap: "wrap", gap: 16,
  }}>
    <GarbashalaLogo size={26} />
    <nav className="site-nav__links" style={{ display: "flex", gap: 28, fontFamily: "var(--font-body)", fontSize: 17 }}>
      {[
        ["home", "Home", "#/"],
        ["library", "Steps", "#/library"],
        ["about", "What is Garba?", "#/about"],
      ].map(([k, label, href]) => (
        <a key={k} href={href} style={{
          color: active === k ? "var(--terracotta)" : "var(--ink)",
          textDecoration: "none",
          fontWeight: active === k ? 600 : 500,
          fontStyle: active === k ? "italic" : "normal",
          position: "relative",
        }}>
          {label}
          {active === k && (
            <svg viewBox="0 0 60 7" width="100%" height="6" style={{ position: "absolute", left: 0, bottom: -6 }} preserveAspectRatio="none">
              <path d="M0 4 Q 15 1 30 4 T 60 4" stroke="var(--terracotta)" strokeWidth="1.5" fill="none" strokeLinecap="round" />
            </svg>
          )}
        </a>
      ))}
    </nav>
    <div className="site-nav__tools" style={{ display: "flex", gap: 12, alignItems: "center" }}>
      <input className="site-nav__search" placeholder="Search a step…" style={{
        background: "transparent",
        border: "1px solid var(--ink)",
        borderRadius: "20px 6px 18px 8px / 8px 18px 6px 20px",
        padding: "6px 14px",
        fontFamily: "var(--font-body)", fontSize: 15,
        width: 180,
        color: "var(--ink)",
      }} />
      <span className="stamp" style={{ borderColor: "var(--maroon)", color: "var(--maroon)" }}>
        ❀ free, always
      </span>
    </div>
  </header>
);

Object.assign(window, {
  Handwrite, Diya, Chakra, Foot, Feather, Marigold,
  HandDivider, NumberStamp, DrawPath, GarbashalaLogo,
  Difficulty, NavBar,
});
