// components.jsx — shared UI components

const { useState, useEffect, useRef } = React;

function InquiryBag({ t, onOpen }) {
  const I = (typeof window !== 'undefined') ? window.INQUIRY : null;
  const [n, setN] = useState(() => I ? I.count() : 0);
  useEffect(() => {
    if (!I) return;
    const onChange = () => setN(I.count());
    window.addEventListener('lesso-inquiry-change', onChange);
    return () => window.removeEventListener('lesso-inquiry-change', onChange);
  }, []);
  if (!I) return null;
  const inq = (t && t.inquiry) || {};
  const aria = (inq.badgeAria || 'Open inquiry list ({n} items)').replace('{n}', n);
  return (
    <button type="button" className="inquiry-bag" aria-label={aria} onClick={onOpen}>
      <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
        <path d="M6 7h12l-1 13H7L6 7z"/>
        <path d="M9 7V5a3 3 0 0 1 6 0v2"/>
      </svg>
      {n > 0 && <span className="inquiry-bag__badge">{n}</span>}
    </button>
  );
}

function Header({ t, lang, setLang, route, go, buildUrl }) {
  const items = [
    { key: 'home', label: t.nav.home },
    { key: 'products', label: t.nav.products },
    { key: 'about', label: t.nav.about },
    { key: 'quality', label: t.nav.quality },
    { key: 'news', label: t.nav.news },
    { key: 'contact', label: t.nav.contact },
  ];
  // Mobile menu state. Auto-closes on every route change so visitors don't
  // see a stale open dropdown after navigating from a link inside it.
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => { setMenuOpen(false); }, [route.page]);
  const onClickLink = (e, page, extra) => {
    if (e.metaKey||e.ctrlKey||e.shiftKey||e.button===1) return;
    e.preventDefault();
    setMenuOpen(false);
    go(page, extra);
  };
  return (
    <header className={`site-header ${menuOpen ? 'nav-open' : ''}`}>
      <div className="container header-inner">
        <a className="brand" href={buildUrl(lang, 'home')} onClick={(e) => onClickLink(e, 'home')}>
          <img className="brand-mark" src="/assets/icons/lesso-wordmark.png" alt={t.brand.name} />
          <span className="brand-sub">{t.brand.sub}</span>
        </a>
        <button
          className="nav-toggle"
          type="button"
          aria-label={menuOpen ? 'Fechar menu' : 'Abrir menu'}
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen(o => !o)}
        >
          <span className="nav-toggle-bar" />
          <span className="nav-toggle-bar" />
          <span className="nav-toggle-bar" />
        </button>
        <nav className="nav">
          {items.map(it => (
            <a key={it.key} href={buildUrl(lang, it.key)}
              className={route.page === it.key || (it.key === 'products' && route.page === 'product') ? 'active' : ''}
              onClick={(e) => onClickLink(e, it.key)}>{it.label}</a>
          ))}
        </nav>
        <div className="header-right">
          <div className="lang-switch" role="tablist" aria-label="Language">
            <button className={lang === 'pt' ? 'active' : ''} aria-pressed={lang==='pt'} onClick={() => setLang('pt')}>PT</button>
            <button className={lang === 'en' ? 'active' : ''} aria-pressed={lang==='en'} onClick={() => setLang('en')}>EN</button>
            <button className={lang === 'es' ? 'active' : ''} aria-pressed={lang==='es'} onClick={() => setLang('es')}>ES</button>
          </div>
          <InquiryBag t={t} onOpen={() => window.INQUIRY_UI && window.INQUIRY_UI.openDrawer()} />
          <a className="btn btn-primary btn-sm arrow" href={buildUrl(lang, 'contact')} onClick={(e) => onClickLink(e, 'contact')}>
            {t.nav.inquiry}
          </a>
        </div>
      </div>
    </header>
  );
}

function Footer({ t, go, buildUrl, lang }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-top">
          <div>
            <div className="brand">
              <img className="brand-mark" src="/assets/icons/lesso-wordmark.png" alt={t.brand.name} />
              <span className="brand-sub" style={{color:'#a8aba0'}}>{t.brand.sub}</span>
            </div>
            <p className="about-text">{t.footer.about}</p>
          </div>
          <div>
            <h5>{t.footer.colProducts}</h5>
            <ul>
              {t.footer.prodLinks.map((label, i) => (
                <li key={i}><a onClick={e => { e.preventDefault(); go('products'); }} href={buildUrl(lang, 'products')}>{label}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h5>{t.footer.colCompany}</h5>
            <ul>
              {t.footer.coLinks.map((l, i) => (
                <li key={i}><a onClick={e => { e.preventDefault(); go('about'); }} href={buildUrl(lang, 'about')}>{l}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h5>{t.footer.colResources}</h5>
            <ul>
              {t.footer.resLinks.map((l, i) => (
                <li key={i}><a onClick={e => { e.preventDefault(); go(i < 3 ? 'quality' : 'contact'); }} href={buildUrl(lang, i < 3 ? 'quality' : 'contact')}>{l}</a></li>
              ))}
            </ul>
          </div>
          <FooterSocial t={t} lang={lang} />
        </div>
        <div className="footer-bottom">
          <div>{t.footer.legal}</div>
          <div>{t.footer.legal2}</div>
        </div>
      </div>
    </footer>
  );
}

// Inline SVG icons for the footer + contact social cards. Same path
// data as the SocialLinksSection in pages.jsx — repeated here so the
// footer is self-contained without pulling pages.jsx state.
const SOCIAL_ICONS = {
  youtube:   <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M23.5 6.2a3 3 0 00-2.1-2.1C19.5 3.5 12 3.5 12 3.5s-7.5 0-9.4.6A3 3 0 00.5 6.2C0 8.1 0 12 0 12s0 3.9.5 5.8a3 3 0 002.1 2.1c1.9.6 9.4.6 9.4.6s7.5 0 9.4-.6a3 3 0 002.1-2.1c.5-1.9.5-5.8.5-5.8s0-3.9-.5-5.8zM9.6 15.6V8.4l6.3 3.6-6.3 3.6z"/></svg>,
  whatsapp:  <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M17.5 14.4c-.3-.2-1.8-.9-2.1-1-.3-.1-.5-.1-.7.2-.2.3-.8 1-1 1.2-.2.2-.4.2-.6.1-.3-.2-1.2-.4-2.2-1.4-.8-.7-1.4-1.6-1.5-1.9-.2-.3 0-.4.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5-.1-.2-.7-1.7-1-2.3-.3-.6-.5-.5-.7-.5-.2 0-.4 0-.6 0s-.5.1-.8.4c-.3.3-1.1 1-1.1 2.5 0 1.5 1.1 2.9 1.2 3.1.2.2 2.1 3.2 5.1 4.5.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.8-.7 2-1.4.3-.7.3-1.3.2-1.4-.1-.1-.3-.2-.6-.3zM12 2C6.5 2 2 6.5 2 12c0 1.9.5 3.7 1.5 5.3L2 22l4.8-1.5c1.5.8 3.2 1.3 5.2 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2z"/></svg>,
  facebook:  <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M22 12c0-5.5-4.5-10-10-10S2 6.5 2 12c0 5 3.7 9.1 8.4 9.9v-7H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.4 2.9h-2.3v7C18.3 21.1 22 17 22 12z"/></svg>,
  twitter:   <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>,
  douyin:    <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M16.6 2c.5 1.8 1.5 3.2 3 4.2 1.1.7 2.3 1.1 3.4 1.2v3.4c-2.2 0-4.3-.7-6-2v8.6c0 3.6-2.9 6.6-6.5 6.6S4 21 4 17.4s2.9-6.6 6.5-6.6c.5 0 1 .1 1.5.2v3.5c-.5-.2-1-.3-1.5-.3-1.7 0-3.1 1.4-3.1 3.2 0 1.8 1.4 3.2 3.1 3.2s3.1-1.4 3.1-3.2V2h3z"/></svg>,
  instagram: <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M12 2.2c3.2 0 3.6 0 4.8.1 1.2 0 1.8.2 2.2.4.6.2 1 .5 1.4.9.4.4.7.8.9 1.4.2.4.4 1 .4 2.2.1 1.2.1 1.6.1 4.8s0 3.6-.1 4.8c0 1.2-.2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1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6zm-2 0l-8 5-8-5h16zm0 12H4V8l8 5 8-5v10z"/></svg>,
};

// Footer's 5th column — small icon grid linking out to every social
// platform the customer has filled in. Hidden in full if no URLs are
// configured.
function FooterSocial({ t, lang }) {
  const social = (window.CONTACT && window.CONTACT.social) || {};
  // bg = chip background colour, fg = SVG colour. On the dark footer the
  // X / TikTok marks use a white background with black ink so they don't
  // blend into the surface, the rest use the platform brand colour.
  const rows = [
    { id: 'youtube',   url: social.youtube,      name: 'YouTube',  bg: '#FF0000', fg: '#fff' },
    { id: 'whatsapp',  url: social.whatsappLink, name: 'WhatsApp', bg: '#25D366', fg: '#fff' },
    { id: 'facebook',  url: social.facebook,     name: 'Facebook', bg: '#1877F2', fg: '#fff' },
    { id: 'twitter',   url: social.twitter,      name: 'X',        bg: '#ffffff', fg: '#000' },
    { id: 'douyin',    url: social.douyin,       name: 'TikTok',   bg: '#ffffff', fg: '#000' },
    { id: 'instagram', url: social.instagram,    name: 'Instagram', bg: '#E4405F', fg: '#fff' },
    { id: 'email',     url: social.emailAlt ? `mailto:${social.emailAlt}` : '', name: social.emailAlt || 'E-mail', bg: '#525252', fg: '#fff' },
  ].filter(r => r.url);
  if (rows.length === 0) return null;
  return (
    <div>
      <h5>{(t && t.footer && t.footer.colSocial) || ({ pt: 'Conecte-se', en: 'Connect', es: 'Conéctese' }[lang] || 'Connect')}</h5>
      <ul className="footer-social-icons">
        {rows.map(r => (
          <li key={r.id}>
            <a
              href={r.url}
              target="_blank"
              rel="noopener noreferrer"
              aria-label={r.name}
              title={r.name}
              style={{ '--social-bg': r.bg, '--social-fg': r.fg }}
            >{SOCIAL_ICONS[r.id]}</a>
          </li>
        ))}
      </ul>
    </div>
  );
}

function Crumbs({ items, go, lang, buildUrl }) {
  const onClick = (e, to) => { if (e.metaKey||e.ctrlKey||e.shiftKey||e.button===1) return; e.preventDefault(); go(to); };
  return (
    <nav className="crumbs" aria-label="Breadcrumb">
      <ol>
        {items.map((it, i) => (
          <li key={i}>
            {it.to && buildUrl ? (
              <a href={buildUrl(lang, it.to)} onClick={(e) => onClick(e, it.to)}>{it.label}</a>
            ) : it.to ? (
              <a href="#" onClick={(e) => onClick(e, it.to)}>{it.label}</a>
            ) : (
              <span aria-current="page">{it.label}</span>
            )}
            {i < items.length - 1 && <span className="sep" aria-hidden="true">/</span>}
          </li>
        ))}
      </ol>
    </nav>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// InquiryAddButton — reusable + / ✓ toggle that lives inside product cards.
// Two visual variants:
//   variant="corner" — absolutely-positioned circular pill on top-right
//     of the .thumb (used by ProductCard)
//   variant="row"    — full-width secondary button at the bottom of a card
//     (used by subproduct cards)
// Renders nothing if window.INQUIRY is somehow missing (e.g. mid-boot).
// ────────────────────────────────────────────────────────────────────────────
function InquiryAddButton({ itemKey, label, image, url, variant, t }) {
  const I = (typeof window !== 'undefined') ? window.INQUIRY : null;
  const [added, setAdded] = useState(() => !!(I && I.has(itemKey)));
  useEffect(() => {
    if (!I) return;
    const onChange = () => setAdded(I.has(itemKey));
    window.addEventListener('lesso-inquiry-change', onChange);
    return () => window.removeEventListener('lesso-inquiry-change', onChange);
  }, [itemKey]);
  if (!I) return null;
  const onClick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (I.has(itemKey)) {
      I.remove(itemKey);
    } else {
      I.add({ key: itemKey, label, image, url, addedAt: new Date().toISOString() });
    }
  };
  const inq = (t && t.inquiry) || {};
  if (variant === 'corner') {
    return (
      <button
        type="button"
        className={'pc-add' + (added ? ' is-added' : '')}
        aria-label={added ? inq.removeAria : inq.addAria}
        onClick={onClick}
      >
        {added ? '✓' : '+'}
      </button>
    );
  }
  // variant === 'row'
  return (
    <button
      type="button"
      className={'sub-card__add' + (added ? ' is-added' : '')}
      onClick={onClick}
    >
      {added ? (inq.subAdded || '✓ Added') : (inq.subAdd || '+ Add')}
    </button>
  );
}

function ProductCard({ product, go, tone, t, lang, buildUrl }) {
  const href = buildUrl ? buildUrl(lang, 'product', { slug: product.slug }) : '#';
  const openProduct = () => go('product', { slug: product.slug });
  const onClick = (e) => {
    if (e.defaultPrevented) return;
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) {
      window.open(href, '_blank', 'noopener');
      return;
    }
    openProduct();
  };
  return (
    <div
      className="product-card"
      role="link"
      tabIndex={0}
      onClick={onClick}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          openProduct();
        }
      }}
      aria-label={product.name}
      data-href={href}
    >
      <div className="thumb">
        <img
          src={product.image || placeholderImg(product.short, tone)}
          alt=""
          loading="eager"
          decoding="async"
          onError={(e) => { e.currentTarget.src = placeholderImg(product.short, tone); }}
        />
        <span className="tag">{product.tag}</span>
        <InquiryAddButton
          itemKey={'series:' + product.slug}
          label={product.name}
          image={product.image}
          url={buildUrl ? buildUrl(lang, 'product', { slug: product.slug }) : '#'}
          variant="corner"
          t={t}
        />
      </div>
      <div className="body">
        <h3>{product.name}</h3>
        <p className="desc">{product.desc}</p>
        <div className="specs">
          {product.specs.map((s, i) => <span key={i} className="spec-chip">{s}</span>)}
        </div>
        <span className="link" aria-hidden="true">{(t && t.pd && t.pd.learnMore) || 'Learn more'}</span>
      </div>
    </div>
  );
}

function FAQItem({ q, a }) {
  const [open, setOpen] = useState(false);
  const id = useRef('faq-' + Math.random().toString(36).slice(2, 9));
  const btnId = id.current + '-btn';
  const panelId = id.current + '-panel';
  return (
    <div className={'faq-item' + (open ? ' open' : '')}>
      <button
        id={btnId}
        className="faq-q"
        aria-expanded={open}
        aria-controls={panelId}
        onClick={() => setOpen(!open)}
      >
        <span>{q}</span>
        <span className="plus" aria-hidden="true">+</span>
      </button>
      <div
        id={panelId}
        role="region"
        aria-labelledby={btnId}
        className="a"
      >{a}</div>
    </div>
  );
}

function CTABand({ t, go }) {
  return (
    <section className="section">
      <div className="container">
        <div className="cta-band">
          <div>
            <h2>{t.home.ctaBandH}</h2>
            <p>{t.home.ctaBandP}</p>
          </div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
            <button className="btn btn-primary btn-lg arrow" onClick={() => go('contact')}>{t.home.ctaPrimary}</button>
            <button className="btn btn-secondary btn-lg" onClick={() => go('quality')}>{t.nav.quality}</button>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Header, Footer, Crumbs, ProductCard, FAQItem, CTABand, InquiryAddButton, InquiryBag });
