/* ============================================================
   Rainbow Group — signature.jsx
   Shared primitives: useReveal, RGCursor, Scramble, PrismLayer,
   Heritage, HERITAGE_EVENTS, Stat, SectionHead.
   Per DESIGN-SYSTEM.md §4.
   ============================================================ */

const { useState: useStateS, useEffect: useEffectS, useRef: useRefS, useMemo: useMemoS } = React;

/* ---------- HERITAGE_EVENTS ---------- */
const HERITAGE_EVENTS = [
  { year: '2001', title: 'Hasan Habib General Trading founded',
    body: 'The parent firm begins trading in Kuwait — laying the supply, client and craft network that RGCC would later inherit.' },
  { year: '2008', title: 'First turnkey fit-out',
    body: 'The group takes on full responsibility for an interior, end-to-end — joinery, stone, gypsum, specialty paints under one roof.' },
  { year: '2015', title: '300th project milestone',
    body: 'The workshop passes 300 completed sites. Long-term relationships with Al Shaya, Tamdeen and Kharafi deepen.' },
  { year: '2017', title: 'RGCC incorporated',
    body: 'Rainbow Group Contracting Company W.L.L is formally established to carry forward the interior-finishing practice with dedicated leadership.' },
  { year: '2020', title: 'Four Points by Sheraton',
    body: 'Full hospitality fit-out at Four Points — public areas, F&B and guest floors delivered in a single phase alongside parallel private-villa work.' },
  { year: '2022', title: '500 projects delivered',
    body: 'Cumulative project count crosses 500. The firm formalises its five-discipline service map and in-house joinery workshop.' },
  { year: '2025', title: 'Haute Dolci',
    body: 'Delivery of a 1,200 m² feature facade and double-height GRG dome, setting a new benchmark for hospitality fit-out in Kuwait.' },
];

/* ---------- useReveal hook ---------- */
function useReveal() {
  const ref = useRefS(null);
  useEffectS(() => {
    const el = ref.current;
    if (!el) return;
    if (document.documentElement.getAttribute('data-motion') === 'still' ||
        (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches)) {
      el.classList.add('in');
      return;
    }
    el.style.opacity = '0';
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.style.opacity = '1';
          entry.target.classList.add('in');
          io.unobserve(entry.target);
        }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

/* ---------- RGCursor ---------- */
function RGCursor() {
  const ref = useRefS(null);
  const [label, setLabel] = useStateS('');
  const [expanded, setExpanded] = useStateS(false);
  const [isButton, setIsButton] = useStateS(false);

  useEffectS(() => {
    if (window.matchMedia && window.matchMedia('(max-width: 900px)').matches) return;
    const move = (e) => {
      if (!ref.current) return;
      ref.current.style.left = e.clientX + 'px';
      ref.current.style.top = e.clientY + 'px';
      const hit = e.target.closest && e.target.closest('[data-cursor-label]');
      const btn = e.target.closest && e.target.closest('a, button, .btn');
      if (hit) {
        setLabel(hit.getAttribute('data-cursor-label') || '');
        setExpanded(true);
        setIsButton(!!btn);
      } else if (e.target.closest && e.target.closest('a, button')) {
        setLabel('CLICK');
        setExpanded(true);
        setIsButton(!!btn);
      } else {
        setLabel('');
        setExpanded(false);
        setIsButton(false);
      }
    };
    window.addEventListener('mousemove', move);
    return () => window.removeEventListener('mousemove', move);
  }, []);

  return React.createElement(
    'div',
    { ref, className: `rg-cursor ${expanded ? 'expanded' : ''} ${isButton ? 'is-button' : ''}`, 'aria-hidden': 'true' },
    expanded ? label : ''
  );
}

/* ---------- Scramble ---------- */
function Scramble({ text = '', trigger = 0, duration = 900 }) {
  const [out, setOut] = useStateS(text);
  useEffectS(() => {
    const chars = '█▓▒░/#*+·.—';
    const start = Date.now();
    let raf;
    const tick = () => {
      const t = Math.min(1, (Date.now() - start) / duration);
      const lockedLen = Math.floor(t * text.length);
      let next = '';
      for (let i = 0; i < text.length; i++) {
        if (i < lockedLen || text[i] === ' ') next += text[i];
        else next += chars[Math.floor(Math.random() * chars.length)];
      }
      setOut(next);
      if (t < 1) raf = setTimeout(tick, 40);
    };
    tick();
    return () => clearTimeout(raf);
  }, [trigger, text, duration]);
  return out;
}

/* ---------- PrismLayer ---------- */
function PrismLayer() {
  const [mouse, setMouse] = useStateS({ x: 0.5, y: 0.5 });
  const [angle, setAngle] = useStateS(0);

  useEffectS(() => {
    const move = (e) => setMouse({ x: e.clientX / window.innerWidth, y: e.clientY / window.innerHeight });
    window.addEventListener('mousemove', move);
    return () => window.removeEventListener('mousemove', move);
  }, []);

  useEffectS(() => {
    let raf;
    const tick = () => {
      setAngle(a => (a + 0.15) % 360);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return React.createElement(
    'div',
    { className: 'prism-layer', 'aria-hidden': 'true' },
    React.createElement('div', {
      className: 'prism-arc',
      style: { left: `${mouse.x * 100}%`, top: `${mouse.y * 100}%`, '--arc-angle': angle }
    }),
    React.createElement('div', {
      className: 'prism-arc',
      style: { left: `${(1 - mouse.x) * 100}%`, top: `${mouse.y * 80 + 20}%`, '--arc-angle': -angle, opacity: 0.6, transform: 'translate(-50%,-50%) scale(0.6)' }
    })
  );
}

/* ---------- SectionHead ---------- */
function SectionHead({ idx, kicker, en, ar, dark = false }) {
  const muted = dark ? 'rgba(243,237,226,0.5)' : 'var(--muted)';
  const ink = dark ? '#f3ede2' : 'var(--ink)';
  // `idx` kept in the signature for API compatibility but no longer rendered.
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 40, alignItems: 'baseline', marginBottom: 56 }}>
      <div>
        <div className="eyebrow" style={{ color: muted, marginBottom: 8 }}>{kicker}</div>
        <h2 className="display" style={{ fontSize: 'clamp(40px, 5.5vw, 84px)', color: ink, display: 'flex', gap: 24, alignItems: 'baseline', flexWrap: 'wrap' }}>
          <span>{en}</span>
          <span className="ar" style={{ fontSize: '0.55em', color: muted, fontWeight: 400 }}>{ar}</span>
        </h2>
      </div>
      <div style={{ width: 60, height: 1, background: ink, opacity: 0.6 }} />
    </div>
  );
}

/* ---------- Stat helper ---------- */
function Stat({ num, suffix, label, ar, dark = false }) {
  const ivory = dark ? 'rgba(243,237,226,0.6)' : 'var(--muted)';
  return (
    <div style={{ borderTop: `1px solid ${dark ? 'rgba(243,237,226,0.25)' : 'var(--rule)'}`, paddingTop: 24 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span className="display" style={{ fontSize: 'clamp(56px, 7vw, 104px)', color: dark ? '#f3ede2' : 'var(--ink)' }}>{num}</span>
        {suffix ? <span className="display" style={{ fontSize: 'clamp(32px, 3.5vw, 56px)', color: 'var(--gold-hi)' }}>{suffix}</span> : null}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 12, gap: 16 }}>
        <span className="mono" style={{ color: ivory, fontSize: 11 }}>{label}</span>
        <span className="ar" style={{ fontSize: 14, color: ivory }}>{ar}</span>
      </div>
    </div>
  );
}

/* ---------- Heritage ---------- */
function Heritage() {
  const [active, setActive] = useStateS(3);
  const ref = useReveal();
  const e = HERITAGE_EVENTS[active];
  return (
    <section id="heritage" ref={ref} className="reveal" style={{ background: 'var(--paper-2)', padding: '140px 0 120px' }}>
      <div className="wrap">
        <SectionHead idx="01" kicker="Heritage · الإرث" en="A quarter century, one thread" ar="ربعُ قرنٍ من خيطٍ واحد" />
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 64, alignItems: 'start' }} data-mobile-stack>
          <div>
            <p className="display" style={{ fontSize: 'clamp(22px, 2.5vw, 32px)', lineHeight: 1.35, maxWidth: '28ch' }}>
              RGCC was <em style={{ color: 'var(--gold)', fontStyle: 'italic' }}>incorporated in 2017</em>, but the craft, the supply chain, and the client relationships trace back to <em style={{ color: 'var(--gold)', fontStyle: 'italic' }}>2001</em> — when the parent firm, Hasan Habib General Trading, first opened in Kuwait City.
            </p>
            <p style={{ marginTop: 24, color: 'var(--ink-2)', fontSize: 15, lineHeight: 1.7, maxWidth: '44ch' }}>
              We carry a <strong style={{ fontWeight: 500 }}>twenty-five-year memory</strong> into every new site: which stone mason finishes a travertine return cleanly, which gypsum cures to the right colour, which client prefers silent delivery at 4 a.m. None of that is written in a manual — it is inherited.
            </p>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24, marginTop: 48 }}>
              <div><div className="mono" style={{ color: 'var(--muted)', marginBottom: 8 }}>First trading year</div><div className="display" style={{ fontSize: 28 }}>2001</div></div>
              <div><div className="mono" style={{ color: 'var(--muted)', marginBottom: 8 }}>RGCC incorporated</div><div className="display" style={{ fontSize: 28 }}>2017</div></div>
              <div><div className="mono" style={{ color: 'var(--muted)', marginBottom: 8 }}>One thread</div><div className="display" style={{ fontSize: 28 }}>25<span style={{ color: 'var(--gold-hi)' }}>+</span></div></div>
            </div>
          </div>
          <div style={{ background: 'var(--paper)', padding: 36, border: '1px solid var(--rule)', position: 'sticky', top: 100 }}>
            <div className="mono" style={{ color: 'var(--gold)', marginBottom: 14 }}>{`· Milestone 0${active + 1}`}</div>
            <div className="display" style={{ fontSize: 48, color: 'var(--gold)', fontStyle: 'italic', marginBottom: 20 }}>{e.year}</div>
            <h3 className="display" style={{ fontSize: 24, marginBottom: 16 }}>{e.title}</h3>
            <p style={{ color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.6 }}>{e.body}</p>
          </div>
        </div>
        <div style={{ marginTop: 72, borderTop: '1px solid var(--rule)', paddingTop: 24, display: 'grid', gridTemplateColumns: `repeat(${HERITAGE_EVENTS.length}, 1fr)`, gap: 4 }}>
          {HERITAGE_EVENTS.map((ev, i) => (
            <button
              key={ev.year}
              onMouseEnter={() => setActive(i)}
              onClick={() => setActive(i)}
              data-cursor-label={ev.year}
              style={{
                display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 10,
                padding: '12px 0', background: 'transparent', border: 0, cursor: 'pointer',
                fontFamily: 'inherit', color: 'inherit', textAlign: 'left'
              }}
            >
              <span style={{ width: i === active ? 9 : 5, height: i === active ? 9 : 5, borderRadius: '50%', background: i === active ? 'var(--gold)' : 'var(--muted)', transition: 'all 0.3s ease' }} />
              <span className="mono" style={{ color: i === active ? 'var(--gold)' : 'var(--muted)', fontSize: 11, letterSpacing: '0.16em' }}>{ev.year}</span>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Social icons (inline SVG, editorial) ---------- */
function SocialIcons({ variant = 'dark' }) {
  // `variant` just controls accessibility — colour comes from `currentColor` on the parent.
  return (
    <div className="social-row" role="list">
      <a className="social-icon" role="listitem" href="https://instagram.com/rainbowgroupkwt" target="_blank" rel="noopener" aria-label="Rainbow Group on Instagram" data-cursor-label="Instagram">
        <svg viewBox="0 0 24 24" aria-hidden="true">
          <path d="M12 2.2c3.2 0 3.6 0 4.8.1 1.2 0 1.9.2 2.4.4.6.2 1 .5 1.5 1s.8.9 1 1.5c.2.5.4 1.2.4 2.4.1 1.2.1 1.6.1 4.8s0 3.6-.1 4.8c0 1.2-.2 1.9-.4 2.4a4 4 0 0 1-1 1.5 4 4 0 0 1-1.5 1c-.5.2-1.2.4-2.4.4-1.2.1-1.6.1-4.8.1s-3.6 0-4.8-.1c-1.2 0-1.9-.2-2.4-.4a4 4 0 0 1-1.5-1 4 4 0 0 1-1-1.5c-.2-.5-.4-1.2-.4-2.4C2.2 15.6 2.2 15.2 2.2 12s0-3.6.1-4.8c0-1.2.2-1.9.4-2.4a4 4 0 0 1 1-1.5 4 4 0 0 1 1.5-1c.5-.2 1.2-.4 2.4-.4C8.4 2.2 8.8 2.2 12 2.2Zm0 1.8c-3.1 0-3.5 0-4.7.1-1.1 0-1.7.2-2.1.3-.5.2-.9.4-1.3.8-.4.4-.6.8-.8 1.3-.1.4-.3 1-.3 2.1C2.7 9.8 2.7 10.2 2.7 12s0 2.2.1 3.4c0 1.1.2 1.7.3 2.1.2.5.4.9.8 1.3.4.4.8.6 1.3.8.4.1 1 .3 2.1.3 1.2.1 1.6.1 4.7.1s3.5 0 4.7-.1c1.1 0 1.7-.2 2.1-.3.5-.2.9-.4 1.3-.8.4-.4.6-.8.8-1.3.1-.4.3-1 .3-2.1.1-1.2.1-1.6.1-3.4s0-2.2-.1-3.4c0-1.1-.2-1.7-.3-2.1a3 3 0 0 0-.8-1.3 3 3 0 0 0-1.3-.8c-.4-.1-1-.3-2.1-.3C15.5 4 15.1 4 12 4Zm0 3.1a5 5 0 1 1 0 10 5 5 0 0 1 0-10Zm0 1.8a3.2 3.2 0 1 0 0 6.4 3.2 3.2 0 0 0 0-6.4Zm5.2-2.4a1.2 1.2 0 1 1 0 2.4 1.2 1.2 0 0 1 0-2.4Z" />
        </svg>
      </a>
      <a className="social-icon" role="listitem" href="https://www.linkedin.com/company/rainbow-group-contracting-kwt" target="_blank" rel="noopener" aria-label="Rainbow Group on LinkedIn" data-cursor-label="LinkedIn">
        <svg viewBox="0 0 24 24" aria-hidden="true">
          <path d="M20.45 20.45h-3.55v-5.57c0-1.33-.03-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.36V9h3.41v1.56h.05a3.74 3.74 0 0 1 3.37-1.85c3.6 0 4.27 2.37 4.27 5.45v6.29ZM5.34 7.43a2.06 2.06 0 1 1 0-4.12 2.06 2.06 0 0 1 0 4.12Zm1.78 13.02H3.56V9h3.56v11.45ZM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0Z" />
        </svg>
      </a>
      <a className="social-icon" role="listitem" href="https://wa.me/96522410045" target="_blank" rel="noopener" aria-label="WhatsApp +965 2241 0045" data-cursor-label="WhatsApp">
        <svg viewBox="0 0 24 24" aria-hidden="true">
          <path d="M19.1 4.9A10 10 0 0 0 3.7 17.5L2.1 22l4.6-1.6A10 10 0 1 0 19.1 4.9Zm-7 16.2a8.3 8.3 0 0 1-4.2-1.2l-.3-.2-2.7 1 1-2.7-.2-.3a8.3 8.3 0 1 1 15.7-3.9 8.3 8.3 0 0 1-9.3 7.3Zm4.6-6.2c-.2-.1-1.4-.7-1.7-.8-.2-.1-.4-.1-.5.1-.1.2-.6.8-.8 1-.1.1-.3.1-.5 0a6.7 6.7 0 0 1-2-1.3 7.5 7.5 0 0 1-1.3-1.7c-.1-.2 0-.3.1-.5l.4-.5.2-.5V8.3c-.1-.1-.5-1.3-.7-1.8-.2-.5-.4-.4-.5-.4h-.5c-.2 0-.5.1-.7.3a2.6 2.6 0 0 0-.9 2c0 1.2.9 2.4 1 2.5.1.2 1.7 2.6 4.1 3.6a13 13 0 0 0 1.4.5c.6.2 1.1.2 1.5.1.5-.1 1.4-.6 1.6-1.2a2 2 0 0 0 .2-1.2c-.1-.1-.2-.2-.5-.3Z" />
        </svg>
      </a>
    </div>
  );
}

/* ---------- MashrabiyaCorner ---------- */
function MashrabiyaCorner() {
  return (
    <svg className="mashrabiya-corner" viewBox="0 0 220 220" aria-hidden="true">
      <defs>
        <pattern id="mash" width="40" height="40" patternUnits="userSpaceOnUse">
          <circle cx="20" cy="20" r="18" fill="none" stroke="#f3ede2" strokeWidth="1" />
          <path d="M 20 2 L 20 38 M 2 20 L 38 20" stroke="#f3ede2" strokeWidth="1" />
          <path d="M 6 6 L 34 34 M 34 6 L 6 34" stroke="#f3ede2" strokeWidth="0.6" opacity="0.8" />
        </pattern>
      </defs>
      <rect width="220" height="220" fill="url(#mash)" />
    </svg>
  );
}

/* ---------- Publish ---------- */
Object.assign(window, {
  useReveal, RGCursor, Scramble, PrismLayer, Heritage, MashrabiyaCorner,
  SectionHead, Stat, HERITAGE_EVENTS, SocialIcons
});
