/* ═══════════════════════════════════════════════
   AUREAL — Shared UI Components
   Nav, Footer, Section, FadeIn, Button, etc.
   ═══════════════════════════════════════════════ */

/* ── Section ── */
function Section({ bg = 'dark', children, className = '', style, id, padTop }) {
  const cs = `au-section sec-${bg} ${className}`.trim();
  const s = padTop ? { paddingTop: padTop, ...style } : style;
  return (
    <section className={cs} style={s} id={id}>
      <div className="au-container">{children}</div>
    </section>
  );
}

/* ── FadeIn (IntersectionObserver) ── */
function FadeIn({ children, delay = 0, className = '', as = 'div', style }) {
  const ref = React.useRef();
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) { setVisible(true); obs.disconnect(); } },
      { threshold: 0.08 }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  const Tag = as;
  return (
    <Tag
      ref={ref}
      className={className}
      style={{
        opacity: visible ? 1 : 0,
        transform: visible ? 'translateY(0)' : 'translateY(20px)',
        transition: `opacity 0.6s var(--ease) ${delay}ms, transform 0.6s var(--ease) ${delay}ms`,
        ...style,
      }}
    >
      {children}
    </Tag>
  );
}

/* ── Eyebrow ── */
function Eyebrow({ children }) {
  return <p className="eyebrow">{children}</p>;
}

/* ── GoldRule ── */
function GoldRule({ style }) {
  return <div className="gold-rule" style={style}></div>;
}

/* ── Button ── */
function Btn({ variant = 'primary', children, onClick, style, className = '' }) {
  return (
    <button className={`au-btn au-btn-${variant} ${className}`} onClick={onClick} style={style}>
      {children}
    </button>
  );
}

/* ── Image Placeholder ── */
function ImgPlaceholder({ aspect = '4/5', label = 'Product photo', style, className = '' }) {
  return (
    <div className={`au-img-placeholder ${className}`} style={{ aspectRatio: aspect, ...style }}>
      <span style={{ position: 'relative', zIndex: 1 }}>{label}</span>
    </div>
  );
}

/* ── Croppable Image (drag pan · wheel zoom · persisted) ── */
function CropImage({ src, tweaks, setTweak, keyPrefix = 'founder', defaultAspect = '3/4', style, className = '' }) {
  const aspect = tweaks[keyPrefix + 'Aspect'] || defaultAspect;
  const zoom = Math.max(1, Math.min(4, tweaks[keyPrefix + 'Zoom'] ?? 1));
  const x = tweaks[keyPrefix + 'X'] ?? 0;
  const y = tweaks[keyPrefix + 'Y'] ?? 0;

  const frameRef = React.useRef(null);
  const drag = React.useRef(null);
  const [hover, setHover] = React.useState(false);
  const [editing, setEditing] = React.useState(false); // tweaks-mode crop UI

  // Show overlay controls only when Tweaks panel is active
  React.useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') setEditing(true);
      if (e.data?.type === '__deactivate_edit_mode') setEditing(false);
    };
    window.addEventListener('message', onMsg);
    // Initial probe: if a Tweaks panel is already open elsewhere we won't know,
    // but harmless — overlay just stays hidden until toggle.
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const maxOffset = 50 * (zoom - 1); // |x|, |y| ≤ this
  const clamp = (v) => Math.max(-maxOffset, Math.min(maxOffset, v));

  const onPointerDown = (e) => {
    if (!editing) return;
    drag.current = { sx: e.clientX, sy: e.clientY, ox: x, oy: y };
    e.currentTarget.setPointerCapture(e.pointerId);
  };

  const onPointerMove = (e) => {
    if (!drag.current) return;
    const rect = frameRef.current.getBoundingClientRect();
    const dx = ((e.clientX - drag.current.sx) / rect.width) * 100;
    const dy = ((e.clientY - drag.current.sy) / rect.height) * 100;
    setTweak({
      [keyPrefix + 'X']: clamp(drag.current.ox + dx),
      [keyPrefix + 'Y']: clamp(drag.current.oy + dy),
    });
  };

  const endDrag = () => { drag.current = null; };

  const onWheel = (e) => {
    if (!editing) return;
    e.preventDefault();
    const delta = -e.deltaY * 0.003;
    const newZoom = Math.max(1, Math.min(4, zoom + delta));
    const ratio = newZoom > 1 ? (newZoom - 1) / Math.max(0.0001, zoom - 1) : 0;
    setTweak({
      [keyPrefix + 'Zoom']: +newZoom.toFixed(3),
      [keyPrefix + 'X']: +(x * ratio).toFixed(2),
      [keyPrefix + 'Y']: +(y * ratio).toFixed(2),
    });
  };

  const reset = (e) => {
    e.stopPropagation();
    setTweak({
      [keyPrefix + 'Zoom']: 1,
      [keyPrefix + 'X']: 0,
      [keyPrefix + 'Y']: 0,
    });
  };

  return (
    <div
      ref={frameRef}
      className={`au-crop ${className}`}
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={endDrag}
      onPointerCancel={endDrag}
      onWheel={onWheel}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        aspectRatio: aspect,
        overflow: 'hidden',
        position: 'relative',
        borderRadius: 16,
        background: '#0a0a0a',
        cursor: editing ? (drag.current ? 'grabbing' : 'grab') : 'default',
        userSelect: 'none',
        touchAction: editing ? 'none' : 'auto',
        boxShadow: '0 30px 60px -20px rgba(0,0,0,0.4)',
        ...style,
      }}
    >
      <img
        src={src}
        alt=""
        draggable={false}
        style={{
          position: 'absolute',
          inset: 0,
          width: '100%',
          height: '100%',
          objectFit: 'cover',
          objectPosition: 'center',
          transform: `translate(${x}%, ${y}%) scale(${zoom})`,
          transformOrigin: 'center',
          pointerEvents: 'none',
          willChange: 'transform',
        }}
      />

      {/* Edit-mode overlay: rule-of-thirds grid + hint + reset */}
      {editing && (
        <React.Fragment>
          <div style={{
            position: 'absolute', inset: 0, pointerEvents: 'none',
            opacity: hover || drag.current ? 1 : 0.35,
            transition: 'opacity 0.2s',
            backgroundImage:
              'linear-gradient(to right, transparent calc(33.333% - 0.5px), rgba(255,255,255,0.35) calc(33.333% - 0.5px), rgba(255,255,255,0.35) calc(33.333% + 0.5px), transparent calc(33.333% + 0.5px), transparent calc(66.666% - 0.5px), rgba(255,255,255,0.35) calc(66.666% - 0.5px), rgba(255,255,255,0.35) calc(66.666% + 0.5px), transparent calc(66.666% + 0.5px)),' +
              'linear-gradient(to bottom, transparent calc(33.333% - 0.5px), rgba(255,255,255,0.35) calc(33.333% - 0.5px), rgba(255,255,255,0.35) calc(33.333% + 0.5px), transparent calc(33.333% + 0.5px), transparent calc(66.666% - 0.5px), rgba(255,255,255,0.35) calc(66.666% - 0.5px), rgba(255,255,255,0.35) calc(66.666% + 0.5px), transparent calc(66.666% + 0.5px))',
            boxShadow: 'inset 0 0 0 1.5px rgba(204,158,4,0.7)',
            borderRadius: 16,
          }} />
          <div style={{
            position: 'absolute', left: 12, bottom: 12,
            display: 'flex', gap: 8, alignItems: 'center',
            opacity: hover ? 1 : 0,
            transition: 'opacity 0.2s',
            pointerEvents: hover ? 'auto' : 'none',
          }}>
            <span style={{
              fontFamily: 'system-ui, sans-serif',
              fontSize: 11, fontWeight: 500,
              letterSpacing: '0.04em',
              color: '#fff',
              background: 'rgba(0,0,0,0.7)',
              backdropFilter: 'blur(6px)',
              padding: '6px 10px', borderRadius: 999,
              border: '1px solid rgba(255,255,255,0.12)',
            }}>drag to pan · scroll to zoom · {Math.round(zoom * 100)}%</span>
            <button
              onClick={reset}
              onPointerDown={(e) => e.stopPropagation()}
              style={{
                fontFamily: 'system-ui, sans-serif',
                fontSize: 11, fontWeight: 600,
                letterSpacing: '0.04em',
                color: '#fff',
                background: 'rgba(204,158,4,0.85)',
                padding: '6px 10px', borderRadius: 999,
                border: '1px solid rgba(255,255,255,0.18)',
                cursor: 'pointer',
              }}
            >RESET</button>
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

/* ── Navigation ── */
function Nav({ currentPage, navigate, cartCount = 0 }) {
  const [open, setOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);

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

  const go = (page) => { navigate(page); setOpen(false); };

  const links = [
    { id: 'custom', label: 'Custom' },
    { id: 'pricing', label: 'Pricing' },
    { id: 'community', label: 'Community' },
    { id: 'about', label: 'About' },
    { id: 'join', label: 'Join' },
  ];

  return (
    <nav className="au-nav" style={scrolled ? { boxShadow: 'var(--shadow-sm)' } : {}}>
      <div className="au-nav-inner">
        <button className="au-nav-logo" onClick={() => go('home')}><img src={(window.__resources && window.__resources.logoTag) || 'assets/Logo_Tag_v2.png'} alt="Aureal" style={{ height: '28px', display: 'block' }} /></button>
        <button className="au-nav-toggle" onClick={() => setOpen(!open)} aria-label="Menu">
          <span></span><span></span><span></span>
        </button>
        <ul className={`au-nav-links ${open ? 'open' : ''}`}>
          {links.map(l => (
            <li key={l.id}>
              <button
                className={`au-nav-link ${currentPage === l.id ? 'active' : ''}`}
                onClick={() => go(l.id)}
              >
                {l.label}
              </button>
            </li>
          ))}
          <li>
            <button
              className={`au-nav-link ${currentPage === 'cart' ? 'active' : ''}`}
              onClick={() => go('cart')}
              aria-label="Cart"
              style={{ padding: '0.25rem 0.5rem' }}
            >
              <span className="au-cart-icon">
                <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"></path>
                  <line x1="3" y1="6" x2="21" y2="6"></line>
                  <path d="M16 10a4 4 0 01-8 0"></path>
                </svg>
                {cartCount > 0 && <span className="au-cart-badge">{cartCount}</span>}
              </span>
            </button>
          </li>
          <li>
            <button className="au-nav-cta" onClick={() => go('contact')}>Get Started</button>
          </li>
        </ul>
      </div>
    </nav>
  );
}

/* ── Footer ── */
function Footer({ navigate }) {
  const go = (page) => { navigate(page); };
  return (
    <footer className="au-footer">
      <div className="au-container">
        <div className="au-footer-grid">
          <div className="au-footer-brand">
            <div className="au-footer-logo">AUREAL</div>
            <div className="au-footer-tagline">Custom apparel for communities that care.</div>
            <p style={{ fontSize: '0.88rem', color: 'var(--text-muted)', maxWidth: 280 }}>
              California LLC
            </p>
          </div>
          <div className="au-footer-col">
            <h4>Services</h4>
            <ul>
              <li><button onClick={() => go('custom')}>Custom Orders</button></li>
              <li><button onClick={() => go('pricing')}>Pricing</button></li>
              <li><button onClick={() => go('community')}>Community Storefront</button></li>
            </ul>
          </div>
          <div className="au-footer-col">
            <h4>Company</h4>
            <ul>
              <li><button onClick={() => go('about')}>About</button></li>
              <li><button onClick={() => go('join')}>Join the Team</button></li>
              <li><button onClick={() => go('contact')}>Get Started</button></li>
            </ul>
          </div>
        </div>
        <div className="au-footer-bottom">
          <span>© 2026 Aureal. All rights reserved.</span>
          <span>Made with intention.</span>
        </div>
      </div>
    </footer>
  );
}

/* ── Gold CTA Section ── */
function GoldCTA({ headline = "Ready to make something worth wearing?", cta = "Get Started", navigate }) {
  return (
    <Section bg="gold">
      <div style={{ textAlign: 'center', padding: '1rem 0' }}>
        <FadeIn>
          <h2 style={{ fontStyle: 'normal', fontWeight: 700, marginBottom: '1.5rem' }}>{headline}</h2>
          <Btn variant="dark" onClick={() => navigate('contact')}>{cta}</Btn>
        </FadeIn>
      </div>
    </Section>
  );
}

/* ── Staggered Grid ── */
function StaggerGrid({ children, columns = 3, gap = '2rem', style }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${columns}, 1fr)`, gap, ...style }}>
      {React.Children.map(children, (child, i) => (
        <FadeIn delay={i * 80}>{child}</FadeIn>
      ))}
    </div>
  );
}

// Export to window
Object.assign(window, {
  Section, FadeIn, Eyebrow, GoldRule, Btn, ImgPlaceholder, CropImage,
  Nav, Footer, GoldCTA, StaggerGrid,
});
