const { useRef, useEffect, useState } = React;

// ── KINETIC INTRO ─────────────────────────────────────────────────────────────
const KineticIntro = () => {
  const ref = useRef(null);
  const linesRef = useRef([]);

  useEffect(() => {
    const observer = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        linesRef.current.forEach((el, i) => {
          if (el) setTimeout(() => el.classList.add('vis'), i * 200);
        });
      }
    }, { threshold: 0.25 });
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, []);

  const lines = [
    { text: "We're a digital agency", delay: 0 },
    { text: "born in the Pink City,", delay: 200 },
    { text: "building for businesses", delay: 400 },
    { text: ["that think ", <span key="g" className="grad">globally<span style={{ fontStyle: 'normal', fontSize: '0.5em', verticalAlign: 'middle', marginLeft: 8 }}>↗</span></span>], delay: 600 },
  ];

  return (
    <section ref={ref} id="intro" className="jaali-bg" style={{ minHeight: '100vh', background: '#F5F1EA', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '10vh 8vw', overflow: 'hidden' }}>
      <div style={{ maxWidth: 1100 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', color: 'rgba(10,10,10,0.4)', marginBottom: 56, textTransform: 'uppercase' }}>[ ABOUT US ]</div>
        <div>
          {lines.map((line, i) => (
            <div key={i} ref={el => linesRef.current[i] = el} className="fu"
              style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2rem, 5vw, 6.5rem)', lineHeight: 1.08, color: '#0A0A0A', letterSpacing: '-0.025em', marginBottom: 8, animationDelay: `${line.delay}ms` }}>
              {Array.isArray(line.text) ? line.text : line.text}
            </div>
          ))}
        </div>
        <div style={{ marginTop: 56, display: 'flex', gap: 48, flexWrap: 'wrap' }}>
          {[['Pink City pedigree', 'Jaipur-born, globally wired.'], ['Jugaad-free engineering', 'Built right the first time.'], ['Full-stack growth', 'Build · Grow · Automate.']].map(([title, sub]) => (
            <div key={title} style={{ flex: '1 1 220px' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: 'var(--terra)', marginBottom: 8, textTransform: 'uppercase' }}>{title}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'rgba(10,10,10,0.6)', lineHeight: 1.6 }}>{sub}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ── SERVICES ──────────────────────────────────────────────────────────────────
const ServicesSection = () => {
  const ref = useRef(null);
  const [vis, setVis] = useState(false);

  useEffect(() => {
    const observer = new IntersectionObserver(([e]) => { if (e.isIntersecting) setVis(true); }, { threshold: 0.1 });
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, []);

  const pillars = [
    {
      num: '01',
      title: 'Build',
      icon: (
        <svg width="48" height="48" viewBox="0 0 48 48" fill="none">
          <rect x="6" y="6" width="36" height="36" rx="2" stroke="var(--terra)" strokeWidth="1.5"/>
          <path d="M14 18h20M14 24h12M14 30h16" stroke="var(--cream)" strokeWidth="1.2" strokeLinecap="round"/>
          <circle cx="38" cy="10" r="5" fill="var(--terra)" opacity="0.3"/>
        </svg>
      ),
      items: ['Custom Software', 'Ecommerce Stores', 'Marketplace Setup', 'Export-Ready B2B Catalogs'],
    },
    {
      num: '02',
      title: 'Grow',
      icon: (
        <svg width="48" height="48" viewBox="0 0 48 48" fill="none">
          <path d="M8 36 L20 20 L28 28 L40 10" stroke="var(--terra)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          <circle cx="40" cy="10" r="3" fill="var(--saffron)"/>
          <path d="M8 42 h32" stroke="rgba(245,241,234,0.2)" strokeWidth="1"/>
        </svg>
      ),
      items: ['SEO + AEO/GEO', 'Performance Marketing', 'Social Media Management', 'Email & Newsletter Automation'],
    },
    {
      num: '03',
      title: 'Automate',
      icon: (
        <svg width="48" height="48" viewBox="0 0 48 48" fill="none">
          <circle cx="24" cy="24" r="16" stroke="var(--terra)" strokeWidth="1.5"/>
          <circle cx="24" cy="24" r="6" fill="var(--terra)" opacity="0.25"/>
          <path d="M24 8 v4M24 36 v4M8 24 h4M36 24 h4" stroke="var(--cream)" strokeWidth="1.2" strokeLinecap="round"/>
          <circle cx="24" cy="24" r="2.5" fill="var(--saffron)"/>
        </svg>
      ),
      items: ['AI Chatbots', 'WhatsApp Business API', 'Workflow Automation', 'CRM & Lead Funnels'],
    },
  ];

  const handleMouseMove = (e, card) => {
    const rect = card.getBoundingClientRect();
    const x = (e.clientX - rect.left) / rect.width - 0.5;
    const y = (e.clientY - rect.top) / rect.height - 0.5;
    card.style.transform = `translateY(-14px) rotateY(${x * 6}deg) rotateX(${-y * 6}deg)`;
  };
  const handleMouseLeave = (card) => { card.style.transform = ''; };

  return (
    <section id="services" ref={ref} style={{ background: '#0A0A0A', padding: '12vh 6vw', overflow: 'hidden' }}>
      {/* Header */}
      <div style={{ marginBottom: 72 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', color: 'var(--terra)', marginBottom: 20, textTransform: 'uppercase' }}>[ 01 ] — WHAT WE DO</div>
        <h2 className={`fu ${vis ? 'vis' : ''}`} style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2rem, 4vw, 5.5rem)', lineHeight: 1.08, color: 'var(--cream)', letterSpacing: '-0.02em', maxWidth: 700 }}>
          Three pillars.<br />One outcome: <span className="grad">growth.</span>
        </h2>
      </div>

      {/* Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 24, perspective: 1000 }}>
        {pillars.map((p, i) => (
          <div key={p.num} className="pillar-card tilt"
            style={{ padding: '44px 40px', borderRadius: 2, cursor: 'none', animationDelay: `${i * 0.1}s` }}
            onMouseMove={e => handleMouseMove(e, e.currentTarget)}
            onMouseLeave={e => handleMouseLeave(e.currentTarget)}
            data-cursor="true">
            {/* Icon */}
            <div style={{ marginBottom: 32 }}>{p.icon}</div>
            {/* Number */}
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em', color: 'var(--terra)', marginBottom: 16 }}>PILLAR {p.num}</div>
            {/* Title */}
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2rem, 3vw, 3.5rem)', color: 'var(--cream)', marginBottom: 28, letterSpacing: '-0.02em' }}>{p.title}</div>
            {/* Items */}
            <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
              {p.items.map(item => (
                <li key={item} style={{ display: 'flex', alignItems: 'center', gap: 10, fontFamily: 'var(--font-body)', fontSize: 14, color: 'rgba(245,241,234,0.6)', lineHeight: 1.5 }}>
                  <span style={{ color: 'var(--terra)', fontSize: 12 }}>—</span>{item}
                </li>
              ))}
            </ul>
            {/* Arrow */}
            <div style={{ marginTop: 36, color: 'var(--terra)', fontSize: 22, transition: 'transform 0.3s ease' }}
              onMouseOver={e => e.currentTarget.style.transform = 'translateX(6px)'}
              onMouseOut={e => e.currentTarget.style.transform = ''}>→</div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 48, textAlign: 'center' }}>
        <em style={{ fontFamily: 'var(--font-display)', fontSize: 16, color: 'rgba(245,241,234,0.4)', fontStyle: 'italic' }}>
          Pick one. Or let us orchestrate all three.
        </em>
      </div>
      <div className="gold-rule" style={{ marginTop: 80, opacity: 0.4 }} />
    </section>
  );
};

// ── INDUSTRIES ────────────────────────────────────────────────────────────────
const IndustriesSection = () => {
  const row1 = ['Jewelry & Handicraft Export', 'Healthcare', 'Real Estate', 'Hospitality', 'D2C Brands'];
  const row2 = ['Coaching & EdTech', 'Restaurants', 'Wedding Planners', 'Heritage Hotels', 'Tourism'];
  const doubled1 = [...row1, ...row1, ...row1, ...row1];
  const doubled2 = [...row2, ...row2, ...row2, ...row2];

  return (
    <section style={{ background: '#0d0d0d', padding: '12vh 0', overflow: 'hidden' }}>
      <div style={{ padding: '0 6vw', marginBottom: 56 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', color: 'var(--terra)', marginBottom: 16, textTransform: 'uppercase' }}>[ 01.5 ] — INDUSTRIES</div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(1.5rem, 2.5vw, 2.8rem)', color: 'rgba(245,241,234,0.35)', letterSpacing: '-0.01em' }}>
          We've built for them all.
        </div>
      </div>

      {[{ items: doubled1, cls: 'marquee-left' }, { items: doubled2, cls: 'marquee-right' }].map((row, ri) => (
        <div key={ri} style={{ overflow: 'hidden', marginBottom: ri === 0 ? 0 : 0, paddingBottom: ri === 0 ? 16 : 0 }}>
          <div className={row.cls}>
            {row.items.map((item, i) => (
              <span key={i} className="ind-item"
                style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2.5rem, 4.5vw, 5.5rem)', lineHeight: 1.2, letterSpacing: '-0.02em' }}>
                {item}
                <span style={{ color: 'rgba(212,175,55,0.4)', marginLeft: 12 }}>·</span>
              </span>
            ))}
          </div>
        </div>
      ))}
    </section>
  );
};

// ── WORK / CASE STUDIES ───────────────────────────────────────────────────────
const WorkSection = () => {
  const sectionRef = useRef(null);

  const cases = [
    { name: 'ShilpKraft Export', industry: 'Jewelry & Handicraft', metric: '+312% organic traffic in 6 months', services: ['SEO', 'AEO', 'Shopify'], bg: 'linear-gradient(145deg, #1f0900 0%, #3d1800 40%, #0A0A0A 100%)', num: '01' },
    { name: 'MehranMart', industry: 'D2C Ecommerce', metric: '₹2.4Cr GMV in first quarter', services: ['Shopify', 'Perf. Marketing', 'Email'], bg: 'linear-gradient(145deg, #00090f 0%, #001a2d 40%, #0A0A0A 100%)', num: '02' },
    { name: 'HealPath Clinics', industry: 'Healthcare', metric: '60% support tickets automated', services: ['AI Chatbot', 'WhatsApp API', 'CRM'], bg: 'linear-gradient(145deg, #001a08 0%, #002d12 40%, #0A0A0A 100%)', num: '03' },
    { name: 'Haveli Heritage', industry: 'Hospitality', metric: '4.2× booking conversion lift', services: ['Website', 'SEO', 'AEO'], bg: 'linear-gradient(145deg, #1a1600 0%, #2d2800 40%, #0A0A0A 100%)', num: '04' },
  ];

  useEffect(() => {
    const section = sectionRef.current;
    if (!section) return;
    const cards = section.querySelectorAll('.case-card');
    const handleScroll = () => {
      cards.forEach((card, i) => {
        const next = cards[i + 1];
        if (!next) return;
        const nextTop = next.getBoundingClientRect().top;
        const overlap = Math.max(0, Math.min(1, 1 - nextTop / (window.innerHeight * 0.85)));
        const scale = 1 - overlap * 0.04;
        card.style.transform = `scale(${scale})`;
        card.style.filter = `brightness(${1 - overlap * 0.3})`;
      });
    };
    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <section id="work" ref={sectionRef} style={{ background: '#0A0A0A', padding: '12vh 0 0' }}>
      <div style={{ padding: '0 6vw', marginBottom: 64 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', color: 'var(--terra)', marginBottom: 20, textTransform: 'uppercase' }}>[ 02 ] — SELECTED WORK</div>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2.2rem, 4vw, 5.5rem)', color: 'var(--cream)', letterSpacing: '-0.025em' }}>
          Receipts, not promises.
        </h2>
      </div>

      <div style={{ position: 'relative' }}>
        {cases.map((c, i) => (
          <div key={c.num} className="case-card"
            style={{ position: 'sticky', top: `${60 + i * 30}px`, zIndex: i + 1, transformOrigin: 'top center', transition: 'transform 0.3s ease, filter 0.3s ease' }}
            data-cursor-label="VIEW" data-cursor="true">
            <div style={{ margin: '0 6vw', marginBottom: 24, borderRadius: 4, overflow: 'hidden', background: c.bg, padding: '64px 56px', minHeight: '60vh', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', border: '1px solid rgba(255,255,255,0.05)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,241,234,0.3)' }}>
                  {c.num} / {cases.length}
                </div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.16em', color: 'var(--terra)', textTransform: 'uppercase' }}>{c.industry}</div>
              </div>
              <div>
                <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2.5rem, 5vw, 6rem)', color: 'var(--cream)', letterSpacing: '-0.025em', marginBottom: 20 }}>{c.name}</h3>
                <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 'clamp(1.2rem, 2.5vw, 2rem)', color: 'var(--saffron)', marginBottom: 32 }}>{c.metric}</div>
                <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
                  {c.services.map(s => (
                    <span key={s} style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.18em', color: 'rgba(245,241,234,0.45)', border: '1px solid rgba(245,241,234,0.15)', padding: '5px 14px', textTransform: 'uppercase' }}>{s}</span>
                  ))}
                  <a href="#" className="ul-link" style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.16em', color: 'var(--cream)', opacity: 0.7 }}>View case →</a>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
};

Object.assign(window, { KineticIntro, ServicesSection, IndustriesSection, WorkSection });
