import React, { Suspense, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { Canvas, useFrame } from "@react-three/fiber";
import { Environment, Float, Html, OrbitControls } from "@react-three/drei";
import * as THREE from "three";
import { gsap } from "gsap";
import "./styles.css";

function KLogo() {
  const group = useRef();
  const [dragging, setDragging] = useState(false);

  useFrame((state, delta) => {
    if (!group.current) return;
    if (!dragging) {
      group.current.rotation.y += delta * 0.35;
      group.current.rotation.x = THREE.MathUtils.lerp(
        group.current.rotation.x,
        Math.sin(state.clock.elapsedTime * 0.55) * 0.18,
        0.035
      );
    }
  });

  return (
    <group
      ref={group}
      scale={1.35}
      onPointerDown={(e) => { e.stopPropagation(); setDragging(true); }}
      onPointerUp={(e) => { e.stopPropagation(); setDragging(false); }}
      onPointerOut={() => setDragging(false)}
    >
      <mesh castShadow>
        <boxGeometry args={[2.2, 2.2, 0.62]} />
        <meshPhysicalMaterial
          color="#c7b8ff"
          roughness={0.2}
          metalness={0.12}
          transmission={0.05}
          clearcoat={1}
        />
      </mesh>

      {/* Cutout-style dark K face */}
      <group position={[0, 0, 0.34]}>
        <mesh position={[-0.55, 0, 0.02]} scale={[0.18, 0.78, 0.04]}>
          <boxGeometry args={[1, 1, 1]} />
          <meshStandardMaterial color="#101018" roughness={0.35} />
        </mesh>
        <mesh position={[0.03, 0.34, 0.02]} rotation={[0, 0, -0.65]} scale={[0.15, 0.62, 0.04]}>
          <boxGeometry args={[1, 1, 1]} />
          <meshStandardMaterial color="#101018" roughness={0.35} />
        </mesh>
        <mesh position={[0.03, -0.34, 0.02]} rotation={[0, 0, 0.65]} scale={[0.15, 0.62, 0.04]}>
          <boxGeometry args={[1, 1, 1]} />
          <meshStandardMaterial color="#101018" roughness={0.35} />
        </mesh>
      </group>

      {/* pastel side accents */}
      <mesh position={[0.98, 0.65, 0.34]} scale={[0.12, 0.45, 0.05]}>
        <boxGeometry args={[1, 1, 1]} />
        <meshStandardMaterial color="#8fe8df" emissive="#315c59" emissiveIntensity={0.15} />
      </mesh>
      <mesh position={[0.98, -0.65, 0.34]} scale={[0.12, 0.45, 0.05]}>
        <boxGeometry args={[1, 1, 1]} />
        <meshStandardMaterial color="#ffd2a8" emissive="#704a2d" emissiveIntensity={0.12} />
      </mesh>
    </group>
  );
}

function Capability({ type, color, title, text }) {
  const group = useRef();
  useFrame((state) => {
    if (group.current) {
      group.current.rotation.y = state.clock.elapsedTime * 0.42;
      group.current.rotation.x = Math.sin(state.clock.elapsedTime * 0.7) * 0.18;
    }
  });

  return (
    <div className="capability-card">
      <div className="object-stage">
        <Canvas camera={{ position: [0, 0, 5.2], fov: 42 }} dpr={[1, 1.7]}>
          <ambientLight intensity={1.7} />
          <directionalLight position={[3, 4, 5]} intensity={3} />
          <pointLight position={[-3, -2, 2]} intensity={3} color={color} />
          <Suspense fallback={null}>
            <Float speed={1.5} rotationIntensity={0.25} floatIntensity={0.35}>
              <group ref={group}>
                <mesh castShadow>
                  <roundedBoxGeometry args={[1.8, 1.8, 1.8]} radius={0.18} smoothness={5} />
                  <meshPhysicalMaterial color={color} roughness={0.18} metalness={0.08} clearcoat={1} />
                </mesh>
                <Html center transform position={[0, 0, 0.94]}>
                  <div className="object-label">{type}</div>
                </Html>
              </group>
            </Float>
            <Environment preset="city" />
          </Suspense>
        </Canvas>
      </div>
      <div className="cap-copy">
        <span className="index">0{type === "AI" ? 1 : type === "WEB" ? 2 : 3}</span>
        <h3>{title}</h3>
        <p>{text}</p>
      </div>
    </div>
  );
}

const services = [
  ["AI Automation", "Agents, workflows, integrations and intelligent business systems."],
  ["Web Engineering", "Premium interfaces, dashboards and high-performance web platforms."],
  ["Full-Stack Apps", "Production-ready applications from architecture to deployment."],
  ["Custom Software", "Purpose-built tools designed around real operational problems."],
  ["Game Development", "Interactive experiences, mechanics, systems and polished worlds."],
  ["APIs & Integrations", "Reliable connections between products, services and data."],
];

function App() {
  const [menu, setMenu] = useState(false);

  const scrollTo = (id) => {
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth" });
    setMenu(false);
  };

  React.useEffect(() => {
    gsap.from(".hero-copy > *", { y: 28, opacity: 0, duration: 0.8, stagger: 0.1, ease: "power3.out" });
  }, []);

  return (
    <div className="site">
      <header className="nav">
        <button className="brand" onClick={() => scrollTo("top")}>
          <span className="brand-k">K</span>
          <span>KHILJI SOFTWARES</span>
        </button>
        <button className="menu-btn" onClick={() => setMenu(!menu)}>MENU</button>
        <nav className={menu ? "open" : ""}>
          <button onClick={() => scrollTo("services")}>Services</button>
          <button onClick={() => scrollTo("work")}>Work</button>
          <button onClick={() => scrollTo("about")}>About</button>
          <button className="nav-cta" onClick={() => scrollTo("contact")}>Start a project ↗</button>
        </nav>
      </header>

      <main id="top">
        <section className="hero">
          <div className="hero-copy">
            <p className="eyebrow">SOFTWARE / AI / DIGITAL SYSTEMS</p>
            <h1>We build <em>digital systems</em> with depth.</h1>
            <p className="lead">Khilji Softwares creates intelligent automation, web platforms, custom software and interactive products for ambitious ideas.</p>
            <div className="hero-actions">
              <button className="primary" onClick={() => scrollTo("contact")}>Build with us ↗</button>
              <button className="secondary" onClick={() => scrollTo("work")}>Explore capabilities</button>
            </div>
          </div>

          <div className="hero-3d">
            <Canvas shadows camera={{ position: [0, 0, 6], fov: 38 }} dpr={[1, 2]}>
              <color attach="background" args={["#0b0b10"]} />
              <ambientLight intensity={1.5} />
              <directionalLight castShadow position={[4, 5, 6]} intensity={4} />
              <pointLight position={[-4, -2, 3]} intensity={5} color="#b8a7ff" />
              <pointLight position={[3, 1, -1]} intensity={4} color="#8fe8df" />
              <Suspense fallback={null}>
                <Float speed={1.1} rotationIntensity={0.12} floatIntensity={0.5}>
                  <KLogo />
                </Float>
                <Environment preset="city" />
              </Suspense>
              <OrbitControls enableZoom={false} enablePan={false} autoRotate={false} />
            </Canvas>
            <div className="drag-note">DRAG THE K / EXPLORE DEPTH</div>
          </div>
        </section>

        <section className="marquee"><div>AI AUTOMATION · WEB ENGINEERING · FULL-STACK · CUSTOM SOFTWARE · GAME DEVELOPMENT · APIS ·</div></section>

        <section className="section" id="services">
          <div className="section-head">
            <div><p className="eyebrow">01 — SERVICES</p><h2>From idea to working system.</h2></div>
            <p className="section-note">Engineering-led digital products with a clean, modern interface and practical architecture.</p>
          </div>
          <div className="service-grid">
            {services.map(([title, desc], i) => (
              <article className="service" key={title}>
                <span>0{i + 1}</span><h3>{title}</h3><p>{desc}</p><b>↗</b>
              </article>
            ))}
          </div>
        </section>

        <section className="section section-3d" id="work">
          <div className="section-head">
            <div><p className="eyebrow">02 — 3D CAPABILITIES</p><h2>Technology you can see.</h2></div>
            <p className="section-note">Actual WebGL scenes, depth, lighting and perspective — not flat cards pretending to be 3D.</p>
          </div>
          <div className="cap-grid">
            <Capability type="AI" color="#b8a7ff" title="AI Systems" text="Automation, agents and intelligent product workflows." />
            <Capability type="WEB" color="#8fe8df" title="Web Engineering" text="High-performance interfaces and full-stack platforms." />
            <Capability type="GAME" color="#ffd2a8" title="Game Development" text="Interactive worlds, systems and polished gameplay." />
          </div>
        </section>

        <section className="section split" id="about">
          <div><p className="eyebrow">03 — ABOUT</p><h2>Small team mindset.<br/>Serious engineering.</h2></div>
          <div className="about-copy"><p>We combine product thinking, modern web engineering and emerging AI capabilities to turn ambitious concepts into useful software.</p><p>Every build is designed to be responsive, maintainable and ready to evolve.</p></div>
        </section>

        <section className="section process">
          <div className="section-head"><div><p className="eyebrow">04 — PROCESS</p><h2>Clear thinking. Clean execution.</h2></div></div>
          <div className="process-grid">
            {["Discover", "Architect", "Build", "Refine", "Launch"].map((x, i) => <div className="process-item" key={x}><span>0{i+1}</span><h3>{x}</h3><p>Focused decisions, rapid implementation and continuous refinement.</p></div>)}
          </div>
        </section>

        <section className="contact" id="contact">
          <p className="eyebrow">05 — CONTACT</p>
          <h2>Have a system in mind?</h2>
          <p>Tell us what you're building. We'll turn the rough idea into a practical next step.</p>
          <a href="mailto:hello@khiljisoftwares.com">hello@khiljisoftwares.com ↗</a>
        </section>
      </main>

      <footer><span>© {new Date().getFullYear()} KHILJI SOFTWARES</span><span>AI · WEB · SOFTWARE · GAMES</span></footer>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<App />);
