// ═══════════════════════════════════════════════
// JAGTAR STUDIO — Design System Components
// ═══════════════════════════════════════════════

const JAGTAR = {};

// ─── Colors ───
JAGTAR.c = {
  bg:         '#F8F6F2',
  cream:      '#F2EDE6',
  charcoal:   '#1A1A1A',
  gray:       '#B8B5B0',
  gold:       '#B08D5C',
  terracotta: '#C97B5C',
  border:     '#E5E2DC',
  success:    '#5C7A5C',
  error:      '#A04444',
  dark:       '#111110',
};

// ─── Image map for real photos ───
JAGTAR.imageMap = {
  'hero': 'https://images.unsplash.com/photo-1618336753974-aae8e04506aa?w=1400&q=80&auto=format',
  'bust-front': 'https://images.unsplash.com/photo-1558618666-fcd25c85f82e?w=800&q=80&auto=format',
  'bust-side': 'https://images.unsplash.com/photo-1547891654-e66ed7ebb968?w=800&q=80&auto=format',
  'bust-quarter': 'https://images.unsplash.com/photo-1588771930296-9d16be4fd228?w=800&q=80&auto=format',
  'bust-detail': 'https://images.unsplash.com/photo-1618336753974-aae8e04506aa?w=800&q=80&auto=format',
  'bust-woman': 'https://images.unsplash.com/photo-1614107151491-6876eecbff89?w=800&q=80&auto=format',
  'bust-man': 'https://images.unsplash.com/photo-1547891654-e66ed7ebb968?w=800&q=80&auto=format',
  'bust-child': 'https://images.unsplash.com/photo-1513519245088-0e12902e35ca?w=800&q=80&auto=format',
  'lifestyle': 'https://images.unsplash.com/photo-1616047006789-b7af5afb8c20?w=1200&q=80&auto=format',
  'founder': 'https://images.unsplash.com/photo-1552058544-f2b08422138a?w=800&q=80&auto=format',
  'studio': 'https://images.unsplash.com/photo-1558618666-fcd25c85f82e?w=1400&q=80&auto=format',
  'process': 'https://images.unsplash.com/photo-1558618019-05d14e5dbf4c?w=800&q=80&auto=format',
  'packaging': 'https://images.unsplash.com/photo-1513519245088-0e12902e35ca?w=800&q=80&auto=format',
  'phone': 'https://images.unsplash.com/photo-1512941937669-90a1b58e7e9c?w=800&q=80&auto=format',
  'good-photo': 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=800&q=80&auto=format',
  'bad-photo': 'https://images.unsplash.com/photo-1519085360753-af0119f7cbe7?w=800&q=80&auto=format',
  'hand-finishing': 'https://images.unsplash.com/photo-1558618019-05d14e5dbf4c?w=1200&q=80&auto=format',
  'mantel': 'https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=800&q=80&auto=format',
  'preview': 'https://images.unsplash.com/photo-1618336753974-aae8e04506aa?w=600&q=80&auto=format',
};

// ─── label→key resolver ───
JAGTAR._resolveImg = (label) => {
  const l = (label || '').toLowerCase();
  if (l.includes('hero')) return JAGTAR.imageMap['hero'];
  if (l.includes('front angle') || l.includes('front view')) return JAGTAR.imageMap['bust-front'];
  if (l.includes('side profile') || l.includes('side')) return JAGTAR.imageMap['bust-side'];
  if (l.includes('three-quarter') || l.includes('quarter')) return JAGTAR.imageMap['bust-quarter'];
  if (l.includes('texture') || l.includes('detail') || l.includes('close-up')) return JAGTAR.imageMap['bust-detail'];
  if (l.includes('woman') || l.includes('profile')) return JAGTAR.imageMap['bust-woman'];
  if (l.includes('elderly') || l.includes('man')) return JAGTAR.imageMap['bust-man'];
  if (l.includes('child')) return JAGTAR.imageMap['bust-child'];
  if (l.includes('bookshelf') || l.includes('lifestyle') || l.includes('mantel')) return JAGTAR.imageMap['lifestyle'];
  if (l.includes('founder') || l.includes('candid')) return JAGTAR.imageMap['founder'];
  if (l.includes('studio') || l.includes('workspace') || l.includes('wide shot')) return JAGTAR.imageMap['studio'];
  if (l.includes('sculptor') || l.includes('hand-finish') || l.includes('finishing')) return JAGTAR.imageMap['hand-finishing'];
  if (l.includes('process') || l.includes('primed')) return JAGTAR.imageMap['process'];
  if (l.includes('unbox') || l.includes('packag') || l.includes('box') || l.includes('tissue')) return JAGTAR.imageMap['packaging'];
  if (l.includes('phone') || l.includes('choosing')) return JAGTAR.imageMap['phone'];
  if (l.includes('good') || l.includes('clear') || l.includes('natural light')) return JAGTAR.imageMap['good-photo'];
  if (l.includes('bad') || l.includes('blurry') || l.includes('dark')) return JAGTAR.imageMap['bad-photo'];
  if (l.includes('example front')) return JAGTAR.imageMap['good-photo'];
  if (l.includes('example side')) return JAGTAR.imageMap['bust-side'];
  if (l.includes('preview') || l.includes('bust preview')) return JAGTAR.imageMap['preview'];
  if (l.includes('bust')) return JAGTAR.imageMap['bust-front'];
  return null;
};

// ─── Image component with real photos ───
JAGTAR.Img = ({ label, dark, ratio = '4/3', style, className }) => {
  const src = JAGTAR._resolveImg(label);

  return (
    <div className={className} style={{
      aspectRatio: ratio,
      width: '100%',
      background: dark ? '#1a1916' : '#dedad2',
      position: 'relative', overflow: 'hidden',
      ...style,
    }}>
      {src ? (
        <img
          src={src}
          alt={label}
          loading="lazy"
          style={{
            position: 'absolute', inset: 0,
            width: '100%', height: '100%',
            objectFit: 'cover',
            filter: 'saturate(0.9) contrast(1.02)',
          }}
        />
      ) : (
        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: `linear-gradient(145deg, ${dark ? '#1a1916' : '#dedad2'} 0%, ${dark ? '#2a2722' : '#cec9c0'} 100%)`,
        }}>
          <span style={{
            fontFamily: '"Courier New", monospace',
            fontSize: 10, letterSpacing: 2, textTransform: 'uppercase',
            color: dark ? '#444038' : '#a8a298',
            padding: '6px 12px',
            background: dark ? 'rgba(20,20,18,0.7)' : 'rgba(240,236,228,0.7)',
          }}>{label}</span>
        </div>
      )}
      {/* subtle film grain overlay */}
      <div style={{
        position: 'absolute', inset: 0, opacity: 0.08, pointerEvents: 'none',
        backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='256' height='256' filter='url(%23n)' opacity='0.5'/%3E%3C/svg%3E")`,
        backgroundSize: '128px',
      }} />
    </div>
  );
};

// ─── Typography ───
JAGTAR.H1 = ({ children, style }) => (
  <h1 style={{
    fontFamily: "'Cormorant Garamond', Georgia, serif",
    fontSize: 'clamp(40px, 5vw, 72px)', fontWeight: 400, lineHeight: 1.1,
    color: JAGTAR.c.charcoal, margin: 0, letterSpacing: '-0.02em',
    ...style,
  }}>{children}</h1>
);

JAGTAR.H2 = ({ children, style }) => (
  <h2 style={{
    fontFamily: "'Cormorant Garamond', Georgia, serif",
    fontSize: 'clamp(30px, 3.5vw, 48px)', fontWeight: 400, lineHeight: 1.2,
    color: JAGTAR.c.charcoal, margin: 0, letterSpacing: '-0.01em',
    ...style,
  }}>{children}</h2>
);

JAGTAR.H3 = ({ children, style }) => (
  <h3 style={{
    fontFamily: "'Cormorant Garamond', Georgia, serif",
    fontSize: 'clamp(22px, 2.5vw, 32px)', fontWeight: 400, lineHeight: 1.3,
    color: JAGTAR.c.charcoal, margin: 0,
    ...style,
  }}>{children}</h3>
);

JAGTAR.Label = ({ children, style }) => (
  <span style={{
    fontFamily: "'Manrope', sans-serif",
    fontSize: 11, fontWeight: 500, letterSpacing: '0.18em',
    textTransform: 'uppercase', color: JAGTAR.c.gray,
    ...style,
  }}>{children}</span>
);

JAGTAR.Body = ({ children, style, small }) => (
  <p style={{
    fontFamily: "'Manrope', sans-serif",
    fontSize: small ? 14 : 18, fontWeight: 400, lineHeight: 1.65,
    color: '#5a5751', margin: 0, textWrap: 'pretty',
    ...style,
  }}>{children}</p>
);

// ─── Primary CTA Button ───
JAGTAR.CTA = ({ children, onClick, style, secondary }) => {
  const [hover, setHover] = React.useState(false);
  const [press, setPress] = React.useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => setPress(true)}
      onMouseUp={() => setPress(false)}
      style={{
        fontFamily: "'Manrope', sans-serif",
        fontSize: 13, fontWeight: 500, letterSpacing: '0.12em',
        textTransform: 'uppercase',
        padding: '16px 40px',
        border: secondary ? `1px solid ${JAGTAR.c.charcoal}` : 'none',
        background: secondary ? 'transparent' : (hover ? '#9e7d50' : JAGTAR.c.gold),
        color: secondary ? JAGTAR.c.charcoal : '#F8F6F2',
        cursor: 'pointer',
        transition: 'all 0.3s ease',
        transform: press ? 'scale(0.98)' : 'scale(1)',
        display: 'inline-block',
        ...style,
      }}
    >{children}</button>
  );
};

// ─── Text Button ───
JAGTAR.TextBtn = ({ children, onClick, style }) => {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        fontFamily: "'Manrope', sans-serif",
        fontSize: 13, fontWeight: 500, letterSpacing: '0.08em',
        textTransform: 'uppercase',
        padding: 0, border: 'none', background: 'none',
        color: JAGTAR.c.charcoal, cursor: 'pointer',
        borderBottom: `1px solid ${hover ? JAGTAR.c.charcoal : JAGTAR.c.border}`,
        paddingBottom: 2, transition: 'border-color 0.3s ease',
        ...style,
      }}
    >{children}</button>
  );
};

// ─── Navigation ───
JAGTAR.Nav = ({ currentPage, onNavigate, dark }) => {
  const [open, setOpen] = React.useState(false);
  const fg = dark ? '#F8F6F2' : JAGTAR.c.charcoal;
  const menuBg = dark ? '#1A1A1A' : '#F8F6F2';

  const links = [
    ['home', 'Home'],
    ['product', 'Commission'],
    ['how', 'Process'],
    ['account', 'My Orders'],
    ['checkout', 'Cart'],
  ];

  return (
    <>
      <nav style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 1000,
        padding: '0 clamp(20px, 4vw, 48px)',
        height: 72, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: dark ? 'rgba(17,17,16,0.9)' : 'rgba(248,246,242,0.92)',
        backdropFilter: 'blur(12px)',
        borderBottom: `1px solid ${dark ? 'rgba(255,255,255,0.06)' : JAGTAR.c.border}`,
        transition: 'background 0.4s ease',
      }}>
        <div
          onClick={() => onNavigate('home')}
          style={{
            fontFamily: "'Cormorant Garamond', Georgia, serif",
            fontSize: 18, fontWeight: 400, letterSpacing: '0.2em',
            color: fg, cursor: 'pointer', userSelect: 'none',
          }}
        >JAGTAR STUDIO</div>
        {/* Hamburger */}
        <button
          onClick={() => setOpen(!open)}
          style={{
            background: 'none', border: 'none', cursor: 'pointer',
            padding: 8, display: 'flex', flexDirection: 'column', gap: open ? 0 : 5,
            alignItems: 'center', justifyContent: 'center',
            width: 36, height: 36, position: 'relative',
          }}
          aria-label="Menu"
        >
          <span style={{
            display: 'block', width: 22, height: 1.5, background: fg,
            transition: 'all 0.3s ease',
            transform: open ? 'rotate(45deg) translateY(0.75px)' : 'none',
            position: open ? 'absolute' : 'relative',
          }} />
          <span style={{
            display: 'block', width: 22, height: 1.5, background: fg,
            transition: 'all 0.3s ease',
            transform: open ? 'rotate(-45deg) translateY(-0.75px)' : 'none',
            position: open ? 'absolute' : 'relative',
          }} />
        </button>
      </nav>

      {/* Full-screen menu overlay */}
      <div style={{
        position: 'fixed', inset: 0, zIndex: 999,
        background: menuBg,
        display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 12,
        opacity: open ? 1 : 0,
        pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity 0.4s ease',
      }}>
        {links.map(([key, label]) => (
          <button
            key={key}
            onClick={() => { onNavigate(key); setOpen(false); }}
            style={{
              fontFamily: "'Cormorant Garamond', Georgia, serif",
              fontSize: 'clamp(28px, 5vw, 48px)', fontWeight: 400,
              background: 'none', border: 'none', cursor: 'pointer',
              color: currentPage === key ? JAGTAR.c.gold : (dark ? '#F8F6F2' : JAGTAR.c.charcoal),
              padding: '12px 0',
              transition: 'color 0.3s ease',
            }}
          >{label}</button>
        ))}
      </div>
    </>
  );
};

// ─── Footer ───
JAGTAR.Footer = ({ onNavigate }) => {
  const footLinkStyle = {
    fontFamily: "'Manrope', sans-serif",
    fontSize: 14, color: '#5a5751',
    textDecoration: 'none',
    borderBottom: `1px solid ${JAGTAR.c.border}`,
    paddingBottom: 1,
    transition: 'border-color 0.2s, color 0.2s',
  };
  return (
    <footer style={{
      padding: 'clamp(48px, 8vw, 100px) clamp(24px, 6vw, 80px)',
      borderTop: `1px solid ${JAGTAR.c.border}`,
      background: JAGTAR.c.bg,
    }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
          gap: 48, marginBottom: 60,
        }}>
          <div>
            <div style={{
              fontFamily: "'Cormorant Garamond', Georgia, serif",
              fontSize: 20, letterSpacing: '0.15em', color: JAGTAR.c.charcoal,
              marginBottom: 16,
            }}>JAGTAR STUDIO</div>
            <JAGTAR.Body small style={{ maxWidth: 260 }}>
              Personalized sculpture from photographs. Hand-finished resin. Made with care.
            </JAGTAR.Body>
          </div>
          <div>
            <JAGTAR.Label style={{ display: 'block', marginBottom: 16 }}>Navigate</JAGTAR.Label>
            {[['home','Home'],['product','Commission'],['how','Process'],['account','My Orders'],['checkout','Cart']].map(([k,l]) => (
              <div key={k} style={{ marginBottom: 8 }}>
                <JAGTAR.TextBtn onClick={() => onNavigate(k)} style={{ fontSize: 14, textTransform: 'none', letterSpacing: 0 }}>{l}</JAGTAR.TextBtn>
              </div>
            ))}
          </div>
          <div>
            <JAGTAR.Label style={{ display: 'block', marginBottom: 16 }}>Legal</JAGTAR.Label>
            {[
              ['/privacy.html', 'Privacy'],
              ['/terms.html', 'Terms'],
              ['/refunds.html', 'Refunds'],
              ['/shipping.html', 'Shipping'],
              ['/cookies.html', 'Cookies'],
              ['/acceptable-use.html', 'Acceptable use'],
            ].map(([href, label]) => (
              <div key={href} style={{ marginBottom: 8 }}>
                <a href={href} style={footLinkStyle}
                  onMouseEnter={e => { e.currentTarget.style.color = JAGTAR.c.charcoal; e.currentTarget.style.borderColor = JAGTAR.c.charcoal; }}
                  onMouseLeave={e => { e.currentTarget.style.color = '#5a5751'; e.currentTarget.style.borderColor = JAGTAR.c.border; }}
                >{label}</a>
              </div>
            ))}
          </div>
          <div>
            <JAGTAR.Label style={{ display: 'block', marginBottom: 16 }}>Connect</JAGTAR.Label>
            <div style={{ marginBottom: 8 }}>
              <a href="https://instagram.com/jagtarstudio" rel="noopener noreferrer" target="_blank" style={footLinkStyle}>Instagram</a>
            </div>
            <div style={{ marginBottom: 8 }}>
              <a href="mailto:hello@jagtarstudio.com" style={footLinkStyle}>hello@jagtarstudio.com</a>
            </div>
          </div>
        </div>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          paddingTop: 24, borderTop: `1px solid ${JAGTAR.c.border}`,
          flexWrap: 'wrap', gap: 12,
        }}>
          <JAGTAR.Body small style={{ color: JAGTAR.c.gray }}>{'©'} 2026 Jagtar Studio</JAGTAR.Body>
          <JAGTAR.Body small style={{ color: JAGTAR.c.gray }}>Made with care in Ontario, Canada</JAGTAR.Body>
        </div>
      </div>
    </footer>
  );
};

// ─── Form Field ───
JAGTAR.Field = ({
  label, placeholder, type = 'text',
  name, value, onChange, required, autoComplete,
  half, style,
}) => {
  const controlled = value !== undefined;
  return (
    <div style={{ marginBottom: 20, ...style }}>
      <label style={{
        fontFamily: "'Manrope', sans-serif",
        fontSize: 12, fontWeight: 500, letterSpacing: '0.08em',
        textTransform: 'uppercase', color: JAGTAR.c.gray,
        display: 'block', marginBottom: 8,
      }}>{label}</label>
      <input
        type={type}
        name={name}
        placeholder={placeholder}
        required={required}
        autoComplete={autoComplete}
        {...(controlled ? { value, onChange } : {})}
        style={{
          width: '100%', boxSizing: 'border-box',
          padding: '14px 16px',
          fontFamily: "'Manrope', sans-serif",
          fontSize: 15, color: JAGTAR.c.charcoal,
          border: `1px solid ${JAGTAR.c.border}`,
          background: '#fff',
          outline: 'none',
          transition: 'border-color 0.3s ease',
        }}
        onFocus={e => e.target.style.borderColor = JAGTAR.c.gold}
        onBlur={e => e.target.style.borderColor = JAGTAR.c.border}
      />
    </div>
  );
};

// ─── Section wrapper with fade-in ───
JAGTAR.Section = ({ children, style, dark, cream, id }) => {
  const ref = React.useRef(null);
  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.1 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  return (
    <section
      ref={ref}
      id={id}
      style={{
        padding: `clamp(60px, 10vw, 160px) clamp(24px, 6vw, 80px)`,
        background: dark ? JAGTAR.c.dark : cream ? JAGTAR.c.cream : JAGTAR.c.bg,
        opacity: visible ? 1 : 0,
        transform: visible ? 'translateY(0)' : 'translateY(30px)',
        transition: 'opacity 0.7s ease, transform 0.7s ease',
        ...style,
      }}
    >
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        {children}
      </div>
    </section>
  );
};

// ─── Divider ───
JAGTAR.Divider = () => (
  <div style={{
    width: 48, height: 1, background: JAGTAR.c.border,
    margin: '0 auto',
  }} />
);

// ─── Upload Zone ───
JAGTAR.Upload = ({ label, sublabel }) => {
  const [hover, setHover] = React.useState(false);
  const [file, setFile] = React.useState(null);

  return (
    <label
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        border: `2px dashed ${hover ? JAGTAR.c.gold : JAGTAR.c.border}`,
        background: hover ? 'rgba(176,141,92,0.04)' : 'transparent',
        padding: 'clamp(32px, 4vw, 48px)',
        cursor: 'pointer',
        transition: 'all 0.3s ease',
        textAlign: 'center',
        minHeight: 180,
      }}
    >
      <input type="file" accept="image/*" style={{ display: 'none' }}
        onChange={e => setFile(e.target.files[0]?.name)} />
      {/* Upload icon */}
      <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke={hover ? JAGTAR.c.gold : JAGTAR.c.gray} strokeWidth="1.5" style={{ marginBottom: 16, transition: 'stroke 0.3s ease' }}>
        <path d="M12 16V4m0 0L8 8m4-4l4 4M4 18h16" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
      <JAGTAR.Label style={{ color: hover ? JAGTAR.c.gold : JAGTAR.c.gray, marginBottom: 6, transition: 'color 0.3s ease' }}>
        {file || label}
      </JAGTAR.Label>
      {sublabel && !file && (
        <JAGTAR.Body small style={{ color: JAGTAR.c.gray, marginTop: 4 }}>{sublabel}</JAGTAR.Body>
      )}
    </label>
  );
};

Object.assign(window, { JAGTAR });
