const { useState, useEffect, useRef } = React;

function Reveal({ children, as = 'div', delay = 0, className = '', ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // If the element is already in view at mount (hero, above-the-fold), reveal immediately.
    const rect = el.getBoundingClientRect();
    const vh = window.innerHeight || document.documentElement.clientHeight;
    if (rect.top < vh && rect.bottom > 0) {
      setSeen(true);
      return;
    }
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setSeen(true); io.disconnect(); }
    }, { threshold: 0.08 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const cls = `reveal ${seen ? 'in' : ''} ${className}`.trim();
  const style = { ...(rest.style || {}), transitionDelay: delay ? `${delay}ms` : undefined };
  return React.createElement(as, { ...rest, ref, className: cls, style }, children);
}

function TopBar() {
  return (
    <div className="topbar">
      <div className="inner">
        <div className="pills">
          <span className="pill"><Icon name="phone" width={12} height={12} /> 990 990 4067</span>
          <span className="pill"><Icon name="pin" width={12} height={12} /> Perumbakkam, Chennai</span>
        </div>
        <div className="scroller">— Elevate Your Glow · Mon–Sat · 10 AM – 8 PM —</div>
      </div>
    </div>
  );
}

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const links = [
    ['Home', '#home'],
    ['About', '#about'],
    ['Services', '#services'],
    ['Transformations', '#transformations'],
    ['FAQs', '#faqs'],
    ['Contact', '#contact'],
  ];
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="inner">
        <a href="#home" className="brand">
          <img src="assets/logo.jpg" alt="Ari Aesthetics" />
          <div className="wordmark">
            <span className="wm-main">Ari</span>
            <span className="wm-sub">Aesthetics</span>
          </div>
        </a>
        <div className="nav-links">
          {links.map(([t, href]) => <a key={t} href={href}>{t}</a>)}
        </div>
        <div className="nav-cta">
          <a href="#contact" className="btn btn-primary">Book Consultation <span className="arrow">→</span></a>
          <button className="burger" aria-label="Menu"><span></span></button>
        </div>
      </div>
    </nav>
  );
}

function Hero() {
  const d = window.ARI.hero;
  const videoRef = React.useRef(null);
  const fadeRef = React.useRef(null);
  React.useEffect(() => {
    const v = videoRef.current;
    const f = fadeRef.current;
    if (!v) return;
    v.muted = true;
    v.playsInline = true;
    const tryPlay = () => { v.play().catch(() => {}); };
    tryPlay();
    const FADE = 1.2; // seconds to fade at end
    const onTime = () => {
      if (!v.duration) return;
      const left = v.duration - v.currentTime;
      if (left <= FADE) {
        const opacity = left / FADE;
        if (f) f.style.opacity = 1 - opacity;
      } else {
        if (f) f.style.opacity = 0;
      }
    };
    const onEnded = () => {
      v.currentTime = 0;
      if (f) f.style.opacity = 0;
      tryPlay();
    };
    const onStalled = () => tryPlay();
    const onPause = () => { if (!document.hidden) tryPlay(); };
    const onVis = () => { if (!document.hidden) tryPlay(); };
    v.addEventListener('timeupdate', onTime);
    v.addEventListener('ended', onEnded);
    v.addEventListener('stalled', onStalled);
    v.addEventListener('pause', onPause);
    v.addEventListener('canplay', tryPlay);
    document.addEventListener('visibilitychange', onVis);
    return () => {
      v.removeEventListener('timeupdate', onTime);
      v.removeEventListener('ended', onEnded);
      v.removeEventListener('stalled', onStalled);
      v.removeEventListener('pause', onPause);
      v.removeEventListener('canplay', tryPlay);
      document.removeEventListener('visibilitychange', onVis);
    };
  }, []);
  return (
    <section className="hero" id="home">
      <video ref={videoRef} autoPlay muted playsInline preload="auto"
        disablePictureInPicture disableRemotePlayback>
        <source src="assets/hero.mp4" type="video/mp4" />
      </video>
      <div ref={fadeRef} className="hero-fade" aria-hidden="true"></div>
      <div className="hero-fallback" aria-hidden="true"></div>
      <div className="hero-inner">
        <Reveal className="pre"><span className="dot"></span>{d.pre}</Reveal>

        <Reveal as="h1" delay={100}>
          {d.h1a}<br />
          {d.h1b} <span className="it">{d.h1c}</span>
        </Reveal>

        <div className="hero-bottom">
          <Reveal className="sub" delay={200}>{d.sub}</Reveal>
          <Reveal className="ctas" delay={300}>
            <a href="#contact" className="btn btn-primary">Book Consultation <span className="arrow">→</span></a>
            <a href="#services" className="btn btn-outline-light">Explore Services</a>
          </Reveal>
        </div>

        <Reveal className="hero-trust" delay={400}>
          <span><Icon name="star" width={14} height={14} /> 5-Star Rated Clinic</span>
          <span><Icon name="check" width={14} height={14} /> Certified Professionals</span>
          <span><Icon name="cpu" width={14} height={14} /> Advanced Technology</span>
          <span><Icon name="heart" width={14} height={14} /> Personalised Plans</span>
        </Reveal>
      </div>
    </section>
  );
}

function Stats() {
  return (
    <section className="stats">
      <div className="grid">
        {window.ARI.stats.map((s, i) => (
          <Reveal key={i} className="cell" delay={i * 80}>
            <div className="num">{s.num}<span className="it">{s.suffix}</span></div>
            <div className="lbl">{s.label}</div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

function About() {
  return (
    <section className="section about" id="about">
      <div className="wrap">
        <div className="section-head">
          <div>
            <div className="label">Our Story</div>
          </div>
          <div className="head-right">
            <Reveal as="h2">Where beauty meets <span className="serif-i">expert care.</span></Reveal>
          </div>
        </div>

        <div className="about-grid">
          <Reveal className="about-img">
            <img src="https://images.unsplash.com/photo-1610289982320-3891f7c9fd6d?w=800&q=80" alt="Ari Aesthetics clinic interior" />
            <div className="float-card">
              <div className="fc-num">8+ <span style={{fontSize:16, fontStyle:'italic', color:'var(--gold)'}}>yrs</span></div>
              <div className="fc-text">of combined aesthetic expertise in Chennai</div>
            </div>
          </Reveal>

          <Reveal className="about-copy" delay={120}>
            <p>At Ari Aesthetics, we believe that your skin's best version is already within you — it just needs the right care to shine. Nestled in the heart of Perumbakkam, Chennai, we are a premium aesthetic clinic dedicated to non-invasive treatments that deliver real, lasting results.</p>
            <p>Our team of certified professionals combines advanced clinical science with a deep understanding of Indian skin — creating treatments that are effective, personalised, and entirely tailored to you. From your first consultation to your final session, we ensure every visit feels like a step toward the most confident version of yourself.</p>
            <p>We don't believe in one-size-fits-all solutions. We believe in <em>you</em>.</p>
          </Reveal>
        </div>

        <div className="pillars">
          {window.ARI.pillars.map((p, i) => (
            <Reveal key={p.title} className="pillar" delay={i * 120}>
              <div className="sym">◆</div>
              <h4>{p.title}</h4>
              <p>{p.body}</p>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function Why() {
  const icons = ['shield', 'cpu', 'face', 'clock', 'chat', 'sparkle'];
  return (
    <section className="section why">
      <div className="wrap">
        <div className="section-head">
          <div><div className="label">The Ari Difference</div></div>
          <div className="head-right">
            <Reveal as="h2">Premium aesthetics, <span className="serif-i">personalised</span> for you.</Reveal>
          </div>
        </div>
        <Reveal className="why-grid">
          {window.ARI.why.map((w, i) => (
            <div key={w.n} className="why-card">
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                <div className="num">— {w.n}</div>
                <div className="icon"><Icon name={icons[i]} /></div>
              </div>
              <h4>{w.title}</h4>
              <p>{w.body}</p>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { Reveal, TopBar, Nav, Hero, Stats, About, Why });
