// services-brands.jsx — Services (3 variants) + Brand wall (2 variants)
// Service copy and brand logos live in services-data.js — edit there, not here.

const SERVICES = SERVICES_DATA;

function SvcAccordion() {
  const [open, setOpen] = React.useState(0);
  return (
    <div className="svc-list">
      {SERVICES.map((s, i) =>
        <div key={s.n} className="svc-row" data-open={open === i}
          onClick={() => setOpen(open === i ? -1 : i)}>
          <div className="svc-head">
            <div className="svc-num">{s.n}</div>
            <div className="svc-name">
              {s.name.replace(s.nameEm, '')}<em>{s.nameEm}</em>
            </div>
            <div className={`svc-tag ${s.status === 'coming' ? 'coming' : ''}`}>
              <span className="pulse"></span>
              {s.tag}
            </div>
            <div className="svc-toggle" aria-label="Toggle">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M7 1v12M1 7h12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
              </svg>
            </div>
          </div>
          <div className="svc-body-wrap">
            <div className="svc-body-inner">
              <div className="svc-body">
                <p className="svc-desc">{s.desc}</p>
                <div className="svc-deliv">
                  <div className="svc-deliv-lbl">What's included</div>
                  <ul>
                    {s.deliv.map(([n, v], j) =>
                      <li key={j}><span>{n}</span><span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-60)' }}>{v}</span></li>
                    )}
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>);
}

function SvcGrid() {
  return (
    <div className="svc-grid">
      {SERVICES.map((s) =>
        <div key={s.n} className="svc-card">
          <div className="svc-img"><img src={s.img} alt="" /></div>
          <div className="svc-num">{s.n} — {s.tag.toUpperCase()}</div>
          <h3 className="svc-name">
            {s.name.replace(s.nameEm, '')}<em>{s.nameEm}</em>
          </h3>
          <p className="svc-desc">{s.desc}</p>
          <div className={`svc-tag ${s.status === 'coming' ? 'coming' : ''}`}>
            <span className="pulse"></span>
            {s.tag}
          </div>
        </div>
      )}
    </div>);
}

function SvcHList() {
  const [hover, setHover] = React.useState({ idx: -1, x: 0, y: 0 });
  const cur = hover.idx >= 0 ? SERVICES[hover.idx] : null;
  return (
    <div className="svc-hlist"
      onMouseLeave={() => setHover({ idx: -1, x: 0, y: 0 })}>
      {SERVICES.map((s, i) => (
        <div key={s.n} className="svc-hrow"
          onMouseEnter={() => setHover(h => ({ ...h, idx: i }))}
          onMouseMove={(e) => {
            const r = e.currentTarget.parentElement.getBoundingClientRect();
            setHover({ idx: i, x: e.clientX - r.left, y: e.clientY - r.top });
          }}>
          <div className="svc-num">{s.n}</div>
          <h3 className="svc-name">
            {s.name.replace(s.nameEm, '')}<em>{s.nameEm}</em>
          </h3>
          <div className={`svc-tag ${s.status === 'coming' ? 'coming' : ''}`}>
            <span className="pulse"></span>
            {s.tag}
          </div>
        </div>
      ))}
      {/* Cursor-tracking image with grey overlay + label */}
      <div className="svc-hover-img"
        style={{ opacity: hover.idx >= 0 ? 1 : 0, left: hover.x, top: hover.y }}
        onClick={leave}>
        <img src={cur ? cur.img : SERVICES[0].img} alt="" />
        <div className="svc-hover-img-overlay">
          <span className="svc-hover-img-label">{cur ? cur.name : ''}</span>
        </div>
      </div>
    </div>
  );
}

function SvcSplit() {
  const all  = SERVICES;
  const main = all.slice(0, 2);
  const add  = all.slice(2);

  // Build a rotating pool of all 4 service images per service
  const imgPool = all.map(s => s.img);
  const getImgs = (i) => [...imgPool.slice(i), ...imgPool.slice(0, i)];

  const [hover, setHover] = React.useState({ idx: -1, x: 0, y: 0 });
  const [imgIdx, setImgIdx] = React.useState(0);
  const intervalRef = React.useRef(null);
  const wrapRef = React.useRef(null);

  const cur = hover.idx >= 0 ? all[hover.idx] : null;
  const imgs = cur ? getImgs(hover.idx) : [];

  React.useEffect(() => {
    clearInterval(intervalRef.current);
    setImgIdx(0);
    if (hover.idx < 0 || imgs.length <= 1) return;
    intervalRef.current = setInterval(
      () => setImgIdx(i => (i + 1) % imgs.length),
      1400
    );
    return () => clearInterval(intervalRef.current);
  }, [hover.idx]);

  const track = (idx) => (e) => {
    if (!wrapRef.current) return;
    const r = wrapRef.current.getBoundingClientRect();
    setHover({ idx, x: e.clientX - r.left, y: e.clientY - r.top });
  };

  const leave = () => { clearInterval(intervalRef.current); setHover({ idx: -1, x: 0, y: 0 }); };

  // Touch: tap to select/deselect — mouse events handle desktop
  const handleTap = (idx) => (e) => {
    if (e.nativeEvent.pointerType === 'mouse') return;
    e.stopPropagation();
    if (hover.idx === idx) { leave(); return; }
    if (!wrapRef.current) return;
    const wr = wrapRef.current.getBoundingClientRect();
    const er = e.currentTarget.getBoundingClientRect();
    setHover({ idx, x: er.left - wr.left + er.width / 2, y: er.top - wr.top + er.height / 2 });
  };

  return (
    <div className="svc-split" ref={wrapRef} onMouseLeave={leave}>

      <div className="svc-split-cards">
        {main.map((s, i) => {
          const Tag = s.page ? 'a' : 'div';
          const linkProps = s.page ? { href: s.page } : {};
          return (
            <Tag key={s.n} {...linkProps} className="svc-split-card"
              onMouseEnter={track(i)} onMouseMove={track(i)} onClick={handleTap(i)}>
              <div className="svc-split-top">
                <span className="svc-split-num">{s.n}</span>
                <span className={`svc-tag ${s.status === 'coming' ? 'coming' : ''}`}>
                  <span className="pulse"></span>{s.tag}
                </span>
              </div>
              <h3 className="svc-split-name">
                {s.name.replace(s.nameEm, '')}<em>{s.nameEm}</em>
              </h3>
              <p className="svc-split-desc">{s.desc.split('.')[0]}.</p>
              {s.page && (
                <span className="svc-split-cta">
                  See packages
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                    <path d="M2.5 9.5L9.5 2.5M9.5 2.5H4M9.5 2.5V8" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </span>
              )}
            </Tag>
          );
        })}
      </div>

      <div className="svc-add">
        <div className="svc-add-eyebrow">Additional services</div>
        <div className="svc-add-list">
          {add.map((s, i) => (
            <div key={s.n} className="svc-add-item"
              onMouseEnter={track(main.length + i)} onMouseMove={track(main.length + i)} onClick={handleTap(main.length + i)}>
              <span className="svc-add-num">{s.n}</span>
              <span className="svc-add-name">{s.name.replace(s.nameEm, '')}<em>{s.nameEm}</em></span>
              <span className="svc-add-desc">{s.desc.split('.')[0]}.</span>
              <span className="svc-add-tag">{s.tag}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Cursor-tracking slideshow — follows mouse across entire section */}
      <div className="svc-hover-img"
        style={{ opacity: hover.idx >= 0 ? 1 : 0, left: hover.x, top: hover.y }}>
        {imgs.length > 0 && <img key={imgIdx} src={imgs[imgIdx]} alt="" />}
        <div className="svc-hover-img-overlay">
          <span className="svc-hover-img-label">{cur ? cur.name : ''}</span>
        </div>
      </div>
    </div>
  );
}

function Services({ style }) {
  return (
    <section className="sec snap-section" id="services"
      data-screen-label="03 Services" data-comment-anchor="services">
      <div className="sec-hd">
        <div className="num">(02)</div>
        <h2 className="title">The <em>services.</em></h2>
        <div className="aside">4 services</div>
      </div>
      {style === 'split' && <SvcSplit />}
      {style === 'grid' && <SvcGrid />}
      {style === 'list' && <SvcHList />}
      {(!style || style === 'accordion') && <SvcAccordion />}
    </section>);
}

// ── Brand wall ──────────────────────────────────────────
// Logo arrays (BRAND_LOGOS_ROW1, BRAND_LOGOS_ROW2, BRAND_LOGOS) live in services-data.js.
// To add/swap a logo: update services-data.js — it will propagate here automatically.

function BrandsClean() {
  return (
    <div className="brand-clean-grid">
      {BRAND_LOGOS.map((src, i) => (
        <div key={i} className="brand-clean-cell">
          <img src={src} alt="" className="brand-clean-img"
            onMouseEnter={e => { e.currentTarget.style.filter = 'brightness(0) opacity(.85)'; }}
            onMouseLeave={e => { e.currentTarget.style.filter = 'brightness(0) opacity(.5)'; }}
          />
        </div>
      ))}
    </div>
  );
}

function BrandsMarquee() {
  return (
    <div className="brands-row">
      {BRAND_LOGOS.map((src, i) =>
        <div key={i} className="brand-item"><img src={src} alt="" /></div>
      )}
    </div>
  );
}

function BrandsGrid() {
  return (
    <div className="brands-grid">
      {BRAND_LOGOS.map((src, i) =>
        <div key={i} className="brand-cell"><img src={src} alt="" /></div>
      )}
    </div>
  );
}

function Brands({ style }) {
  return (
    <section className="brands-section snap-section"
      data-screen-label="02 Brands" data-comment-anchor="brands">

      {/* Section heading row */}
      <div className="sec brands-sec-hd">
        <div className="sec-hd" style={{ marginBottom: 0, borderBottom: 0, paddingBottom: 32 }}>
          <div className="num">(01)</div>
          <h2 className="title">Trusted by brands <em>globally.</em></h2>
          <div className="aside">Dubai → Worldwide</div>
        </div>
      </div>

      {/* Stats */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        gap: 'clamp(24px, 5vw, 64px)', flexWrap: 'wrap',
        padding: '0 var(--gutter) clamp(20px, 2.5vw, 36px)',
      }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 'clamp(34px, 4vw, 62px)', lineHeight: 1, color: 'var(--ink)' }}>300+</div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 'clamp(8px, 0.75vw, 11px)', letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--ink-60)', marginTop: 'clamp(6px, 0.8vw, 10px)' }}>Brands Supported</div>
        </div>
        <div style={{ width: 1, height: 'clamp(32px, 3.5vw, 50px)', background: 'var(--ink-20)', flexShrink: 0 }} />
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 'clamp(34px, 4vw, 62px)', lineHeight: 1, color: 'var(--ink)' }}>650+</div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 'clamp(8px, 0.75vw, 11px)', letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--ink-60)', marginTop: 'clamp(6px, 0.8vw, 10px)' }}>Social Assets Delivered</div>
        </div>
      </div>

      {/* Logo wall */}
      <BrandsClean />
    </section>
  );
}

Object.assign(window, { Services, Brands, SERVICES, BRAND_LOGOS });
