/* global React */
const { useState, useEffect, useRef } = React;

// ============================================================
// SVG primitives
// ============================================================
const HexLogo = ({ size = 40 }) => (
  <svg width={size} height={size * 1.1} viewBox="0 0 40 44" fill="none" aria-hidden="true">
    <path d="M20 1.5 L37.5 11 V33 L20 42.5 L2.5 33 V11 Z"
      stroke="url(#hexg)" strokeWidth="1.5" fill="#0a0a0a" />
    <path d="M20 6 L33 13.5 V30.5 L20 38 L7 30.5 V13.5 Z"
      stroke="rgba(255,106,0,0.3)" strokeWidth="0.8" fill="none" />
    <text x="20" y="26" textAnchor="middle" fontFamily="Anton, sans-serif"
      fontSize="11" fill="#FF6A00" letterSpacing="0.5">RS</text>
    <defs>
      <linearGradient id="hexg" x1="0" y1="0" x2="40" y2="44">
        <stop offset="0" stopColor="#FF6A00" />
        <stop offset="1" stopColor="#F15A24" />
      </linearGradient>
    </defs>
  </svg>
);

const ArrowR = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
    <path d="M2 7 H12 M8 3 L12 7 L8 11" stroke="currentColor" strokeWidth="1.5" />
  </svg>
);

const ServiceIcon = ({ kind }) => {
  const common = { width: 36, height: 36, viewBox: "0 0 36 36", fill: "none", stroke: "currentColor", strokeWidth: 1.5 };
  const map = {
    ui: <svg {...common}><rect x="3" y="6" width="30" height="22" /><rect x="7" y="11" width="10" height="3" /><rect x="7" y="17" width="14" height="3" /><circle cx="27" cy="18" r="3" /></svg>,
    concept: <svg {...common}><path d="M5 30 L12 14 L18 22 L24 10 L31 30 Z" /><circle cx="11" cy="9" r="3" /></svg>,
    art2d: <svg {...common}><path d="M18 4 L32 12 V24 L18 32 L4 24 V12 Z" /><path d="M18 12 L24 16 V20 L18 24 L12 20 V16 Z" /></svg>,
    arabic: <svg {...common}><path d="M8 8 H28 M8 14 H22 M8 20 H26 M8 26 H18" /><circle cx="30" cy="22" r="3" /></svg>,
    direction: <svg {...common}><circle cx="18" cy="18" r="13" /><path d="M18 8 V18 L25 23" /><path d="M14 14 L22 22" /></svg>,
    branding: <svg {...common}><path d="M6 6 H30 V20 L18 30 L6 20 Z" /><circle cx="18" cy="14" r="3" /></svg>,
    pod: <svg {...common}><circle cx="12" cy="14" r="4" /><circle cx="24" cy="14" r="4" /><path d="M4 28 C4 22 28 22 32 28" /></svg>
  };
  return <span className="service-icon">{map[kind]}</span>;
};

// ============================================================
// Nav
// ============================================================
const Nav = ({ lang, setLang, t, setTweak }) => {
  const links = [
    { href: "#home",      label: { en: "Home",     ar: "الرئيسية" } },
    { href: "#about",     label: { en: "About",    ar: "عن الاستوديو" } },
    { href: "#services",  label: { en: "Services", ar: "الخدمات" } },
    { href: "#work",      label: { en: "Work",     ar: "أعمالنا" } },
    { href: "#process",   label: { en: "Process",  ar: "العملية" } },
    { href: "#contact",   label: { en: "Contact",  ar: "تواصل" } }
  ];
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href="#home" className="brand">
          <HexLogo />
          <div className="brand-name">RAWA STUDIOS<small>BY RAWA GAMES</small></div>
        </a>
        <div className="nav-links">
          {links.map(l => (
            <a key={l.href} href={l.href} className="nav-link">{l.label[lang]}</a>
          ))}
          <div className="lang-toggle">
            <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
            <button className={lang === "ar" ? "on" : ""} onClick={() => setLang("ar")}>AR</button>
          </div>
          <a href="#contact" className="btn btn-primary">
            {lang === "ar" ? "ابدأ مشروعك" : "Start a Project"}
          </a>
        </div>
      </div>
    </nav>
  );
};

// ============================================================
// Hex placeholder (for game art slots)
// ============================================================
const HexSlot = ({ label, sub, className = "" }) => (
  <div className={`hex-frame ${className}`}>
    <div className="hex-label">
      <strong>{label}</strong>
      {sub}
    </div>
  </div>
);

const Placeholder = ({ label, sub, style, className = "" }) => (
  <div className={`placeholder ${className}`} style={style}>
    <div className="ph-label">
      <strong>{label}</strong>
      {sub}
    </div>
  </div>
);

const ImageSlot = ({ src, alt, caption, className = "" }) => (
  <figure className={`image-slot ${className}`}>
    <img src={src} alt={alt} loading="lazy" />
    {caption && <figcaption>{caption}</figcaption>}
  </figure>
);

const ThreeModelCard = ({
  src,
  title,
  kicker,
  align = "left",
  background,
  cameraZ = 5.8,
  lift = 0,
  modelScale = 2.1,
  exposure = 1.08,
  ambientIntensity = 2.1,
  keyIntensity = 3.4,
  rimIntensity = 2.2
}) => {
  const canvasRef = useRef(null);
  const frameRef = useRef(null);

  useEffect(() => {
    let renderer;
    let scene;
    let camera;
    let model;
    let mixer;
    let animationId;
    let cleanup = () => {};
    let pointer = { x: 0, y: 0 };
    let active = true;

    function init() {
      if (!active || !canvasRef.current || !frameRef.current || !window.RAWA_THREE) return;

      const { THREE, GLTFLoader } = window.RAWA_THREE;
      const canvas = canvasRef.current;
      const frame = frameRef.current;
      const clock = new THREE.Clock();

      scene = new THREE.Scene();
      camera = new THREE.PerspectiveCamera(28, 1, 0.1, 100);
      camera.position.set(0, 0.35, cameraZ);
      camera.lookAt(0, 0.2, 0);

      renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true });
      renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
      renderer.outputColorSpace = THREE.SRGBColorSpace;
      renderer.toneMapping = THREE.ACESFilmicToneMapping;
      renderer.toneMappingExposure = exposure;

      scene.add(new THREE.HemisphereLight(0xd7e7ff, 0x3a2416, ambientIntensity));

      const key = new THREE.DirectionalLight(0xffffff, keyIntensity);
      key.position.set(3, 5, 5);
      scene.add(key);

      const fill = new THREE.DirectionalLight(0xffd2a0, ambientIntensity * 0.7);
      fill.position.set(-3, 1.8, 4);
      scene.add(fill);

      const rim = new THREE.DirectionalLight(0x66a8ff, rimIntensity);
      rim.position.set(-4, 2, -2);
      scene.add(rim);

      const loader = new GLTFLoader();
      loader.load(src, (gltf) => {
        if (!active) return;
        model = gltf.scene;
        model.traverse((child) => {
          if (!child.isMesh) return;
          child.castShadow = true;
          child.receiveShadow = true;
          if (child.material && child.material.map) {
            child.material.map.colorSpace = THREE.SRGBColorSpace;
          }
        });

        const box = new THREE.Box3().setFromObject(model);
        const center = box.getCenter(new THREE.Vector3());
        const size = box.getSize(new THREE.Vector3());
        const maxSize = Math.max(size.x, size.y, size.z) || 1;
        model.position.sub(center);
        model.position.y += lift;
        model.scale.setScalar(modelScale / maxSize);
        model.rotation.y = align === "right" ? -0.36 : 0.36;
        scene.add(model);

        if (gltf.animations && gltf.animations.length) {
          mixer = new THREE.AnimationMixer(model);
          mixer.clipAction(gltf.animations[0]).play();
        }
      });

      function resize() {
        if (!frame || !renderer || !camera) return;
        const width = Math.max(1, frame.clientWidth);
        const height = Math.max(1, frame.clientHeight);
        renderer.setSize(width, height, false);
        camera.aspect = width / height;
        camera.updateProjectionMatrix();
      }

      function onPointerMove(event) {
        const rect = frame.getBoundingClientRect();
        pointer = {
          x: ((event.clientX - rect.left) / rect.width - 0.5) * 2,
          y: ((event.clientY - rect.top) / rect.height - 0.5) * 2
        };
      }

      function animate() {
        animationId = requestAnimationFrame(animate);
        const delta = clock.getDelta();
        if (mixer) mixer.update(delta);
        if (model) {
          const base = align === "right" ? -0.36 : 0.36;
          model.rotation.y += (base + pointer.x * 0.18 - model.rotation.y) * 0.06;
          model.rotation.x += (-pointer.y * 0.08 - model.rotation.x) * 0.06;
        }
        renderer.render(scene, camera);
      }

      resize();
      animate();
      window.addEventListener("resize", resize);
      frame.addEventListener("pointermove", onPointerMove);

      cleanup = () => {
        window.removeEventListener("resize", resize);
        frame.removeEventListener("pointermove", onPointerMove);
        if (animationId) cancelAnimationFrame(animationId);
        if (renderer) renderer.dispose();
        if (scene) {
          scene.traverse((child) => {
            if (child.geometry) child.geometry.dispose();
            if (child.material) {
              const materials = Array.isArray(child.material) ? child.material : [child.material];
              materials.forEach((material) => material.dispose());
            }
          });
        }
      };
    }

    if (window.RAWA_THREE) init();
    else window.addEventListener("rawa-three-ready", init, { once: true });

    return () => {
      active = false;
      window.removeEventListener("rawa-three-ready", init);
      cleanup();
    };
  }, [src, align, cameraZ, lift, modelScale, exposure, ambientIntensity, keyIntensity, rimIntensity]);

  return (
    <figure
      className={`duel-card duel-card-${align}`}
      style={background ? { "--duel-card-bg": `url("${background}")` } : undefined}
    >
      <div className="duel-model-frame" ref={frameRef}>
        <canvas ref={canvasRef} aria-label={title} />
      </div>
      <figcaption>
        <span>{kicker}</span>
        <strong>{title}</strong>
      </figcaption>
    </figure>
  );
};

const ArenaDuelSection = ({ lang }) => (
  <section className="arena-duel" id="arena-duel">
    <div className="arena-duel-bg" aria-hidden="true" />
    <div className="arena-duel-shade" aria-hidden="true" />
    <div className="arena-duel-inner">
      <div className="arena-duel-copy">
        <div className="sec-tag"><span className="num">00</span>{lang === "ar" ? "فن ثلاثي الأبعاد" : "3D Art Production"}</div>
        <h2 className="h-display arena-duel-title">
          {lang === "ar" ? "نصنع فنًا ثلاثي الأبعاد للألعاب والعوالم." : <>WE CREATE<br/><span>3D ART.</span></>}
        </h2>
      </div>
      <div className="arena-duel-cards">
        <ThreeModelCard
          src="assets/arena/timbercrest-inn.glb"
          title="Timbercrest Inn"
          kicker={lang === "ar" ? "بيئة ثلاثية الأبعاد" : "3D Environment"}
          align="left"
          cameraZ={8.2}
          lift={0}
          modelScale={2.35}
          exposure={0.98}
          ambientIntensity={1.7}
          keyIntensity={3}
          rimIntensity={1.8}
        />
        <ThreeModelCard
          src="assets/arena/golden-regent.glb"
          title="Tatar Emperor"
          kicker={lang === "ar" ? "إمبراطور التتار" : "Tatar Empire"}
          align="left"
          cameraZ={6.9}
          lift={0.18}
          modelScale={2.44}
          exposure={1.34}
          ambientIntensity={3.4}
          keyIntensity={4.2}
          rimIntensity={2.8}
        />
        <ThreeModelCard
          src="assets/arena/azure-hoplite.glb"
          title="Greek Soldier"
          kicker={lang === "ar" ? "جندي يوناني" : "Greek Army"}
          align="right"
          cameraZ={6.7}
          lift={0.22}
          modelScale={2.48}
        />
        <ThreeModelCard
          src="assets/arena/crimson-dome-hospital.glb"
          title="Hospital Building"
          kicker={lang === "ar" ? "عمارة طبية" : "3D Architecture"}
          align="center"
          cameraZ={7.8}
          lift={0.02}
          modelScale={2.28}
          exposure={0.98}
          ambientIntensity={1.65}
          keyIntensity={2.9}
          rimIntensity={1.7}
        />
      </div>
    </div>
  </section>
);

// ============================================================
// HERO
// ============================================================
const Hero = ({ lang, variant }) => {
  const [headlineIdx, setHeadlineIdx] = useState(0);
  const headlines_en = [
    ["GAME ART", <><span className="accent">& UI/UX</span></>, <><span className="stroke">FOR THE GCC</span></>],
    ["ARABIC-FIRST", <><span className="accent">GAME ART</span></>, <><span className="stroke">DIRECTION</span></>],
    ["MAKING GAMES", <><span className="accent">WORTH</span></>, <><span className="stroke">PLAYING</span></>]
  ];
  const headline_ar = [
    ["فن ألعاب", <span className="accent">وتجربة مستخدم</span>, <span className="stroke">للسوق الخليجي</span>]
  ];
  const heads = lang === "ar" ? headline_ar : headlines_en;
  useEffect(() => {
    const i = setInterval(() => setHeadlineIdx(x => (x + 1) % heads.length), 4500);
    return () => clearInterval(i);
  }, [heads.length]);

  const chips_en = ["Game UI/UX", "2D Art", "Concept Art", "Arabic UX", "Live-Ops", "Creative Direction"];
  const chips_ar = ["تصميم الواجهات", "الرسم 2D", "التصميم التصوري", "تجربة عربية", "تشغيل مستمر", "إخراج فني"];
  const chips = lang === "ar" ? chips_ar : chips_en;
  const chipPos = [
    { top: "8%", left: "-8%" },
    { top: "22%", right: "-6%" },
    { top: "48%", left: "-12%" },
    { bottom: "26%", right: "-8%" },
    { bottom: "8%", left: "8%" },
    { top: "62%", right: "8%" }
  ];

  const videoRef = useRef(null);
  const scrollPhase = useRef('idle'); // 'idle' | 'playing' | 'done'
  const touchStartY = useRef(0);

  // Seek to first frame once video data is ready
  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    const seek = () => { v.currentTime = 0.001; };
    if (v.readyState >= 2) seek();
    else v.addEventListener('loadeddata', seek, { once: true });
  }, []);

  // Attach all scroll + video-time handlers
  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;

    function startPlay() {
      if (scrollPhase.current !== 'idle') return;
      scrollPhase.current = 'playing';
      v.play().catch(() => {});
    }

    function onTouchStart(e) { touchStartY.current = e.touches[0].clientY; }
    function onTouchMove(e) {
      e.preventDefault();
      if (touchStartY.current - e.touches[0].clientY > 10) startPlay();
    }
    function onWheel(e) {
      e.preventDefault();
      if (e.deltaY > 0) startPlay();
    }
    function onKeyDown(e) {
      const fwd = ['ArrowDown', 'PageDown', ' '];
      if (fwd.includes(e.key)) { e.preventDefault(); startPlay(); }
      else if (['ArrowUp', 'PageUp'].includes(e.key)) e.preventDefault();
    }

    function unlock() {
      if (scrollPhase.current === 'done') return;
      scrollPhase.current = 'done';
      v.pause();
      window.removeEventListener('wheel', onWheel);
      window.removeEventListener('touchstart', onTouchStart);
      window.removeEventListener('touchmove', onTouchMove);
      window.removeEventListener('keydown', onKeyDown);
    }

    function onTimeUpdate() { if (v.currentTime >= 3) unlock(); }
    function onEnded() { unlock(); }

    v.addEventListener('timeupdate', onTimeUpdate);
    v.addEventListener('ended', onEnded);
    window.addEventListener('wheel', onWheel, { passive: false });
    window.addEventListener('touchstart', onTouchStart, { passive: true });
    window.addEventListener('touchmove', onTouchMove, { passive: false });
    window.addEventListener('keydown', onKeyDown);

    return () => {
      v.removeEventListener('timeupdate', onTimeUpdate);
      v.removeEventListener('ended', onEnded);
      window.removeEventListener('wheel', onWheel);
      window.removeEventListener('touchstart', onTouchStart);
      window.removeEventListener('touchmove', onTouchMove);
      window.removeEventListener('keydown', onKeyDown);
    };
  }, []);

  return (
    <section className="hero" id="home">
      <video
        ref={videoRef}
        className="hero-video"
        src="hero-bg.mp4"
        muted
        playsInline
        preload="auto"
      />
      <div className="hero-video-overlay" />
      <div className="hero-grid" />
      <div className="container">
        <div className="hero-content">
          <div className="hero-text">
            <div className="hero-tag">
              <span className="dot" />
              {lang === "ar" ? "ذراع الخدمات الإبداعية لشركة RAWA GAMES" : "CREATIVE SERVICES ARM OF RAWA GAMES"}
            </div>
            <h1 className="h-display hero-headline">
              {heads[headlineIdx].map((line, i) => <div key={i}>{line}</div>)}
            </h1>
            <p className="hero-sub">
              {lang === "ar"
                ? "نساعد فرق الألعاب والمنتجات الرقمية على بناء تجارب بصرية قوية، مناسبة ثقافياً، وجاهزة للاعب العربي. تصميم واجهات، فن ثنائي الأبعاد، تصميم تصوري، وإخراج فني — مصمم خصيصاً للسوق الخليجي."
                : "Rawa Studios helps game companies, startups, and digital product teams create culturally relevant, visually powerful, and commercially ready experiences for Arabic-speaking players."}
            </p>
            <div className="hero-cta">
              <a href="#contact" className="btn btn-primary">
                {lang === "ar" ? "ابدأ مشروعك" : "Start a Project"} <ArrowR />
              </a>
              <a href="#work" className="btn btn-ghost">
                {lang === "ar" ? "شاهد أعمالنا" : "View Our Work"}
              </a>
            </div>
            <div className="hero-trust">
              {lang === "ar" ? "من صناع " : "From the creators of "}
              <strong>SWORD OF RULE</strong>
              <span className="pipe" />
              <strong>NAJLA</strong>
            </div>
          </div>

          {variant !== "no-art" && (
            <div className="hero-visual">
              <div className="tactical-frame" />
              {variant === "single" && (
                <Placeholder
                  label="HERO GAME ART"
                  sub="Sword of Rule key visual"
                  style={{ position: "absolute", inset: 0 }}
                />
              )}
              <div className="hero-chips">
                {chips.map((c, i) => (
                  <div key={i} className="hero-chip" style={{...chipPos[i], animationDelay: `${i * 0.4}s`}}>{c}</div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
};

// ============================================================
// Marquee strip
// ============================================================
const MarqueeStrip = ({ lang }) => {
  const items_en = [
    "Arabic-First Game Production",
    "Original Handcrafted Art",
    "Strategy & Mobile Game Experience",
    "Live-Service Roadmap",
    "Saudi / GCC Market Focus",
    "Production-Ready Delivery"
  ];
  const items_ar = [
    "إنتاج ألعاب عربية أولاً",
    "فن أصلي يدوي الصنع",
    "خبرة في الاستراتيجية والجوال",
    "خارطة طريق خدمة حية",
    "تركيز على السوق الخليجي",
    "تسليم جاهز للإنتاج"
  ];
  const items = lang === "ar" ? items_ar : items_en;
  const doubled = [...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {doubled.map((it, i) => (
          <div key={i} className="marquee-item">
            <span className="dot" />{it}
          </div>
        ))}
      </div>
    </div>
  );
};

Object.assign(window, { HexLogo, ArrowR, ServiceIcon, Nav, HexSlot, Placeholder, ImageSlot, ThreeModelCard, ArenaDuelSection, Hero, MarqueeStrip });
