/* global React, window */
// Eyad Academy — shared atoms: icons, mascot, reveal, counter

const { useEffect, useRef, useState } = React;

// ============================================================
// Icon set — hand-tuned to match brand. Uses currentColor.
// ============================================================
function Icon({ name, size = 22 }) {
  const s = { width: size, height: size, display: "inline-block", verticalAlign: "middle" };
  const stroke = { fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "menu":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><path d="M4 7h16M4 12h16M4 17h10"/></g></svg>);
    case "arrow":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><path d="M5 12h14M13 6l6 6-6 6"/></g></svg>);
    case "play":
      return (<svg viewBox="0 0 24 24" style={s}><path d="M8 5v14l11-7z" fill="currentColor"/></svg>);
    case "spark":
      return (<svg viewBox="0 0 24 24" style={s}><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z" fill="currentColor"/><circle cx="19" cy="5" r="1.2" fill="currentColor"/><circle cx="5" cy="19" r="1" fill="currentColor"/></svg>);
    case "compass":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><circle cx="12" cy="12" r="9"/><path d="M15 9l-2 5-5 2 2-5z" fill="currentColor" stroke="none"/></g></svg>);
    case "shield":
      return (<svg viewBox="0 0 24 24" style={s}><path d="M12 3l8 3v5c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6l8-3z" fill="currentColor" opacity="0.2"/><g {...stroke}><path d="M12 3l8 3v5c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6l8-3z"/><path d="M9 12l2 2 4-4"/></g></svg>);
    case "trophy":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><path d="M8 4h8v4a4 4 0 11-8 0V4z"/><path d="M5 5H3v2a3 3 0 003 3M19 5h2v2a3 3 0 01-3 3M10 16h4v3h-4z"/><path d="M9 19h6"/></g></svg>);
    case "book":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><path d="M4 5a2 2 0 012-2h13v16H6a2 2 0 00-2 2V5z"/><path d="M4 5a2 2 0 002 2h13"/></g></svg>);
    case "clock":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></g></svg>);
    case "users":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><circle cx="9" cy="9" r="3.5"/><path d="M3 19c0-3 3-5 6-5s6 2 6 5"/><circle cx="17" cy="10" r="2.5"/><path d="M21 19c0-2-1.5-3.5-4-4"/></g></svg>);
    case "star":
      return (<svg viewBox="0 0 24 24" style={s}><path d="M12 3l2.7 6 6.3.5-4.8 4.2 1.5 6.3L12 16.8 6.3 20l1.5-6.3L3 9.5 9.3 9z" fill="currentColor"/></svg>);
    case "check":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><path d="M5 12l5 5 9-12"/></g></svg>);
    case "close":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><path d="M6 6l12 12M18 6L6 18"/></g></svg>);
    case "chevron":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><path d="M9 6l6 6-6 6"/></g></svg>);
    case "quote":
      return (<svg viewBox="0 0 24 24" style={s}><path d="M7 7h4v4H8c0 2 1 3 3 3v2c-3 0-5-2-5-5V7zm8 0h4v4h-3c0 2 1 3 3 3v2c-3 0-5-2-5-5V7z" fill="currentColor"/></svg>);
    case "quran":
      return (<svg viewBox="0 0 28 28" style={s}><g {...stroke}><path d="M6 6a2 2 0 012-2h12v18H8a2 2 0 00-2 2V6z"/><path d="M14 8v8M10 12h8" /></g></svg>);
    case "arabic":
      return (<svg viewBox="0 0 28 28" style={s}><g {...stroke}><path d="M5 8c2-2 4-2 6 0s4 2 6 0 4-2 6 0"/><path d="M5 16c2-2 4-2 6 0s4 2 6 0 4-2 6 0"/><circle cx="14" cy="22" r="1" fill="currentColor" stroke="none"/></g></svg>);
    case "math":
      return (<svg viewBox="0 0 28 28" style={s}><g {...stroke}><path d="M4 14h8M8 10v8"/><path d="M16 11l6 6M22 11l-6 6"/></g></svg>);
    case "science":
      return (<svg viewBox="0 0 28 28" style={s}><g {...stroke}><path d="M11 4v6l-5 10a3 3 0 003 3h10a3 3 0 003-3l-5-10V4"/><path d="M9 4h10"/><circle cx="13" cy="18" r="1.2" fill="currentColor" stroke="none"/><circle cx="17" cy="15" r="1" fill="currentColor" stroke="none"/></g></svg>);
    case "lightning":
      return (<svg viewBox="0 0 24 24" style={s}><path d="M13 2L4 14h7l-1 8 9-12h-7z" fill="currentColor"/></svg>);
    case "twitter":
      return (<svg viewBox="0 0 24 24" style={s}><path d="M18 4h3l-7 8 8 8h-6l-5-6-5 6H3l8-9-8-7h6l4 5z" fill="currentColor"/></svg>);
    case "insta":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="0.8" fill="currentColor" stroke="none"/></g></svg>);
    case "youtube":
      return (<svg viewBox="0 0 24 24" style={s}><g {...stroke}><rect x="2" y="6" width="20" height="12" rx="3"/><path d="M10 9.5v5l4-2.5z" fill="currentColor" stroke="none"/></g></svg>);
    case "tiktok":
      return (<svg viewBox="0 0 24 24" style={s}><path d="M14 4h3c0 2 2 4 4 4v3c-2 0-3-.5-4-1v6a5 5 0 11-5-5v3a2 2 0 102 2V4z" fill="currentColor"/></svg>);
    default: return null;
  }
}

// ============================================================
// Mascot — 4 styles, swap via Tweaks
// ============================================================
function Mascot({ style = "real", className = "", size }) {
  const sty = size ? { width: size, height: size } : {};
  if (style === "real") {
    return (
      <div className={className} style={sty}>
        <img src="assets/mascot.png" alt="نجمة إياد" />
      </div>
    );
  }
  if (style === "geometric") {
    return (
      <div className={className} style={sty}>
        <svg viewBox="0 0 100 100" style={{ width: "100%", height: "100%" }}>
          <defs>
            <radialGradient id="g-geo" cx="40%" cy="35%">
              <stop offset="0%" stopColor="#FFF6DC"/>
              <stop offset="60%" stopColor="#F5D67A"/>
              <stop offset="100%" stopColor="#D9A441"/>
            </radialGradient>
          </defs>
          <path
            d="M50 8 L60 38 L92 40 L66 58 L74 90 L50 72 L26 90 L34 58 L8 40 L40 38 Z"
            fill="url(#g-geo)"
            stroke="#B8862D" strokeWidth="1.5" strokeLinejoin="round"
          />
        </svg>
      </div>
    );
  }
  if (style === "lineart") {
    return (
      <div className={className} style={sty}>
        <svg viewBox="0 0 100 100" style={{ width: "100%", height: "100%" }}>
          <defs>
            <linearGradient id="g-line" x1="0" x2="1" y1="0" y2="1">
              <stop offset="0%" stopColor="#D9A441"/>
              <stop offset="100%" stopColor="#8B7AD9"/>
            </linearGradient>
            <radialGradient id="g-line-glow" cx="50%" cy="50%">
              <stop offset="0%" stopColor="#F5D67A" stopOpacity="0.6"/>
              <stop offset="100%" stopColor="#F5D67A" stopOpacity="0"/>
            </radialGradient>
          </defs>
          <circle cx="50" cy="50" r="42" fill="url(#g-line-glow)"/>
          <path
            d="M50 12 L60 40 L90 42 L66 60 L74 90 L50 74 L26 90 L34 60 L10 42 L40 40 Z"
            fill="none" stroke="url(#g-line)" strokeWidth="3.5" strokeLinejoin="round"
          />
          <circle cx="30" cy="22" r="1.6" fill="#D9A441"/>
          <circle cx="76" cy="78" r="1.2" fill="#8B7AD9"/>
          <circle cx="22" cy="68" r="1" fill="#D9A441"/>
        </svg>
      </div>
    );
  }
  // "sunny" — soft sun
  return (
    <div className={className} style={sty}>
      <svg viewBox="0 0 100 100" style={{ width: "100%", height: "100%" }}>
        <defs>
          <radialGradient id="g-sun" cx="40%" cy="40%">
            <stop offset="0%" stopColor="#FFF6DC"/>
            <stop offset="60%" stopColor="#F5D67A"/>
            <stop offset="100%" stopColor="#D9A441"/>
          </radialGradient>
        </defs>
        <g>
          {[0,30,60,90,120,150,180,210,240,270,300,330].map(a => (
            <rect key={a} x="48.5" y="6" width="3" height="14" rx="1.5"
              fill="#F5D67A" transform={`rotate(${a} 50 50)`} opacity="0.8"/>
          ))}
          <circle cx="50" cy="50" r="28" fill="url(#g-sun)"/>
          <circle cx="42" cy="48" r="2.2" fill="#1B2654"/>
          <circle cx="58" cy="48" r="2.2" fill="#1B2654"/>
          <path d="M43 56 Q50 62 57 56" stroke="#1B2654" strokeWidth="1.8" fill="none" strokeLinecap="round"/>
          <ellipse cx="38" cy="55" rx="3" ry="2" fill="#E89B8B" opacity="0.6"/>
          <ellipse cx="62" cy="55" rx="3" ry="2" fill="#E89B8B" opacity="0.6"/>
        </g>
      </svg>
    </div>
  );
}

// ============================================================
// Reveal — fade-up on scroll
// ============================================================
function Reveal({ children, delay = 0, as = "div", ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) { setTimeout(() => setShown(true), delay); io.disconnect(); }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  const Tag = as;
  return (
    <Tag ref={ref} className={`reveal ${shown ? "in" : ""} ${rest.className || ""}`} {...rest}>
      {children}
    </Tag>
  );
}

// ============================================================
// Animated counter — counts up when in view
// ============================================================
function Counter({ value, decimal = false, suffix = "" }) {
  const ref = useRef(null);
  const [n, setN] = useState(0);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    let started = false;
    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !started) {
        started = true;
        const start = performance.now();
        const dur = 1600;
        const tick = (t) => {
          const p = Math.min(1, (t - start) / dur);
          const eased = 1 - Math.pow(1 - p, 3);
          setN(value * eased);
          if (p < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
      }
    }, { threshold: 0.3 });
    io.observe(el);
    return () => io.disconnect();
  }, [value]);
  const display = decimal
    ? n.toFixed(1)
    : Math.round(n).toLocaleString("ar-EG");
  return <span ref={ref}>{display}{suffix}</span>;
}

// ============================================================
// Floating decorative shapes for backgrounds
// ============================================================
function FloatingDeco({ variant = "hero" }) {
  if (variant === "hero") {
    return (
      <div className="bg-ambient" aria-hidden="true">
        <div className="blob" style={{ top: "-10%", right: "-5%", width: 480, height: 480, background: "radial-gradient(circle, rgba(245,214,122,0.5), transparent 70%)" }}/>
        <div className="blob" style={{ bottom: "-15%", left: "-10%", width: 520, height: 520, background: "radial-gradient(circle, rgba(139,122,217,0.35), transparent 70%)", animationDelay: "-6s" }}/>
        <div className="blob" style={{ top: "30%", left: "40%", width: 320, height: 320, background: "radial-gradient(circle, rgba(143,184,232,0.3), transparent 70%)", animationDelay: "-10s" }}/>
        <Sparkles count={8}/>
      </div>
    );
  }
  if (variant === "subtle") {
    return (
      <div className="bg-ambient" aria-hidden="true">
        <div className="blob" style={{ top: "20%", right: "-10%", width: 360, height: 360, background: "radial-gradient(circle, rgba(217,164,65,0.18), transparent 70%)" }}/>
        <div className="blob" style={{ bottom: "10%", left: "-10%", width: 380, height: 380, background: "radial-gradient(circle, rgba(139,122,217,0.18), transparent 70%)", animationDelay: "-8s" }}/>
      </div>
    );
  }
  return null;
}

function Sparkles({ count = 6 }) {
  const pts = useRef(
    Array.from({ length: count }).map(() => ({
      top: 5 + Math.random() * 85,
      left: 5 + Math.random() * 90,
      d: Math.random() * 4,
      s: 0.6 + Math.random() * 0.8,
    }))
  ).current;
  return pts.map((p, i) => (
    <span key={i} className="sparkle"
      style={{ top: `${p.top}%`, left: `${p.left}%`, animationDelay: `${p.d}s`, transform: `scale(${p.s})` }}/>
  ));
}

Object.assign(window, { Icon, Mascot, Reveal, Counter, FloatingDeco, Sparkles });

// ============================================================
// I18N + THEME CONTEXT
// ============================================================
const EyadCtx = React.createContext({
  lang: "ar", theme: "light", t: {},
  setLang: () => {}, setTheme: () => {},
});

function EyadProvider({ children }) {
  const [lang, setLangState] = useState(() => {
    try { return localStorage.getItem("eyad-lang") || "ar"; } catch { return "ar"; }
  });
  const [theme, setThemeState] = useState(() => {
    try { return localStorage.getItem("eyad-theme") || "light"; } catch { return "light"; }
  });

  useEffect(() => {
    document.documentElement.setAttribute("lang", window.I18N[lang].htmlLang);
    document.documentElement.setAttribute("dir", window.I18N[lang].dir);
    try { localStorage.setItem("eyad-lang", lang); } catch {}
  }, [lang]);

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    try { localStorage.setItem("eyad-theme", theme); } catch {}
  }, [theme]);

  const setLang = (l) => setLangState(l);
  const setTheme = (th) => setThemeState(th);

  const t = window.I18N[lang];
  return (
    <EyadCtx.Provider value={{ lang, theme, t, setLang, setTheme }}>
      {children}
    </EyadCtx.Provider>
  );
}

function useEyad() { return React.useContext(EyadCtx); }
function useT() { return React.useContext(EyadCtx).t; }

Object.assign(window, { EyadCtx, EyadProvider, useEyad, useT });
