/* CITTA BUILDERS — shared React components used across all five pages.
   Loaded after the Cohere DS bundle; exports onto window.Site so each page's
   own babel script (separate scope) can use them. */

/* Single source of truth for footer social links — update these three URLs to go live. */
const SOCIAL_LINKS = {
  linkedin: 'https://www.linkedin.com/in/citta-builders-365b54424',
  instagram: 'https://www.instagram.com/cittabuilders/',
  facebook: 'https://www.facebook.com/cittabuilders360',
};

const NAV_LINKS = [
  { href: 'index.html', label: 'Home', i18n: 'nav.home' },
  { href: 'about.html', label: 'About', i18n: 'nav.about' },
  { href: 'services.html', label: 'Services', i18n: 'nav.services' },
  { href: 'portfolio.html', label: 'Portfolio', i18n: 'nav.portfolio' },
  { href: 'contact.html', label: 'Contact', i18n: 'nav.contact' },
];

/* ============ Language switcher — instant, local, dictionary-based (shared/i18n.js). No network
   call, no external widget, no polling: choosing a language is a synchronous DOM text swap via
   CITTA_I18N, so there is no delay and nothing to get "stuck". Persisted in localStorage so the
   choice survives page navigation across the whole site. ============ */
const LANGUAGES = [
  { code: 'en', label: 'English' },
  { code: 'sw', label: 'Kiswahili' },
  { code: 'fr', label: 'Français' },
  { code: 'ar', label: 'العربية' },
  { code: 'zh-CN', label: '中文' },
  { code: 'pt', label: 'Português' },
];

function getCurrentLang() {
  return (window.CITTA_I18N && window.CITTA_I18N.getLang()) || 'en';
}

function LanguageSwitcher({ variant, onLight }) {
  const [open, setOpen] = React.useState(false);
  const [current, setCurrent] = React.useState('en');

  React.useEffect(() => {
    setCurrent(getCurrentLang());
    const onChange = (e) => setCurrent(e.detail.lang);
    document.addEventListener('citta-lang-changed', onChange);
    return () => document.removeEventListener('citta-lang-changed', onChange);
  }, []);

  const choose = (code) => {
    setOpen(false);
    if (window.CITTA_I18N) window.CITTA_I18N.setLang(code);
    setCurrent(code);
  };

  return (
    <div className={'lang-switcher notranslate lang-switcher--' + variant + (onLight ? ' on-light' : '')} translate="no">
      <button className="lang-switcher-btn" onClick={() => setOpen((v) => !v)} aria-label="Change language" aria-expanded={open}>
        <i data-lucide="globe" width="15" height="15"></i>
        <span className="lang-switcher-btn-code">{current.split('-')[0].toUpperCase()}</span>
        <span className="lang-switcher-btn-full">{(LANGUAGES.find((l) => l.code === current) || {}).label || current}</span>
      </button>
      {open && (
        <div className="lang-switcher-menu" onMouseLeave={() => setOpen(false)}>
          {LANGUAGES.map((l) => (
            <button key={l.code} className={'lang-switcher-option' + (l.code === current ? ' active' : '')} onClick={() => choose(l.code)}>{l.label}</button>
          ))}
        </div>
      )}
    </div>
  );
}
/* ============ Device-mode switch — removed: real responsive breakpoints (mobile/desktop) now
   handle this automatically, so the manual Desktop/Mobile toggle is no longer needed. ============ */

function Nav({ active, alwaysLight = false }) {
  const [scrolled, setScrolled] = React.useState(alwaysLight);
  const [ready, setReady] = React.useState(false);
  const [hovered, setHovered] = React.useState(null);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [indicator, setIndicator] = React.useState({ left: 0, width: 0, ready: false });
  const linksRef = React.useRef(null);
  const linkRefs = React.useRef({});

  React.useEffect(() => {
    if (alwaysLight) return;
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [alwaysLight]);

  React.useEffect(() => {
    const t = setTimeout(() => setReady(true), 50);
    return () => clearTimeout(t);
  }, []);

  const measure = React.useCallback((label) => {
    const el = linkRefs.current[label];
    const wrap = linksRef.current;
    if (!el || !wrap) return;
    const elRect = el.getBoundingClientRect();
    const wrapRect = wrap.getBoundingClientRect();
    setIndicator({ left: elRect.left - wrapRect.left, width: elRect.width, ready: true });
  }, []);

  React.useEffect(() => {
    measure(hovered || active);
    const onResize = () => measure(hovered || active);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [hovered, active, measure, scrolled]);

  const { Button } = window.CohereDesignSystem_4a3e6b;
  const onLight = scrolled || alwaysLight;
  const logoSrc = onLight ? 'images/logo-black.png' : 'images/logo-white.png';
  return (
    <React.Fragment>
    <header className={'site-nav' + (scrolled ? ' scrolled' : '') + (alwaysLight ? ' on-light' : '')}>
      <div className="container nav-outer">
        <div className={'nav-capsule' + (ready ? ' nav-capsule--ready' : '')}>
          <a className="nav-logo-link" href="index.html">
            <img src={logoSrc} alt="CITTA BUILDERS" className="nav-logo-img" />
          </a>
          <nav className="nav-links notranslate" translate="no" ref={linksRef} onMouseLeave={() => setHovered(null)}>
            <span
              className={'nav-indicator' + (indicator.ready ? ' nav-indicator--ready' : '')}
              style={{ transform: `translateX(${indicator.left}px)`, width: indicator.width }}
            ></span>
            {NAV_LINKS.map((l, i) => (
              <a
                key={l.href}
                href={l.href}
                ref={(el) => { linkRefs.current[l.label] = el; }}
                className={active === l.label ? 'active' : ''}
                style={{ transitionDelay: ready ? '0ms' : (0.1 + i * 0.06) + 's' }}
                onMouseEnter={() => setHovered(l.label)}
                data-i18n={l.i18n}
              >{l.label}</a>
            ))}
          </nav>
          <div className="nav-cta notranslate" translate="no">
            <LanguageSwitcher variant="desktop" onLight={onLight} />
            <a href="contact.html" style={{ textDecoration: 'none' }}>
              <span className="nav-cta-glow">
                <Button variant="primary" onDark={!scrolled && !alwaysLight}><span data-i18n="nav.cta">Schedule a Consultation</span></Button>
              </span>
            </a>
          </div>
          <button
            className={'nav-menu-btn' + (menuOpen ? ' is-open' : '')}
            onClick={() => setMenuOpen((v) => !v)}
            aria-label={menuOpen ? 'Close menu' : 'Open menu'}
            aria-expanded={menuOpen}
          >
            <span></span><span></span><span></span>
          </button>
        </div>
        <div className={'nav-mobile-menu-wrap' + (menuOpen ? ' nav-mobile-menu-wrap--open' : '')}>
        <div className={'nav-mobile-menu notranslate' + (menuOpen ? ' nav-mobile-menu--open' : '')} translate="no">
          {NAV_LINKS.map((l) => (
            <a key={l.href} href={l.href} className={active === l.label ? 'active' : ''} onClick={() => setMenuOpen(false)} data-i18n={l.i18n}>{l.label}</a>
          ))}
          <div className="nav-mobile-lang"><LanguageSwitcher variant="mobile" /></div>
          <a href="contact.html" className="nav-mobile-cta" onClick={() => setMenuOpen(false)} data-i18n="nav.cta">Schedule a Consultation</a>
        </div>
        <div className="nav-mobile-scroll-hint" aria-hidden="true"><i data-lucide="chevron-down" width="16" height="16"></i></div>
        </div>
      </div>
    </header>
    </React.Fragment>
  );
}

function Footer() {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  const [subscribed, setSubscribed] = React.useState(false);
  const [subError, setSubError] = React.useState(null);
  const [subSending, setSubSending] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => { entries.forEach((e) => { if (e.isIntersecting) { setShown(true); io.unobserve(el); } }); },
      { threshold: 0.1 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <footer className={'site-footer' + (shown ? ' site-footer--in' : '')} ref={ref}>
      <div className="footer-grain"></div>
      <div className="footer-glow"></div>
      <div className="container footer-inner">
        <div className="footer-top">
          <div className="footer-brand">
            <a href="index.html" className="footer-logo-link"><img src="images/logo-white.png" alt="CITTA BUILDERS" className="footer-logo-img" /></a>
            <p data-i18n="footer.tagline">Tanzanian civil engineering and construction company delivering durable, high-quality infrastructure since 2005 — from concept to completion.</p>
            <div className="footer-social">
              <a href={SOCIAL_LINKS.linkedin} target="_blank" rel="noopener noreferrer" aria-label="Visit our LinkedIn page"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.86 0-2.14 1.45-2.14 2.94v5.67H9.34V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.38-1.85 3.6 0 4.27 2.37 4.27 5.46zM5.34 7.43a2.06 2.06 0 1 1 0-4.12 2.06 2.06 0 0 1 0 4.12zM7.12 20.45H3.56V9h3.56z"/></svg></a>
              <a href={SOCIAL_LINKS.instagram} target="_blank" rel="noopener noreferrer" aria-label="Visit our Instagram page"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="0.8" fill="currentColor" stroke="none"/></svg></a>
              <a href={SOCIAL_LINKS.facebook} target="_blank" rel="noopener noreferrer" aria-label="Visit our Facebook page"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 21v-7.6h2.6l.4-3H13.5V8.4c0-.87.25-1.46 1.5-1.46h1.6V4.27C16.3 4.19 15.3 4.1 14.16 4.1c-2.4 0-4.05 1.46-4.05 4.15v2.15H7.5v3h2.6V21z"/></svg></a>
            </div>
          </div>
          <div className="footer-links-grid">
            <div className="footer-col">
              <h5 data-i18n="footer.quickLinks">Quick Links</h5>
              <a href="about.html" data-i18n="footer.aboutUs">About Us</a>
              <a href="services.html" data-i18n="footer.services">Services</a>
              <a href="portfolio.html" data-i18n="footer.portfolio">Portfolio</a>
              <a href="contact.html" data-i18n="footer.contact">Contact</a>
            </div>
            <div className="footer-col">
              <h5 data-i18n="footer.servicesHeading">Services</h5>
              <a href="services.html#architectural-design" data-i18n="footer.svcArch">Architectural Design</a>
              <a href="services.html#structural-design" data-i18n="footer.svcStructural">Structural Design</a>
              <a href="services.html#building-construction" data-i18n="footer.svcBuilding">Building Construction</a>
              <a href="services.html#road-construction" data-i18n="footer.svcRoad">Road Construction</a>
              <a href="services.html#project-management" data-i18n="footer.svcPM">Project Management</a>
            </div>
            <div className="footer-col">
              <h5 data-i18n="footer.officeHeading">Office</h5>
              <div data-i18n="footer.officeLine1">Mikocheni Light Industrial Area</div>
              <div data-i18n="footer.officeLine2">Dar es Salaam, Tanzania</div>
              <div>+255 747 461 144<br/>+255 689 641 804<br/>+255 626 841 508</div>
              <div>info@cittabuilders.com</div>
            </div>
            <div className="footer-newsletter">
              <span className="footer-newsletter-eyebrow" data-i18n="footer.newsletterEyebrow">Project Updates</span>
              <h3 className="footer-newsletter-title" data-i18n="footer.newsletterTitle">Stay informed</h3>
              {subscribed ? (
                <div className="footer-newsletter-success"><i data-lucide="check-circle" width="16" height="16"></i> <span data-i18n="footer.newsletterSubmitted">You're subscribed.</span></div>
              ) : (
                <form className="footer-newsletter-form" onSubmit={(e) => {
                  e.preventDefault();
                  const email = e.currentTarget.querySelector('input').value;
                  setSubError(null);
                  setSubSending(true);
                  const fd = new FormData();
                  fd.set('formType', 'newsletter');
                  fd.set('email', email);
                  fetch('send-mail.php', { method: 'POST', body: fd })
                    .then((res) => res.json().catch(() => ({ success: false })))
                    .then((data) => {
                      setSubSending(false);
                      if (data.success) setSubscribed(true);
                      else setSubError('Could not subscribe right now — please try again later.');
                    })
                    .catch(() => { setSubSending(false); setSubError('Could not reach the server. Please try again.'); });
                }}>
                  <input type="email" required placeholder="you@company.com" aria-label="Email address" data-i18n-placeholder="footer.newsletterPlaceholder" />
                  <button type="submit" aria-label="Subscribe" disabled={subSending}><i data-lucide="arrow-right" width="16" height="16"></i></button>
                </form>
              )}
              {subError && <p className="footer-newsletter-legal" style={{ color: 'var(--text-error)' }}>{subError}</p>}
              <p className="footer-newsletter-legal" data-i18n="footer.newsletterLegal">By subscribing, you agree to receive project and company updates from CITTA BUILDERS.</p>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} <span data-i18n="footer.rights">CITTA BUILDERS Ltd. All rights reserved.</span></span>
          <a className="back-to-top" href="#top"><span data-i18n="footer.backToTop">Back to top</span> <i data-lucide="arrow-up" width="14" height="14"></i></a>
        </div>
      </div>
    </footer>
  );
}

/* Runs lucide.createIcons after mount — call once per page from the root component. */
function useLucide(deps = []) {
  React.useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  }, deps);
}

function PageHero({ eyebrow, title, sub, surface = 'primary', children, tall = false, bgImage, i18nEyebrow, i18nTitle, i18nSub }) {
  return (
    <section className={`page-hero surface-${surface}${tall ? ' hero-tall' : ''}`}>
      {bgImage ? (
        <React.Fragment>
          <img src={bgImage} alt="" className="hero-bg-photo" />
          <div className="hero-bg-scrim" />
        </React.Fragment>
      ) : (
        <div className="hero-bg-texture" />
      )}
      <div className="container">
        {eyebrow && <span className="hero-eyebrow" data-i18n={i18nEyebrow}>{eyebrow}</span>}
        <h1 className="hero-headline" data-i18n={i18nTitle}>{title}</h1>
        {sub && <p className="hero-sub" data-i18n={i18nSub}>{sub}</p>}
        {children}
      </div>
    </section>
  );
}

function SectionHead({ eyebrow, title, body, action, i18nEyebrow, i18nTitle, i18nBody }) {
  return (
    <div className="section-head-row">
      <div>
        {eyebrow && <span className="section-eyebrow" data-i18n={i18nEyebrow}>{eyebrow}</span>}
        <h2 className="section-heading" data-i18n={i18nTitle}>{title}</h2>
        {body && <p className="section-body" data-i18n={i18nBody}>{body}</p>}
      </div>
      {action}
    </div>
  );
}

function ImgSlot({ ratio = '4-3', label = 'Image placeholder', src, alt, fit }) {
  if (src) {
    return (
      <div className={`img-slot ratio-${ratio} has-photo` + (fit === 'contain' ? ' fit-contain' : '')}>
        <img src={src} alt={alt || label} loading="lazy" decoding="async" />
      </div>
    );
  }
  return (
    <div className={`img-slot ratio-${ratio}`}>
      <span className="img-slot-label">{label}</span>
    </div>
  );
}

function StatGrid({ stats, onDark = false }) {
  return (
    <div className="stat-grid">
      {stats.map((s) => (
        <div key={s.label} className={'stat-item' + (onDark ? ' on-dark' : '')}>
          <div className="stat-value" data-i18n={s.i18nValue}>{s.value}</div>
          <div className="stat-label" data-i18n={s.i18n}>{s.label}</div>
        </div>
      ))}
    </div>
  );
}

/* ============ LedgerStats — unique count-up scoreboard for the "Why Choose" band ============ */
function LedgerStat({ value, label, index, i18n, i18nValue }) {
  const ref = React.useRef(null);
  const [display, setDisplay] = React.useState(null);
  const match = /^(\d+)(.*)$/.exec(value);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (!match) { setDisplay(value); return; }
    const target = parseInt(match[1], 10);
    const suffix = match[2];
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        io.unobserve(el);
        const duration = 1300;
        const start = performance.now();
        const tick = (now) => {
          const t = Math.min(1, (now - start) / duration);
          const eased = 1 - Math.pow(1 - t, 3);
          setDisplay(Math.round(eased * target) + suffix);
          if (t < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
      });
    }, { threshold: 0.15, rootMargin: '0px 0px -10% 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, [value]);

  return (
    <div className="ledger-stat" ref={ref} style={{ animationDelay: (index * 0.08) + 's' }}>
      <div className="ledger-stat-value" data-i18n={display === null ? undefined : i18nValue}>{display === null ? (match ? '0' + match[2] : value) : display}</div>
      <div className="ledger-stat-label" data-i18n={i18n}>{label}</div>
    </div>
  );
}

function LedgerStats({ stats }) {
  return (
    <div className="ledger-stats">
      {stats.map((s, i) => <LedgerStat key={s.label} value={s.value} label={s.label} index={i} i18n={s.i18n} i18nValue={s.i18nValue} />)}
    </div>
  );
}

function Timeline({ items }) {
  return (
    <div className="timeline">
      {items.map((it, i) => (
        <div className="timeline-row" key={i}>
          <div className="timeline-index">{it.index || String(i + 1).padStart(2, '0')}</div>
          <div>
            <h3 className="timeline-title" data-i18n={it.i18nTitle}>{it.title}</h3>
            <p className="timeline-body" data-i18n={it.i18nBody}>{it.body}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

function ProcessGrid({ steps }) {
  const railRef = React.useRef(null);
  const [active, setActive] = React.useState(0);

  React.useEffect(() => {
    const rail = railRef.current;
    if (!rail) return;
    const cards = Array.from(rail.children);
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && entry.intersectionRatio > 0.6) {
            setActive(cards.indexOf(entry.target));
          }
        });
      },
      { root: rail, threshold: [0.6] }
    );
    cards.forEach((c) => io.observe(c));
    return () => io.disconnect();
  }, [steps]);

  return (
    <div>
      <div className="process-grid" ref={railRef}>
        {steps.map((s, i) => (
          <div className="process-step" key={i}>
            <span className="step-num">{String(i + 1).padStart(2, '0')}</span>
            <h4 data-i18n={s.key ? 'home.' + s.key + 'Title' : undefined}>{s.title}</h4>
            <p data-i18n={s.key ? 'home.' + s.key + 'Body' : undefined}>{s.body}</p>
          </div>
        ))}
      </div>
      <div className="process-dots">
        {steps.map((s, i) => <span key={i} className={'process-dot' + (i === active ? ' active' : '')}></span>)}
      </div>
      <div className="process-swipe-hint">
        <span>Swipe to see all {steps.length} steps</span>
        <i data-lucide="arrow-right" width="14" height="14"></i>
      </div>
    </div>
  );
}

function Testimonials({ items }) {
  return (
    <div className="testimonial-grid">
      {items.map((t, i) => (
        <div className="testimonial-card" key={i}>
          <p className="testimonial-quote" data-i18n={t.key ? 'home.' + t.key + 'Quote' : undefined}>“{t.quote}”</p>
          <div className="testimonial-attrib"><strong data-i18n={t.key ? 'home.' + t.key + 'Name' : undefined}>{t.name}</strong><span data-i18n={t.key ? 'home.' + t.key + 'Role' : undefined}>{t.role}</span></div>
        </div>
      ))}
    </div>
  );
}

function IndustryChips({ items }) {
  const { Chip } = window.CohereDesignSystem_4a3e6b;
  return (
    <div className="chip-row">
      {items.map((i) => <Chip key={i} variant="pill-outline">{i}</Chip>)}
    </div>
  );
}

function CtaBand({ eyebrow, title, sub, surface = 'green', i18nEyebrow, i18nTitle, i18nSub, i18nCta }) {
  const { Button } = window.CohereDesignSystem_4a3e6b;
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => { entries.forEach((e) => { if (e.isIntersecting) { setShown(true); io.unobserve(el); } }); },
      { threshold: 0.25 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <section className="section">
      <div className="container">
        <div ref={ref} className={'cta-band' + (shown ? ' cta-band--in' : '')}>
          <div className="cta-band-grid"></div>
          <div className="cta-band-corner cta-band-corner--tl"></div>
          <div className="cta-band-corner cta-band-corner--tr"></div>
          <div className="cta-band-corner cta-band-corner--bl"></div>
          <div className="cta-band-corner cta-band-corner--br"></div>
          {eyebrow && (
            <span className="cta-band-eyebrow"><span className="pf-live-dot pf-live-dot--gold"></span><span data-i18n={i18nEyebrow}>{eyebrow}</span></span>
          )}
          <div className="cta-band-rule"></div>
          <h2 className="cta-band-title" data-i18n={i18nTitle}>{title}</h2>
          {sub && <p className="cta-band-sub" data-i18n={i18nSub}>{sub}</p>}
          <a href="contact.html" style={{ textDecoration: 'none' }}>
            <span className="nav-cta-glow">
              <Button variant="primary" onDark><span data-i18n={i18nCta || 'nav.cta'}>Schedule a Consultation</span></Button>
            </span>
          </a>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Site: { Nav, Footer, useLucide, PageHero, SectionHead, ImgSlot, StatGrid, LedgerStats, Timeline, ProcessGrid, Testimonials, IndustryChips, CtaBand },
});
