// home-extras.jsx — animated showcase sections that demonstrate agency craft

// ===== CapVisual: mini-animation per capability =====
// kind: brand | realestate | political | performance | automation | content

function useInView(threshold = 0) {
  const ref = React.useRef(null);
  const [seen, setSeen] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    // Fire as soon as any part of the element enters the viewport
    // (with a tiny negative margin so it triggers just before fully visible)
    const io = new IntersectionObserver((es) => {
      es.forEach(e => {
        if (e.isIntersecting) { setSeen(true); io.disconnect(); }
      });
    }, { threshold, rootMargin: '0px 0px -8% 0px' });
    io.observe(ref.current);
    // Safety net — if the element is already in view on mount (e.g. above the fold,
    // or a tall section the observer might not fire on), reveal after a short delay.
    const fallback = setTimeout(() => setSeen(true), 1200);
    return () => { io.disconnect(); clearTimeout(fallback); };
  }, [threshold]);
  return [ref, seen];
}

function BrandVisual() {
  const [ref, seen] = useInView();
  const palette = ['#D4A24C', '#F39137', '#E63E1F', '#0a0a0a', '#fafafa'];
  return (
    <div className="cap-visual" ref={ref}>
      <svg className="cv-wordmark" viewBox="0 0 240 60" aria-hidden="true">
        <text x="0" y="48" className={"cv-stroke" + (seen ? " in" : "")}>Harjog</text>
        <text x="0" y="48" className={"cv-fill" + (seen ? " in" : "")}>Harjog</text>
      </svg>
      <div className="cv-palette">
        {palette.map((c, i) => (
          <span key={c} className={"cv-swatch" + (seen ? " in" : "")}
                style={{ background: c, transitionDelay: `${600 + i * 80}ms` }} />
        ))}
      </div>
      <div className="cv-meta"><span>System v1.4</span><span>5 weights</span></div>
    </div>
  );
}

function RealEstateVisual() {
  const [ref, seen] = useInView();
  return (
    <div className="cap-visual" ref={ref}>
      <div className="cv-map">
        <div className="cv-map-grid" aria-hidden="true" />
        {[
          { x: 22, y: 30, d: 0   },
          { x: 65, y: 55, d: 600 },
          { x: 45, y: 72, d: 1100 },
          { x: 80, y: 22, d: 1500 },
        ].map((p, i) => (
          <span key={i} className={"cv-pin" + (seen ? " in" : "")}
                style={{ left: p.x + '%', top: p.y + '%', transitionDelay: p.d + 'ms', animationDelay: (p.d + 300) + 'ms' }}>
            <span className="cv-ripple" />
            <span className="cv-ripple two" />
          </span>
        ))}
      </div>
      <div className="cv-toast">
        <span className="cv-toast-dot" />
        <span>Site visit booked · Royal Greens</span>
      </div>
    </div>
  );
}

function PoliticalVisual() {
  const [ref, seen] = useInView();
  const cells = 12 * 6;
  return (
    <div className="cap-visual" ref={ref}>
      <div className="cv-dots">
        {Array.from({ length: cells }).map((_, i) => (
          <span key={i} className={"cv-dot" + (seen ? " in" : "")}
                style={{ transitionDelay: `${(i % 12) * 30 + Math.floor(i / 12) * 50}ms` }} />
        ))}
      </div>
      <div className="cv-meta"><span>Booth #42</span><span className="acc">4.2L touchpoints</span></div>
    </div>
  );
}

function PerformanceVisual() {
  const [ref, seen] = useInView();
  const bars = [40, 62, 35, 78, 55, 90, 70];
  const [cpl, setCpl] = React.useState(62);
  React.useEffect(() => {
    if (!seen) return;
    let v = 62;
    const id = setInterval(() => {
      v = Math.max(24, v - 1);
      setCpl(v);
      if (v <= 24) clearInterval(id);
    }, 70);
    return () => clearInterval(id);
  }, [seen]);
  return (
    <div className="cap-visual" ref={ref}>
      <div className="cv-bars">
        {bars.map((h, i) => (
          <span key={i} className={"cv-bar" + (seen ? " in" : "")}
                style={{ '--h': h + '%', transitionDelay: `${i * 90}ms` }} />
        ))}
      </div>
      <div className="cv-cpl">
        <span className="cv-cpl-label">Cost per lead</span>
        <span className="cv-cpl-value">₹<span className="cv-cpl-num">{cpl}</span><span className="cv-cpl-down">↓ 62%</span></span>
      </div>
    </div>
  );
}

function AutomationVisual() {
  const [ref, seen] = useInView();
  // Animated WhatsApp-style chat
  const msgs = [
    { side: 'in',  t: 'Interested in your 3BHK pricing for Royal Greens.' },
    { side: 'out', t: 'Hi Rajan — sharing the floor plan + price sheet now.' },
    { side: 'in',  t: 'Can I visit on Saturday?' },
    { side: 'out', t: '11:30 AM with our site team. Pin: maps.app/r-greens' },
  ];
  return (
    <div className="cap-visual" ref={ref}>
      <div className="cv-chat">
        <div className="cv-chat-head">
          <span className="cv-chat-dot" />
          <span>WhatsApp · Royal Greens bot</span>
          <span className="cv-chat-time">live</span>
        </div>
        {msgs.map((m, i) => (
          <div key={i} className={"cv-msg " + m.side + (seen ? " in" : "")}
               style={{ transitionDelay: `${300 + i * 500}ms` }}>
            {m.t}
          </div>
        ))}
        <div className={"cv-typing" + (seen ? " in" : "")}
             style={{ transitionDelay: '2300ms' }}>
          <span /><span /><span />
        </div>
      </div>
    </div>
  );
}

function ContentVisual() {
  const [ref, seen] = useInView();
  const [pct, setPct] = React.useState(0);
  React.useEffect(() => {
    if (!seen) return;
    let p = 0;
    const id = setInterval(() => {
      p = (p + 1) % 100;
      setPct(p);
    }, 80);
    return () => clearInterval(id);
  }, [seen]);
  return (
    <div className="cap-visual" ref={ref}>
      <div className="cv-reel">
        <div className="cv-reel-frame">
          <div className="cv-reel-grid" aria-hidden="true" />
          <span className="cv-reel-glyph">▶</span>
          <span className="cv-reel-tag">REEL · 12s</span>
          <span className="cv-reel-rec"><span /></span>
        </div>
        <div className="cv-reel-scrub">
          <span className="cv-reel-fill" style={{ width: pct + '%' }} />
          {[12, 25, 50, 75, 88].map(t => (
            <span key={t} className="cv-reel-tick" style={{ left: t + '%' }} />
          ))}
        </div>
        <div className="cv-meta"><span>00:{String(Math.floor(pct * 0.12)).padStart(2,'0')} / 00:12</span><span>1080×1920</span></div>
      </div>
    </div>
  );
}

const CAP_VISUALS = {
  brand: BrandVisual,
  realestate: RealEstateVisual,
  political: PoliticalVisual,
  performance: PerformanceVisual,
  automation: AutomationVisual,
  content: ContentVisual,
};

function AnimatedCapabilities({ setRoute }) {
  const caps = [
    { num: '01', title: 'Brand Identity',        slug: 'brand-identity' },
    { num: '02', title: 'Real Estate Marketing', slug: 'real-estate'    },
    { num: '03', title: 'Political Campaigns',   slug: 'political'      },
    { num: '04', title: 'Performance Marketing', slug: 'performance'    },
    { num: '05', title: 'Marketing Automation',  slug: 'automation'     },
    { num: '06', title: 'Content & Production',  slug: 'content-video'  },
  ];
  return (
    <section id="capabilities">
      <div className="wrap">
        <Reveal className="sec-head">
          <h2><TypeReveal>What we <span className="it">do</span><br />under one roof.</TypeReveal></h2>
        </Reveal>
        {caps.map((c, i) => (
          <Reveal key={c.num} className="svc-stack-item" delay={i * 50}
                  onClick={() => setRoute('service/' + c.slug)}>
            <h1 className="svc-stack-title">
              {c.title.split('').map((ch, j) => (
                <span key={j} className="svc-ch-wrap">
                  <span className="svc-ch" style={{ transitionDelay: `${j * 14}ms` }}>
                    {ch === ' ' ? ' ' : ch}
                  </span>
                  <span className="svc-ch clone" style={{ transitionDelay: `${j * 14}ms` }}>
                    {ch === ' ' ? ' ' : ch}
                  </span>
                </span>
              ))}
            </h1>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// ===== Animated metrics ticker =====
function MetricsTicker() {
  const [ref, seen] = useInView();
  const items = [
    { v: 10,  suffix: '+', k: 'Years in practice',        sub: 'Since 2014'         },
    { v: 140, suffix: '+', k: 'Projects delivered',        sub: 'Film · Social · Marketing' },
    { v: 4.2, suffix: 'L', k: 'Voter touchpoints',        sub: '2025 · verified', float: true },
    { v: 6,   suffix: '',  k: 'Countries — social clients', sub: 'UK · AU · CA · USA · UAE · TH' },
  ];
  return (
    <section className="metrics-ticker" ref={ref}>
      <div className="wrap">
        <div className="mt-grid">
          {items.map((it, i) => (
            <div key={it.k} className={"mt-cell" + (seen ? " in" : "")} style={{ transitionDelay: i * 100 + 'ms' }}>
              <div className="mt-v">
                <CountUp to={it.v}
                  duration={1600}
                  format={(n) => it.float ? n.toFixed(1) : Math.round(n)}
                  suffix={it.suffix} />
              </div>
              <div className="mt-k">{it.k}</div>
              <div className="mt-sub">{it.sub}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// Live activity feed — strip of "events" cycling through
function ActivityFeed() {
  const events = [
    { t: 'JUST NOW',  e: 'Reel published',     d: 'Royal Greens · 9:16 · 12s', kind: 'content' },
    { t: '2 MIN',     e: 'Lead routed',         d: 'Sona Foods · WhatsApp · 47s response', kind: 'auto' },
    { t: '14 MIN',    e: 'CPL crossed target',  d: 'Aman Buildwell · ₹38.4k', kind: 'perf' },
    { t: '38 MIN',    e: 'Hoarding installed',  d: 'GT Road · 40×20 · install verified', kind: 'print' },
    { t: '1 HR',      e: 'IVR broadcast sent',  d: 'MLA campaign · 84/84 booths · 412k calls', kind: 'pol' },
    { t: '2 HR',      e: 'Brand sprint v2',     d: 'Punjab Khadi · identity v2 shipped', kind: 'brand' },
    { t: '4 HR',      e: 'Drone reel cut',      d: 'Heritage Resorts · 90s master', kind: 'content' },
  ];
  const doubled = [...events, ...events];
  return (
    <div className="activity-feed" aria-hidden="true">
      <div className="af-track">
        {doubled.map((ev, i) => (
          <div key={i} className={"af-item af-" + ev.kind}>
            <span className="af-dot" />
            <span className="af-time">{ev.t}</span>
            <span className="af-event">{ev.e}</span>
            <span className="af-detail">{ev.d}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ===== Cursor spotlight on hero =====
function HeroSpotlight() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const hero = el.closest('.hero');
    if (!hero) return;
    const onMove = (e) => {
      const r = hero.getBoundingClientRect();
      const x = ((e.clientX - r.left) / r.width) * 100;
      const y = ((e.clientY - r.top) / r.height) * 100;
      el.style.setProperty('--mx', x + '%');
      el.style.setProperty('--my', y + '%');
      el.classList.add('on');
    };
    const onLeave = () => el.classList.remove('on');
    hero.addEventListener('mousemove', onMove);
    hero.addEventListener('mouseleave', onLeave);
    return () => {
      hero.removeEventListener('mousemove', onMove);
      hero.removeEventListener('mouseleave', onLeave);
    };
  }, []);
  return <div ref={ref} className="hero-spot" aria-hidden="true" />;
}

Object.assign(window, {
  AnimatedCapabilities, MetricsTicker, HeroSpotlight
});
