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

/* ============================================================
   Shared Logo (inline SVG, simple — circular wireframe + "DRONE TEAM")
============================================================ */
function Logo({ size = 36, white = false }) {
  // Real Droneteam mark (circular)
  const src = white ? "assets/droneteam-mark-white.png" : "assets/droneteam-mark.jpg";
  return (
    <img src={src} alt="Droneteam" width={size} height={size}
      style={{ width: size, height: size, display: "block", objectFit: "contain" }} />
  );
}

// Full lockup (mark + wordmark)
function LogoFull({ height = 32, white = false }) {
  const src = white ? "assets/droneteam-logo-white.png" : "assets/droneteam-logo-dark.png";
  return <img src={src} alt="DRONETEAM" style={{ height, width: "auto", display: "block" }} />;
}

/* ============================================================
   Top Nav
============================================================ */
function Nav({ page, setPage, lang, setLang }) {
  const serviceItems = [
    { id: "services", label: "All services", desc: "Six service lines · overview" },
    { id: "photogrammetry", label: "Photogrammetry", desc: "3D scanning · smart cities · heritage" },
    { id: "lightshows", label: "Drone light shows", desc: "Choreographed LED formations" },
  ];
  return (
    <nav className="nav">
      <div className="nav-inner">
        <div className="brand" onClick={() => setPage("home")}>
          <LogoFull height={36} />
          <div style={{ width: 1, height: 30, background: "var(--ink)", opacity: 0.7, margin: "0 6px" }} />
          <img src="assets/parrot-black.png" alt="Parrot" style={{ height: 22, width: "auto", display: "block" }} />
        </div>
        <div className="nav-links">
          <div className={"nav-link" + (page === "home" ? " active" : "")} onClick={() => setPage("home")}>Home</div>

          <div className={"nav-link nav-dropdown" + (["services","photogrammetry","lightshows"].includes(page) ? " active" : "")}>
            <span onClick={() => setPage("services")}>Services <span style={{ fontSize: 9, marginLeft: 4, opacity: 0.6 }}>▾</span></span>
            <div className="nav-dropdown-menu">
              {serviceItems.map(s => (
                <div key={s.id} className="nav-dropdown-item" onClick={() => setPage(s.id)}>
                  <div className="nav-dropdown-label">{s.label}</div>
                  <div className="nav-dropdown-desc">{s.desc}</div>
                </div>
              ))}
            </div>
          </div>

          <div className={"nav-link" + (page === "products" ? " active" : "")} onClick={() => setPage("products")}>Products</div>
          <div className={"nav-link" + (page === "training" ? " active" : "")} onClick={() => setPage("training")}>Training</div>
          <div className={"nav-link" + (page === "contact" ? " active" : "")} onClick={() => setPage("contact")}>Contact</div>
        </div>
        <div className="nav-right">
          <div className="lang-toggle">
            <span className={"lang" + (lang === "EN" ? " active" : "")} onClick={() => setLang("EN")}>EN</span>
            <span style={{opacity: 0.3}}>/</span>
            <span className={"lang" + (lang === "LT" ? " active" : "")} onClick={() => setLang("LT")}>LT</span>
          </div>
          <button className="btn" onClick={() => setPage("contact")}>
            Enquire <span className="arrow">→</span>
          </button>
        </div>
      </div>
      <style>{`
        .nav-dropdown { position: relative; }
        .nav-dropdown-menu {
          position: absolute; top: calc(100% + 14px); left: -16px;
          min-width: 280px; background: #fff; border: 1px solid var(--line);
          box-shadow: 0 20px 40px rgba(10,22,34,0.08);
          padding: 8px; opacity: 0; visibility: hidden;
          transform: translateY(-4px); transition: opacity .18s, transform .18s, visibility .18s;
          z-index: 60;
        }
        .nav-dropdown:hover .nav-dropdown-menu,
        .nav-dropdown:focus-within .nav-dropdown-menu {
          opacity: 1; visibility: visible; transform: translateY(0);
        }
        /* invisible bridge so the gap between trigger and menu doesn't kill hover */
        .nav-dropdown::after {
          content: ""; position: absolute; left: 0; right: 0; top: 100%; height: 18px;
        }
        .nav-dropdown-item {
          padding: 12px 14px; cursor: pointer;
          border-left: 2px solid transparent; transition: background .15s, border-color .15s;
        }
        .nav-dropdown-item:hover { background: var(--bg-soft); border-left-color: var(--brand); }
        .nav-dropdown-label { font-size: 14px; font-weight: 500; color: var(--ink); margin-bottom: 2px; }
        .nav-dropdown-desc { font-family: var(--mono); font-size: 10.5px; letter-spacing: 0.08em; color: var(--ink-3); text-transform: uppercase; }
      `}</style>
    </nav>
  );
}

/* ============================================================
   Footer
============================================================ */
function Footer({ setPage }) {
  return (
    <footer className="site">
      <div className="container">
        <div className="grid">
          <div className="col">
            <div style={{marginBottom: 18}}>
              <LogoFull height={40} white />
            </div>
            <div style={{display: "flex", alignItems: "center", gap: 10, marginBottom: 16}}>
              <span style={{fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.2em", color: "rgba(255,255,255,0.5)"}}>OFFICIAL RESELLER</span>
              <img src="assets/parrot-white.png" alt="Parrot" style={{height: 16, width: "auto", opacity: 0.9}} />
            </div>
            <p style={{maxWidth: 320}}>
              Professional drone services and the full Parrot ANAFI UKR range — part of UAB IT Logika, operating in Lithuania since 2011.
            </p>
          </div>
          <div className="col">
            <h4>Sitemap</h4>
            <a onClick={() => setPage("home")}>Home</a>
            <a onClick={() => setPage("services")}>Services</a>
            <a onClick={() => setPage("photogrammetry")}>Photogrammetry</a>
            <a onClick={() => setPage("lightshows")}>Drone light shows</a>
            <a onClick={() => setPage("products")}>Products</a>
            <a onClick={() => setPage("training")}>Training</a>
            <a onClick={() => setPage("contact")}>Contact</a>
          </div>
          <div className="col">
            <h4>Products</h4>
            <a onClick={() => setPage("products")}>Parrot ANAFI UKR</a>
            <a onClick={() => setPage("products")}>ANAFI UKR GOV</a>
            <a onClick={() => setPage("products")}>XLR Battery</a>
            <a onClick={() => setPage("products")}>Accessories</a>
          </div>
          <div className="col">
            <h4>Contact</h4>
            <p>Dr. Linas Gelazanskas</p>
            <p>linas@droneteam.lt</p>
            <p>+370 682 10215</p>
            <p>Vilnius, Lithuania</p>
          </div>
        </div>
        <div className="small">
          <span>© 2026 DRONETEAM · A SERVICE OF UAB IT LOGIKA</span>
          <span>PRIVACY · COOKIES · TERMS</span>
        </div>
      </div>
    </footer>
  );
}

/* ============================================================
   Photo placeholder
============================================================ */
function Ph({ tag, label, dark, ratio = "16/10", style = {} }) {
  return (
    <div className={"ph" + (dark ? " dark" : "")} style={{ aspectRatio: ratio, ...style }}>
      {tag && <div className="ph-tag">{tag}</div>}
      <span>{label || "Replace with photo"}</span>
    </div>
  );
}

/* ============================================================
   Point-cloud / wireframe canvas — homage to existing droneteam.lt hero
   Animated photogrammetry-style scene: scatter point cloud + drone path
============================================================ */
function PointCloudHero({ height = 560 }) {
  const canvasRef = useRef(null);
  const animRef = useRef(0);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    const ctx = canvas.getContext("2d");

    let W = 0, H = 0;
    function resize() {
      const r = canvas.getBoundingClientRect();
      W = r.width; H = r.height;
      canvas.width = W * dpr; canvas.height = H * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas);

    // Build a scattered "point cloud" of a city/terrain.
    const NUM_POINTS = 1400;
    const points = [];
    for (let i = 0; i < NUM_POINTS; i++) {
      // Two clusters: ground plane and building blobs
      const ground = Math.random() < 0.55;
      let x, y, z, h;
      if (ground) {
        x = (Math.random() - 0.5) * 1.8;
        z = (Math.random() - 0.5) * 1.6;
        h = (Math.random() - 0.5) * 0.04;
      } else {
        // pick a building cluster
        const cx = (Math.random() - 0.5) * 1.6;
        const cz = (Math.random() - 0.5) * 1.4;
        const cw = 0.05 + Math.random() * 0.18;
        const cd = 0.05 + Math.random() * 0.18;
        const ch = 0.08 + Math.random() * 0.4;
        x = cx + (Math.random() - 0.5) * cw;
        z = cz + (Math.random() - 0.5) * cd;
        h = Math.random() * ch;
      }
      points.push({ x, y: h, z, c: Math.random() });
    }

    // Drone waypoints in a ring above the scene
    const NUM_DRONES = 14;
    const drones = [];
    for (let i = 0; i < NUM_DRONES; i++) {
      const a = (i / NUM_DRONES) * Math.PI * 2;
      drones.push({
        a,
        r: 0.85 + (i % 2) * 0.15,
        y: 0.55 + Math.sin(i * 1.3) * 0.08,
      });
    }

    let t0 = performance.now();
    function frame(now) {
      const t = (now - t0) / 1000;
      const yaw = t * 0.08;
      const cosY = Math.cos(yaw), sinY = Math.sin(yaw);
      const pitch = -0.55;
      const cosP = Math.cos(pitch), sinP = Math.sin(pitch);

      ctx.clearRect(0, 0, W, H);

      // dark gradient background
      const grad = ctx.createRadialGradient(W * 0.5, H * 0.65, 50, W * 0.5, H * 0.65, Math.max(W, H) * 0.8);
      grad.addColorStop(0, "#0e2238");
      grad.addColorStop(0.6, "#06101a");
      grad.addColorStop(1, "#03080f");
      ctx.fillStyle = grad;
      ctx.fillRect(0, 0, W, H);

      // project helper
      const cx = W / 2, cy = H * 0.62;
      const scale = Math.min(W, H) * 0.62;
      function project(px, py, pz) {
        // rotate yaw on Y
        const x1 = px * cosY - pz * sinY;
        const z1 = px * sinY + pz * cosY;
        const y1 = py;
        // rotate pitch on X
        const y2 = y1 * cosP - z1 * sinP;
        const z2 = y1 * sinP + z1 * cosP;
        // translate camera back
        const z3 = z2 + 2.2;
        const f = 1.6 / z3;
        return { x: cx + x1 * f * scale, y: cy - y2 * f * scale, depth: z3 };
      }

      // Grid floor
      ctx.strokeStyle = "rgba(92,214,114,0.10)";
      ctx.lineWidth = 1;
      const STEP = 0.1;
      for (let i = -8; i <= 8; i++) {
        const a = project(i * STEP, 0, -0.8);
        const b = project(i * STEP, 0, 0.8);
        ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
      }
      for (let i = -8; i <= 8; i++) {
        const a = project(-0.8, 0, i * STEP);
        const b = project(0.8, 0, i * STEP);
        ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
      }

      // Points
      for (const p of points) {
        const pr = project(p.x, p.y, p.z);
        if (pr.depth < 0.4) continue;
        const size = Math.max(0.5, 1.6 / pr.depth);
        const tone = 200 + Math.floor(p.c * 55);
        ctx.fillStyle = `rgba(${tone},${tone+5},${tone+15},${0.55 + p.c * 0.35})`;
        ctx.fillRect(pr.x, pr.y, size, size);
      }

      // Drone wireframe pyramids + connecting links
      const droneScreen = [];
      for (const d of drones) {
        const a = d.a + t * 0.18;
        const x = Math.cos(a) * d.r;
        const z = Math.sin(a) * d.r;
        const y = d.y + Math.sin(t * 0.6 + a * 2) * 0.02;
        const apex = project(x, y, z);
        // 4 footprint corners projected on ground (frustum)
        const fpts = [
          project(x - 0.13, 0, z - 0.13),
          project(x + 0.13, 0, z - 0.13),
          project(x + 0.13, 0, z + 0.13),
          project(x - 0.13, 0, z + 0.13),
        ];
        droneScreen.push({ apex, fpts });
      }

      // links between adjacent drones — green
      ctx.strokeStyle = "rgba(92,214,114,0.55)";
      ctx.lineWidth = 1.2;
      for (let i = 0; i < droneScreen.length; i++) {
        const a = droneScreen[i].apex;
        const b = droneScreen[(i + 1) % droneScreen.length].apex;
        ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
      }

      // each drone's view frustum — blue lines + ground rectangle
      for (const ds of droneScreen) {
        ctx.strokeStyle = "rgba(78,163,255,0.55)";
        ctx.lineWidth = 1;
        // frustum lines
        for (const fp of ds.fpts) {
          ctx.beginPath();
          ctx.moveTo(ds.apex.x, ds.apex.y);
          ctx.lineTo(fp.x, fp.y);
          ctx.stroke();
        }
        // ground rect
        ctx.beginPath();
        ctx.moveTo(ds.fpts[0].x, ds.fpts[0].y);
        for (let i = 1; i < 4; i++) ctx.lineTo(ds.fpts[i].x, ds.fpts[i].y);
        ctx.closePath();
        ctx.strokeStyle = "rgba(78,163,255,0.7)";
        ctx.stroke();
      }

      // drone bodies — green dot + blue ring
      for (const ds of droneScreen) {
        ctx.beginPath();
        ctx.arc(ds.apex.x, ds.apex.y, 5, 0, Math.PI * 2);
        ctx.fillStyle = "#5cd672";
        ctx.fill();
        ctx.beginPath();
        ctx.arc(ds.apex.x, ds.apex.y, 9, 0, Math.PI * 2);
        ctx.strokeStyle = "rgba(78,163,255,0.7)";
        ctx.lineWidth = 1.2;
        ctx.stroke();
      }

      animRef.current = requestAnimationFrame(frame);
    }
    animRef.current = requestAnimationFrame(frame);

    return () => {
      cancelAnimationFrame(animRef.current);
      ro.disconnect();
    };
  }, []);

  return (
    <div style={{ position: "relative", width: "100%", height, overflow: "hidden", background: "#06101a" }}>
      <canvas ref={canvasRef} style={{ width: "100%", height: "100%", display: "block" }} />
      {/* HUD overlays */}
      <div style={{
        position: "absolute", top: 24, left: 24,
        fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.18em",
        color: "rgba(255,255,255,0.55)", textTransform: "uppercase",
        display: "flex", gap: 20, alignItems: "center",
      }}>
        <span style={{display: "flex", gap: 8, alignItems: "center"}}>
          <span style={{width: 7, height: 7, borderRadius: "50%", background: "#5cd672", boxShadow: "0 0 8px #5cd672"}} />
          LIVE · POINT CLOUD
        </span>
        <span>1,400 PTS</span>
        <span>14 NODES</span>
      </div>
      <div style={{
        position: "absolute", bottom: 24, right: 24,
        fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.18em",
        color: "rgba(255,255,255,0.45)", textTransform: "uppercase",
      }}>
        RTK · GCP · 1—2 CM GSD
      </div>
    </div>
  );
}

window.Logo = Logo;
window.LogoFull = LogoFull;
window.Nav = Nav;
window.Footer = Footer;
window.Ph = Ph;
window.PointCloudHero = PointCloudHero;
