// TruVis Landing v2 — sections A: Nav, Hero, Quick access, Featured, Pillars
const { useState, useEffect, useRef } = React;

// ============== UTILITY BAR + NAV ==============
const TopBar = () => {
  const [navOpen, setNavOpen] = useState(false);
  useEffect(() => {
    const close = () => setNavOpen(false);
    window.addEventListener('hashchange', close);
    return () => window.removeEventListener('hashchange', close);
  }, []);
  useEffect(() => {
    if (typeof document === 'undefined') return;
    document.body.classList.toggle('nav-open', navOpen);
    return () => document.body.classList.remove('nav-open');
  }, [navOpen]);
  return (
  <>
    <div className="utility-bar">
      <div className="utility-inner">
        <div className="utility-left">
          <span><Icon name="pin" size={12} stroke={2} /> Etihad Towers, Abu Dhabi</span>
          <span><Icon name="phone" size={12} stroke={2} /> +971 2 409 3184</span>
          <span><Icon name="mail" size={12} stroke={2} /> Licensing@truvis.ae</span>
        </div>
        <div className="utility-right">
          <a href="#insights">Insights</a>
          <a href="#faq">FAQ</a>
          <a href="#contact">Contact</a>
        </div>
      </div>
    </div>
    <nav className={`nav ${navOpen ? 'nav-mobile-open' : ''}`}>
      <div className="nav-inner">
        <a href="#top" className="nav-logo" onClick={() => setNavOpen(false)}>
          <img src="assets/logo-cyan-shield.png" alt="TRUVIS" />
          <div>
            <div className="nav-logo-text">TRUVIS</div>
            <span className="nav-logo-tagline">Where Trust Creates True Vision</span>
          </div>
        </a>
        <div className="nav-links">
          <a href="#services" className="nav-link" onClick={() => setNavOpen(false)}>Services</a>
          <a href="#jurisdictions" className="nav-link" onClick={() => setNavOpen(false)}>Jurisdictions</a>
          <a href="#process" className="nav-link" onClick={() => setNavOpen(false)}>How we work</a>
          <a href="#insights" className="nav-link" onClick={() => setNavOpen(false)}>Insights</a>
          <a href="#faq" className="nav-link" onClick={() => setNavOpen(false)}>FAQ</a>
        </div>
        <a href="#contact" className="nav-cta" onClick={() => setNavOpen(false)}>Request consultation <Icon name="arrow-right" size={14} stroke={2.2} /></a>
        <button
          type="button"
          className="nav-burger"
          aria-label={navOpen ? 'Close menu' : 'Open menu'}
          aria-expanded={navOpen}
          onClick={() => setNavOpen((v) => !v)}>
          <span /><span /><span />
        </button>
      </div>
    </nav>
  </>
  );
};

// ============== HERO — EDITORIAL CAROUSEL ==============
const HERO_SLIDES = [
  {
    kind: 'monogram',
    eyebrow: 'UAE Financial Licensing · CBUAE · ADGM FSRA · DFSA',
    pretitle: 'For founders, fintechs and family offices',
    title: 'A licence the regulator wants to approve.',
    sub: 'Strategy-led corporate services across the three UAE financial regulators. From the first scoping conversation to a licence in good standing — built to clear authorisation, not to look the part.',
    primary: { label: 'Book a confidential consultation', href: '#contact' },
    secondary: { label: 'Compare jurisdictions', href: '#jurisdictions' },
    badge: 'TV',
    badgeHint: 'TRUVIS monogram',
    accent: 'cream'
  },
  {
    kind: 'chevron',
    eyebrow: 'Featured · CBUAE · Q1 2026 priority',
    pretitle: 'Federal Decree-Law No. 6 of 2025',
    title: 'Open Finance is now a Licensed Financial Activity.',
    sub: 'Effective 16 September 2025, with a one-year reconciliation deadline of 16 September 2026. Article 62 captures TPPs, Account Information Services and platforms enabling licensed activities — irrespective of medium or technology. The window to position is now.',
    primary: { label: 'Read the brief', href: 'https://truvi.ae/insights/cbuae-open-finance-decree-law-6-2025', external: true },
    secondary: { label: 'Discuss with our team', href: '#contact' },
    accent: 'petroleum'
  },
  {
    kind: 'editorial',
    eyebrow: 'Three regulators. One choice that shapes everything.',
    pretitle: 'The 2026 regulatory map',
    title: 'At the centre of the UAE’s financial future.',
    sub: 'CBUAE Open Finance, ADGM FSRA and DFSA — three frameworks, three legal systems. We identify the pathway that serves your commercial objectives, then execute the application with the precision the regulator expects.',
    primary: { label: 'Compare jurisdictions', href: '#jurisdictions' },
    secondary: { label: 'How we work', href: '#process' },
    accent: 'navy'
  }
];

const Hero = ({ ctaCopy }) => {
  const [idx, setIdx] = useState(0);
  const total = HERO_SLIDES.length;
  const slide = HERO_SLIDES[idx];
  const ctaOverride = {
    consultation: 'Request consultation',
    briefing: 'Schedule a briefing',
    engage: 'Begin your engagement'
  };

  // auto-advance
  useEffect(() => {
    const t = setInterval(() => setIdx(i => (i + 1) % total), 7500);
    return () => clearInterval(t);
  }, [total]);

  const primaryLabel = idx === 0 && ctaCopy && ctaOverride[ctaCopy] ? ctaOverride[ctaCopy] : slide.primary.label;

  return (
    <section className={`hero hero-${slide.accent}`} id="top" data-screen-label="Hero">
      <div className="hero-bg-image" />
      <div className="hero-bg-fade" />
      <div className="hero-bg-grid" />

      {/* Vertical slide indicators (left rail) */}
      <div className="hero-rail-left" aria-label="Hero slides">
        {HERO_SLIDES.map((_, i) => (
          <button
            key={i}
            type="button"
            className={`hero-rail-dot ${i === idx ? 'active' : ''}`}
            onClick={() => setIdx(i)}
            aria-label={`Slide ${i + 1}`}
          >
            <span className="rail-num">{String(i + 1).padStart(2, '0')}</span>
            <span className="rail-bar" />
          </button>
        ))}
      </div>

      {/* Vertical icon rail (right) */}
      <div className="hero-rail-right" aria-label="Quick links">
        <a href="https://www.linkedin.com" target="_blank" rel="noopener noreferrer" className="rail-icon" aria-label="LinkedIn">in</a>
        <a href="mailto:Licensing@truvis.ae" className="rail-icon" aria-label="Email"><Icon name="mail" size={14} stroke={2} /></a>
        <a href="tel:+97124093184" className="rail-icon" aria-label="Phone"><Icon name="phone" size={14} stroke={2} /></a>
        <a href="https://truvi.ae/insights" target="_blank" rel="noopener noreferrer" className="rail-icon" aria-label="Insights"><Icon name="document" size={14} stroke={2} /></a>
        <span className="rail-divider" />
        <span className="rail-vert-label">FOLLOW</span>
      </div>

      <div className="hero-content">
        <div className="container">
          <div className="hero-slide-grid">
            <div className="hero-slide-text">
              <span className="eyebrow hero-eyebrow">{slide.eyebrow}</span>
              <div className="hero-pretitle">{slide.pretitle}</div>
              <h1 className="hero-title hero-title-xl">
                {slide.title}
              </h1>
              <p className="hero-sub">{slide.sub}</p>
              <div className="hero-ctas">
                <a
                  href={slide.primary.href}
                  className="btn btn-primary"
                  target={slide.primary.external ? '_blank' : undefined}
                  rel={slide.primary.external ? 'noopener noreferrer' : undefined}
                >
                  {primaryLabel} <Icon name="arrow-right" size={14} stroke={2.2} />
                </a>
                <a href={slide.secondary.href} className="btn btn-ghost-light">
                  {slide.secondary.label}
                </a>
              </div>
              <div className="hero-trust-inline" aria-label="Credibility">
                <span className="hero-trust-pill"><span className="dot" /> Response within 1 business day</span>
                <span className="hero-trust-pill"><span className="dot" /> Confidential by default</span>
                <span className="hero-trust-pill"><span className="dot" /> No obligation scoping call</span>
              </div>
              <div className="hero-meta">
                <span><strong>{String(idx + 1).padStart(2, '0')}</strong> / {String(total).padStart(2, '0')}</span>
                <span className="hero-meta-sep" />
                <button className="hero-meta-btn" onClick={() => setIdx((idx - 1 + total) % total)} aria-label="Previous slide">&larr; Prev</button>
                <button className="hero-meta-btn" onClick={() => setIdx((idx + 1) % total)} aria-label="Next slide">Next &rarr;</button>
              </div>
            </div>

            <div className="hero-slide-visual">
              {slide.kind === 'monogram' && (
                <div className="hero-monogram">
                  <svg viewBox="0 0 400 400" className="hero-mono-svg" aria-hidden="true">
                    <defs>
                      <linearGradient id="monoG" x1="0" y1="0" x2="1" y2="1">
                        <stop offset="0%" stopColor="var(--tv-brand-cyan)" stopOpacity="0.95" />
                        <stop offset="100%" stopColor="var(--tv-deep-emerald)" stopOpacity="0.85" />
                      </linearGradient>
                    </defs>
                    {/* Concentric arcs */}
                    <circle cx="200" cy="200" r="180" fill="none" stroke="rgba(255,255,255,0.18)" strokeWidth="1" />
                    <circle cx="200" cy="200" r="150" fill="none" stroke="rgba(255,255,255,0.22)" strokeWidth="1" />
                    <circle cx="200" cy="200" r="120" fill="none" stroke="rgba(255,255,255,0.28)" strokeWidth="1.2" />
                    {/* Diagonal chevron pair */}
                    <path d="M 110 280 L 200 110 L 290 280" fill="none" stroke="url(#monoG)" strokeWidth="22" strokeLinecap="square" strokeLinejoin="miter" />
                    <path d="M 140 295 L 200 165 L 260 295" fill="none" stroke="rgba(255,255,255,0.85)" strokeWidth="6" strokeLinecap="square" strokeLinejoin="miter" />
                    {/* Outer ticks */}
                    {Array.from({ length: 12 }).map((_, i) => {
                      const a = (i * 30) * Math.PI / 180;
                      const x1 = 200 + Math.cos(a) * 188;
                      const y1 = 200 + Math.sin(a) * 188;
                      const x2 = 200 + Math.cos(a) * 198;
                      const y2 = 200 + Math.sin(a) * 198;
                      return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="rgba(255,255,255,0.4)" strokeWidth="1.5" />;
                    })}
                  </svg>
                  <div className="hero-mono-caption">
                    <span className="hero-mono-tag">{slide.badgeHint}</span>
                    <span className="hero-mono-year">EST. 2024</span>
                  </div>
                </div>
              )}

              {slide.kind === 'chevron' && (
                <div className="hero-chevron">
                  <svg viewBox="0 0 500 500" className="hero-chevron-svg" aria-hidden="true">
                    <defs>
                      <linearGradient id="chevG" x1="0" y1="0" x2="1" y2="1">
                        <stop offset="0%" stopColor="var(--tv-brand-cyan)" />
                        <stop offset="100%" stopColor="var(--tv-deep-emerald)" />
                      </linearGradient>
                    </defs>
                    <path d="M 80 460 L 280 60 L 320 60 L 120 460 Z" fill="url(#chevG)" />
                    <path d="M 200 460 L 400 60 L 440 60 L 240 460 Z" fill="rgba(255,255,255,0.18)" />
                    <path d="M 320 460 L 480 140 L 500 180 L 360 460 Z" fill="rgba(255,255,255,0.08)" />
                    {/* Skyline silhouette behind */}
                    <g opacity="0.32">
                      <rect x="40" y="320" width="20" height="140" fill="white" />
                      <rect x="65" y="280" width="14" height="180" fill="white" />
                      <rect x="84" y="250" width="22" height="210" fill="white" />
                      <rect x="110" y="310" width="16" height="150" fill="white" />
                      <polygon points="380,460 400,200 420,460" fill="white" />
                      <rect x="425" y="290" width="18" height="170" fill="white" />
                      <rect x="446" y="260" width="14" height="200" fill="white" />
                    </g>
                  </svg>
                  <span className="hero-chevron-tag">2026 — The Open Finance turning point</span>
                </div>
              )}

              {slide.kind === 'editorial' && (
                <div className="hero-editorial-card">
                  <span className="hero-ed-tag">Three frameworks. One choice.</span>
                  <div className="hero-ed-rows">
                    <div className="hero-ed-row">
                      <span className="hero-ed-num">01</span>
                      <div>
                        <div className="hero-ed-h">ADGM · FSRA</div>
                        <div className="hero-ed-p">UK Common Law · Fintech RegLab · Virtual Assets</div>
                      </div>
                    </div>
                    <div className="hero-ed-row">
                      <span className="hero-ed-num">02</span>
                      <div>
                        <div className="hero-ed-h">DIFC · DFSA</div>
                        <div className="hero-ed-p">English Common Law · Banking · Asset Mgmt</div>
                      </div>
                    </div>
                    <div className="hero-ed-row">
                      <span className="hero-ed-num">03</span>
                      <div>
                        <div className="hero-ed-h">CBUAE</div>
                        <div className="hero-ed-p">Federal · Open Finance · PSP · SVF</div>
                      </div>
                    </div>
                  </div>
                  <a href="#jurisdictions" className="hero-ed-link">Open jurisdiction comparator <Icon name="arrow-right" size={11} stroke={2.2} /></a>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ============== QUICK ACCESS STRIP ==============
const QUICK_ITEMS = [
  { num: '01', icon: 'compass', title: 'Choose your jurisdiction', desc: 'Five-question framework comparing ADGM, DIFC and CBUAE for your business.', href: '#jurisdictions' },
  { num: '02', icon: 'shield', title: 'Apply for a licence', desc: 'ADGM FSP, DFSA, banking, fund management, payments and Open Finance pathways.', href: '#services' },
  { num: '03', icon: 'sandbox', title: 'Sandbox or full route', desc: 'ADGM RegLab and DFSA Innovation Testing Licence pathway strategy.', href: '#services' },
  { num: '04', icon: 'building', title: 'Form a company', desc: 'Free zone, mainland, holding structures and 17+ international jurisdictions.', href: '#services' }
];

const QuickAccess = () => (
  <section className="quick-access" data-screen-label="Quick access">
    <div className="container">
      <div className="quick-grid">
        {QUICK_ITEMS.map((q, i) => (
          <a key={i} href={q.href} className="quick-item">
            <span className="quick-num">{q.num} &middot; QUICK ACCESS</span>
            <Icon name={q.icon} size={32} stroke={1.5} className="quick-icon" />
            <h3 className="quick-title">{q.title}</h3>
            <p className="quick-desc">{q.desc}</p>
            <span className="quick-arrow">Continue <Icon name="arrow-right" size={12} stroke={2.2} /></span>
          </a>
        ))}
      </div>
    </div>
  </section>
);

// ============== FEATURED STORY ==============
const Featured = () => (
  <section className="section section-cream" data-screen-label="Featured">
    <div className="container">
      <div className="section-head reveal">
        <span className="eyebrow">Where TRUVIS fits</span>
        <h2 className="section-title">Fintech specialists, not generalists.</h2>
        <p className="section-lede">
          We sit between strategic advisory and corporate operations &mdash; a fintech-focused team
          that translates regulatory ambition into a licensed, operating entity.
        </p>
      </div>
      <div className="featured reveal">
        <div className="featured-img">
          <span className="featured-img-tag">Headquarters</span>
        </div>
        <div className="featured-body">
          <span className="featured-eyebrow">Etihad Towers, Abu Dhabi</span>
          <h3 className="featured-h">In the room with the regulators that matter.</h3>
          <p className="featured-p">
            Headquartered at the heart of the UAE&rsquo;s sovereign and institutional financial ecosystem &mdash;
            with active engagement across DIFC, ADGM and CBUAE.
          </p>
          <ul className="featured-bullets">
            <li>Pre-application engagement with FSRA Authorisation Team and DFSA</li>
            <li>Regulatory business plans prepared to the standard the regulator expects</li>
            <li>Ongoing corporate maintenance &mdash; AML / UBO, renewals, amendments</li>
            <li>17+ international jurisdictions covered directly by our team</li>
          </ul>
          <a href="#contact" className="btn btn-primary">
            Begin your engagement <Icon name="arrow-right" size={16} stroke={2} />
          </a>
        </div>
      </div>
    </div>
  </section>
);

// ============== PILLARS / SERVICES ==============
const Services = () => (
  <section className="section" id="services" data-screen-label="Services">
    <div className="container">
      <div className="section-head reveal">
        <span className="eyebrow">Our services</span>
        <h2 className="section-title">Six disciplines, one engagement model.</h2>
        <p className="section-lede">
          Every engagement begins with the question that matters most: what is the optimal structure to
          serve your long-term objectives? Execution follows from that answer.
        </p>
      </div>
      <div className="pillars-grid">
        {window.TV_DATA.SERVICES.map((s, i) => (
          <div key={i} id={s.slug} className={`pillar reveal ${s.color}`}>
            <span className="pillar-num">0{i+1} &middot; {s.title.toUpperCase().split(' ')[0]}</span>
            <h3>{s.title}</h3>
            <p>{s.desc}</p>
            <a href="#contact" className="pillar-cta">{s.cta} <Icon name="arrow-right" size={12} stroke={2.2} /></a>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// ============== STATS BAND ==============
const useCounter = (target, duration = 1500, start) => {
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!start) return;
    let raf, t0;
    const step = (t) => {
      if (!t0) t0 = t;
      const p = Math.min((t - t0) / duration, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(Math.round(target * eased));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [start, target, duration]);
  return val;
};

const StatCell = ({ stat, start }) => {
  const numeric = parseFloat(stat.num.replace(/,/g, ''));
  const isNumeric = !isNaN(numeric);
  const v = useCounter(isNumeric ? numeric : 0, 1400, start && isNumeric);
  const display = isNumeric
    ? (numeric >= 1000 ? v.toLocaleString() : v)
    : stat.num;
  return (
    <div className="stat-cell">
      <div className="stat-num">{display}<span className="unit">{stat.unit}</span></div>
      <div className="stat-lbl">{stat.lbl}</div>
      <div className="stat-desc">{stat.desc}</div>
    </div>
  );
};

const StatsBand = () => {
  const [start, setStart] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setStart(true); obs.disconnect(); }
    }, { threshold: 0.3 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return (
    <section className="stats-band" ref={ref} data-screen-label="Stats">
      <div className="stats-band-img" />
      <div className="stats-band-overlay" />
      <div className="container">
        <div className="stats-grid">
          {window.TV_DATA.STATS.map((s, i) => (
            <StatCell key={i} stat={s} start={start} />
          ))}
        </div>
      </div>
    </section>
  );
};

window.TV_V2_A = { TopBar, Hero, QuickAccess, Featured, Services, StatsBand };
