const { useRef, useEffect, useState } = React;

// ── PROCESS ───────────────────────────────────────────────────────────────────
const ProcessSection = () => {
  const sectionRef = useRef(null);
  const [activeStep, setActiveStep] = useState(0);

  const steps = [
    { num: '01', title: 'Discover', body: 'Deep dive into your business, audience, and market. We listen before we speak.' },
    { num: '02', title: 'Strategize', body: 'A roadmap built around outcomes, not vanity metrics. Every move is deliberate.' },
    { num: '03', title: 'Build', body: 'Pixel-perfect design, production-grade code. No shortcuts, no excuses.' },
    { num: '04', title: 'Launch', body: 'Calm, controlled, zero-drama deployment. Done this a hundred times.' },
    { num: '05', title: 'Optimize', body: 'We measure, iterate, and grow with you. Ship and ghost is not our style.' },
  ];

  useEffect(() => {
    const section = sectionRef.current;
    if (!section) return;
    const handleScroll = () => {
      const rect = section.getBoundingClientRect();
      const totalH = section.offsetHeight - window.innerHeight;
      const progress = Math.max(0, Math.min(1, -rect.top / totalH));
      setActiveStep(Math.min(steps.length - 1, Math.floor(progress * steps.length)));
    };
    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <section id="process" ref={sectionRef} style={{ background: '#F5F1EA', position: 'relative' }}>
      {/* Scroll-height spacer */}
      <div style={{ height: `${steps.length * 100}vh` }}>
        <div style={{ position: 'sticky', top: 0, height: '100vh', display: 'flex', overflow: 'hidden' }}>
          {/* Left — giant number */}
          <div style={{ width: '42%', display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '0 4vw 0 6vw', borderRight: '1px solid rgba(10,10,10,0.08)' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', color: 'var(--terra)', marginBottom: 40, textTransform: 'uppercase' }}>[ 03 ] — HOW WE WORK</div>
            <div style={{ position: 'relative' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(6rem, 14vw, 18rem)', lineHeight: 0.9, color: '#0A0A0A', letterSpacing: '-0.04em', transition: 'all 0.5s cubic-bezier(0.16,1,0.3,1)', userSelect: 'none' }}>
                {steps[activeStep].num}
              </div>
              <div style={{ marginTop: 20, height: 2, background: 'rgba(10,10,10,0.1)', overflow: 'hidden' }}>
                <div style={{ height: '100%', background: 'var(--terra)', width: `${((activeStep + 1) / steps.length) * 100}%`, transition: 'width 0.6s cubic-bezier(0.16,1,0.3,1)' }} />
              </div>
              <div style={{ marginTop: 16, fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.2em', color: 'rgba(10,10,10,0.35)' }}>
                {activeStep + 1} of {steps.length}
              </div>
            </div>
          </div>

          {/* Right — step content */}
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '0 6vw 0 5vw' }}>
            <div style={{ position: 'relative', overflow: 'hidden' }}>
              {steps.map((step, i) => (
                <div key={step.num}
                  style={{ position: i === activeStep ? 'relative' : 'absolute', top: 0, left: 0, width: '100%', opacity: i === activeStep ? 1 : 0, transform: i === activeStep ? 'translateY(0)' : 'translateY(24px)', transition: 'opacity 0.6s ease, transform 0.6s cubic-bezier(0.16,1,0.3,1)', pointerEvents: i === activeStep ? 'auto' : 'none' }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2.5rem, 5vw, 6rem)', color: '#0A0A0A', letterSpacing: '-0.025em', marginBottom: 24, lineHeight: 1.05 }}>
                    {step.title}
                  </div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 18, lineHeight: 1.7, color: 'rgba(10,10,10,0.55)', maxWidth: 480, fontWeight: 300 }}>
                    {step.body}
                  </div>
                </div>
              ))}
            </div>

            {/* Step nav dots */}
            <div style={{ display: 'flex', gap: 12, marginTop: 64 }}>
              {steps.map((step, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'none', opacity: i === activeStep ? 1 : 0.35, transition: 'opacity 0.3s' }}>
                  <div style={{ width: i === activeStep ? 24 : 6, height: 1, background: i === activeStep ? 'var(--terra)' : '#0A0A0A', transition: 'width 0.4s ease' }} />
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.15em', color: '#0A0A0A' }}>{step.num}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ── TESTIMONIALS ──────────────────────────────────────────────────────────────
const TestimonialsSection = () => {
  const [active, setActive] = useState(0);
  const quotes = [
    { text: "They didn't just build us a website. They built us a growth engine.", author: "Director, Jewelry Export Co.", location: "Jaipur" },
    { text: "Our ChatGPT and Google rankings shot up simultaneously. I didn't think that was possible.", author: "Founder, D2C Wellness Brand", location: "Delhi" },
    { text: "Zero drama, maximum output. The rarest combination in the agency world.", author: "CEO, Heritage Hospitality Group", location: "Rajasthan" },
  ];

  useEffect(() => {
    const id = setInterval(() => setActive(a => (a + 1) % quotes.length), 5000);
    return () => clearInterval(id);
  }, []);

  return (
    <section style={{ background: '#0A0A0A', padding: '14vh 6vw', overflow: 'hidden' }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', color: 'var(--terra)', marginBottom: 60, textTransform: 'uppercase' }}>[ 04 ] — WHAT THEY SAY</div>
      <div style={{ position: 'relative', minHeight: 320 }}>
        {quotes.map((q, i) => (
          <div key={i}
            style={{ position: i === active ? 'relative' : 'absolute', top: 0, left: 0, width: '100%', opacity: i === active ? 1 : 0, transform: i === active ? 'translateX(0)' : 'translateX(40px)', transition: 'opacity 0.7s ease, transform 0.7s cubic-bezier(0.16,1,0.3,1)', pointerEvents: i === active ? 'auto' : 'none' }}>
            <div style={{ maxWidth: 1000 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontWeight: 700, fontSize: 'clamp(1.8rem, 3.5vw, 4.5rem)', color: 'var(--cream)', lineHeight: 1.2, letterSpacing: '-0.02em', marginBottom: 40, textWrap: 'pretty' }}>
                "{q.text}"
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                <div style={{ width: 32, height: 1, background: 'var(--gold)', opacity: 0.6 }} />
                <div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'rgba(245,241,234,0.7)', fontWeight: 500 }}>{q.author}</div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.18em', color: 'var(--terra)', marginTop: 4 }}>{q.location}</div>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Dots */}
      <div style={{ display: 'flex', gap: 10, marginTop: 48 }}>
        {quotes.map((_, i) => (
          <button key={i} onClick={() => setActive(i)} style={{ all: 'unset', cursor: 'none', width: i === active ? 32 : 8, height: 2, background: i === active ? 'var(--terra)' : 'rgba(245,241,234,0.2)', transition: 'width 0.4s ease, background 0.3s' }} />
        ))}
      </div>
    </section>
  );
};

// ── ABOUT ─────────────────────────────────────────────────────────────────────
const AboutSection = () => {
  const ref = useRef(null);
  const [counts, setCounts] = useState([0, 0, 0, 0]);
  const targets = [50, 8, 12, 100];
  const labels = ['Projects Shipped', 'Industries Served', 'Cr+ Revenue Generated', '% Jaipur-based'];
  const prefixes = ['', '', '₹', ''];
  const suffixes = ['+', '+', 'Cr+', '%'];

  useEffect(() => {
    const observer = new IntersectionObserver(([e]) => {
      if (!e.isIntersecting) return;
      targets.forEach((target, ti) => {
        const duration = 1800;
        const start = performance.now();
        const animate = (now) => {
          const progress = Math.min(1, (now - start) / duration);
          const ease = 1 - Math.pow(1 - progress, 3);
          setCounts(prev => { const n = [...prev]; n[ti] = Math.round(ease * target); return n; });
          if (progress < 1) requestAnimationFrame(animate);
        };
        setTimeout(() => requestAnimationFrame(animate), ti * 150);
      });
      observer.disconnect();
    }, { threshold: 0.3 });
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, []);

  return (
    <section id="about" ref={ref} style={{ background: '#F5F1EA', padding: '14vh 6vw' }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: '6vw', alignItems: 'start' }}>
        {/* Left */}
        <div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', color: 'var(--terra)', marginBottom: 32, textTransform: 'uppercase' }}>[ 05 ] — WHO WE ARE</div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2.2rem, 3.5vw, 4.5rem)', color: '#0A0A0A', lineHeight: 1.1, letterSpacing: '-0.02em', marginBottom: 32 }}>
            Built in<br /><span style={{ color: 'var(--terra)' }}>Jaipur.</span><br />Trusted globally.
          </h2>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 16, lineHeight: 1.8, color: 'rgba(10,10,10,0.6)', fontWeight: 300, maxWidth: 440, marginBottom: 24 }}>
            We're a boutique digital agency that grew up in the Pink City and grew into global markets. Our obsession is simple: help businesses build better, grow faster, and operate smarter.
          </p>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 16, lineHeight: 1.8, color: 'rgba(10,10,10,0.6)', fontWeight: 300, maxWidth: 440 }}>
            No offshore teams. No junior-handled accounts. Just a tight crew of designers, developers, and growth strategists who take your business personally.
          </p>
        </div>

        {/* Right — stats */}
        <div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2 }}>
            {targets.map((_, i) => (
              <div key={i} style={{ background: i % 2 === 0 ? '#0A0A0A' : 'rgba(10,10,10,0.06)', padding: '40px 36px' }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2.5rem, 4vw, 5rem)', color: i % 2 === 0 ? 'var(--cream)' : '#0A0A0A', lineHeight: 1, letterSpacing: '-0.03em', marginBottom: 12 }}>
                  {prefixes[i]}{counts[i]}{suffixes[i]}
                </div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.16em', color: i % 2 === 0 ? 'rgba(245,241,234,0.4)' : 'rgba(10,10,10,0.45)', textTransform: 'uppercase' }}>
                  {labels[i]}
                </div>
              </div>
            ))}
          </div>

          {/* Trusted by ticker */}
          <div style={{ marginTop: 40, overflow: 'hidden', borderTop: '1px solid rgba(10,10,10,0.1)', paddingTop: 24 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 8, letterSpacing: '0.2em', color: 'rgba(10,10,10,0.35)', marginBottom: 16, textTransform: 'uppercase' }}>Trusted by</div>
            <div className="marquee-slow">
              {Array(10).fill(null).map((_, i) => (
                <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 32, paddingRight: 48 }}>
                  {['Jewelry Co.', 'D2C Brand', 'Heritage Group', 'EdTech Co.', 'Clinic Chain'].map(n => (
                    <span key={n} style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'rgba(10,10,10,0.35)', fontWeight: 500, whiteSpace: 'nowrap', paddingRight: 40 }}>
                      {n}
                    </span>
                  ))}
                </span>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ── CONTACT ───────────────────────────────────────────────────────────────────
const ContactSection = () => {
  const [sent, setSent] = useState(false);
  const [name, setName] = useState('');
  const [company, setCompany] = useState('');
  const [service, setService] = useState('');
  const [budget, setBudget] = useState('');
  const [email, setEmail] = useState('');

  const handleSend = (e) => {
    e.preventDefault();
    setSent(true);
    setTimeout(() => setSent(false), 4000);
  };

  return (
    <section id="contact" style={{ background: '#0A0A0A', padding: '14vh 6vw', minHeight: '100vh', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', color: 'var(--terra)', marginBottom: 56, textTransform: 'uppercase' }}>[ 06 ] — START A PROJECT</div>

      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(2.5rem, 6vw, 8rem)', color: 'var(--cream)', letterSpacing: '-0.03em', lineHeight: 1.04, marginBottom: 72, maxWidth: 900 }}>
        Got a project?<br />Let's make it<br /><span className="grad">unforgettable.</span>
      </h2>

      {sent ? (
        <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 'clamp(1.5rem, 3vw, 3rem)', color: 'var(--saffron)', animation: 'fadeUp 0.6s ease forwards' }}>
          Got it. We'll be in touch. ✦
        </div>
      ) : (
        <form onSubmit={handleSend} style={{ maxWidth: 900 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 'clamp(1.2rem, 2.2vw, 2.2rem)', color: 'var(--cream)', lineHeight: 2.2, opacity: 0.9 }}>
            <span>I'm </span>
            <input className="inline-input" value={name} onChange={e => setName(e.target.value)} placeholder="your name" style={{ fontSize: 'inherit', fontFamily: 'var(--font-display)', fontStyle: 'italic' }} />
            <span> from </span>
            <input className="inline-input" value={company} onChange={e => setCompany(e.target.value)} placeholder="company" style={{ fontSize: 'inherit', fontFamily: 'var(--font-display)', fontStyle: 'italic' }} />
            <span>,<br />interested in </span>
            <select className="inline-select" value={service} onChange={e => setService(e.target.value)} style={{ fontSize: 'inherit' }}>
              <option value="">— service —</option>
              <option>Custom Software</option>
              <option>Ecommerce / Shopify</option>
              <option>SEO + AEO</option>
              <option>Performance Marketing</option>
              <option>AI Automation</option>
              <option>WhatsApp API</option>
              <option>Full Package (Build + Grow + Automate)</option>
            </select>
            <span>,<br />with a budget of </span>
            <select className="inline-select" value={budget} onChange={e => setBudget(e.target.value)} style={{ fontSize: 'inherit' }}>
              <option value="">— range —</option>
              <option>₹50K – ₹1L</option>
              <option>₹1L – ₹3L</option>
              <option>₹3L – ₹10L</option>
              <option>₹10L+</option>
            </select>
            <span>.<br />Reach me at </span>
            <input className="inline-input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="your@email.com" style={{ fontSize: 'inherit', fontFamily: 'var(--font-display)', fontStyle: 'italic', minWidth: 220 }} />
            <span>.</span>
          </div>
          <button type="submit" className="send-btn">
            <span>Send it</span>
            <span style={{ fontSize: 16 }}>→</span>
          </button>
        </form>
      )}

      {/* Sidebar contact info */}
      <div style={{ position: 'fixed', bottom: 48, right: 48, zIndex: 100, display: 'flex', flexDirection: 'column', gap: 14, alignItems: 'flex-end' }}>
        {[
          { label: 'WhatsApp', val: '+91 98765 43210', href: 'https://wa.me/919876543210' },
          { label: 'Email', val: 'hello@eriont.in', href: 'mailto:hello@eriont.in' },
        ].map(({ label, val, href }) => (
          <a key={label} href={href} className="ul-link" style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.16em', color: 'rgba(245,241,234,0.35)', textTransform: 'uppercase', textDecoration: 'none' }}>
            {label}
          </a>
        ))}
      </div>
    </section>
  );
};

// ── FOOTER ────────────────────────────────────────────────────────────────────
const FooterSection = () => {
  const nameRef = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && nameRef.current) nameRef.current.classList.add('filled');
    }, { threshold: 0.3 });
    if (nameRef.current) observer.observe(nameRef.current);
    return () => observer.disconnect();
  }, []);

  const cols = [
    { title: 'Services', links: ['Custom Software', 'Ecommerce', 'SEO + AEO', 'Performance Mktg', 'AI Automation'] },
    { title: 'Industries', links: ['Jewelry & Export', 'Healthcare', 'D2C Brands', 'Real Estate', 'Hospitality'] },
    { title: 'Company', links: ['About', 'Process', 'Work', 'Careers', 'Blog'] },
    { title: 'Connect', links: ['hello@eriont.in', '+91 98765 43210', 'Jaipur, Rajasthan 302001', 'LinkedIn', 'Instagram'] },
  ];

  return (
    <footer style={{ background: '#050505', padding: '10vh 6vw 6vh', borderTop: '1px solid rgba(245,241,234,0.06)' }}>
      {/* Massive name */}
      <div style={{ overflow: 'hidden', marginBottom: 80 }}>
        <div ref={nameRef} className="footer-name" style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(4rem, 17vw, 22rem)', lineHeight: 0.9, letterSpacing: '-0.04em', whiteSpace: 'nowrap', willChange: 'color' }}>
          ERIONT
        </div>
      </div>

      <div className="gold-rule" style={{ marginBottom: 56, opacity: 0.3 }} />

      {/* Link grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 48, marginBottom: 72 }}>
        {cols.map(col => (
          <div key={col.title}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.22em', color: 'var(--terra)', marginBottom: 20, textTransform: 'uppercase' }}>{col.title}</div>
            <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 12 }}>
              {col.links.map(link => (
                <li key={link}>
                  <a href="#" className="ul-link" style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'rgba(245,241,234,0.45)', textDecoration: 'none', fontWeight: 300 }}>{link}</a>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>

      {/* Bottom bar */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16, paddingTop: 28, borderTop: '1px solid rgba(245,241,234,0.06)' }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.16em', color: 'rgba(245,241,234,0.25)' }}>
          © 2026 ERIONT DIGITAL · ALL RIGHTS RESERVED
        </div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'rgba(245,241,234,0.3)', fontWeight: 300 }}>
          Made with care in Jaipur 🇮🇳
        </div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.12em', color: 'rgba(245,241,234,0.2)' }}>
          {new Date().toISOString().slice(0, 10)}
        </div>
      </div>
    </footer>
  );
};

Object.assign(window, { ProcessSection, TestimonialsSection, AboutSection, ContactSection, FooterSection });
