/* ============================================================
   Shared UI primitives — Evans Web Store
   ============================================================ */
const { useState, useEffect, useRef, useContext, createContext } = React;

const AppCtx = createContext(null);

/* ---------- Icons (stroke, 1.6) ---------- */
function Icon({ name, size = 20, className = '', style }) {
  const s = { width: size, height: size, fill: 'none', stroke: 'currentColor',
    strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round', ...style };
  const paths = {
    cart: <><circle cx="9" cy="20" r="1.4"/><circle cx="18" cy="20" r="1.4"/><path d="M2.5 3h2.2l2.2 12.3a1.6 1.6 0 0 0 1.6 1.3h8.4a1.6 1.6 0 0 0 1.6-1.3L21 6.5H6.2"/></>,
    user: <><circle cx="12" cy="8" r="3.6"/><path d="M4.5 20a7.5 7.5 0 0 1 15 0"/></>,
    chevron: <path d="M9 6l6 6-6 6"/>,
    chevronDown: <path d="M6 9l6 6 6-6"/>,
    chevronLeft: <path d="M15 6l-6 6 6 6"/>,
    check: <path d="M20 6L9 17l-5-5"/>,
    checkCircle: <><circle cx="12" cy="12" r="9.2"/><path d="M8.5 12.2l2.4 2.4 4.6-4.8"/></>,
    plus: <path d="M12 5v14M5 12h14"/>,
    minus: <path d="M5 12h14"/>,
    search: <><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.2-3.2"/></>,
    truck: <><path d="M3 6h11v9H3z"/><path d="M14 9h4l3 3v3h-7z"/><circle cx="7" cy="18" r="1.6"/><circle cx="17.5" cy="18" r="1.6"/></>,
    box: <><path d="M3 8l9-5 9 5v8l-9 5-9-5z"/><path d="M3 8l9 5 9-5M12 13v8"/></>,
    pin: <><path d="M12 21s-7-6.2-7-11a7 7 0 0 1 14 0c0 4.8-7 11-7 11z"/><circle cx="12" cy="10" r="2.4"/></>,
    coins: <><ellipse cx="9" cy="7" rx="6" ry="2.8"/><path d="M3 7v5c0 1.5 2.7 2.8 6 2.8M3 12v5c0 1.5 2.7 2.8 6 2.8"/><ellipse cx="16" cy="14" rx="5" ry="2.4"/><path d="M11 14v5c0 1.3 2.2 2.4 5 2.4s5-1.1 5-2.4v-5"/></>,
    bell: <><path d="M18 8a6 6 0 0 0-12 0c0 7-3 8-3 8h18s-3-1-3-8"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/></>,
    grid: <><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></>,
    users: <><circle cx="9" cy="8" r="3.2"/><path d="M3.5 19a5.5 5.5 0 0 1 11 0"/><path d="M16 5.2a3.2 3.2 0 0 1 0 6M17.5 19a5.5 5.5 0 0 0-2.3-4.5"/></>,
    alert: <><path d="M12 3l9.5 16.5H2.5z"/><path d="M12 9.5v4.5M12 17.2v.1"/></>,
    logout: <><path d="M15 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h9"/><path d="M19 12H9m0 0l3.5-3.5M9 12l3.5 3.5"/></>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M2 12h3M19 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1"/></>,
    receipt: <><path d="M5 3v18l2-1.3 2 1.3 2-1.3 2 1.3 2-1.3 2 1.3V3l-2 1.3-2-1.3-2 1.3-2-1.3-2 1.3z"/><path d="M8 8h8M8 12h8M8 16h5"/></>,
    trash: <><path d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M6 7l1 13a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-13"/></>,
    edit: <><path d="M14 5l5 5M4 20l1-4L16 5l3 3L8 19z"/></>,
    shield: <><path d="M12 3l8 3v6c0 4.5-3.4 7.8-8 9-4.6-1.2-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></>,
    spark: <path d="M12 3l1.8 5.4L19 10l-5.2 1.6L12 17l-1.8-5.4L5 10l5.2-1.6z"/>,
    arrowRight: <path d="M5 12h14m0 0l-5.5-5.5M19 12l-5.5 5.5"/>,
  };
  return <svg viewBox="0 0 24 24" className={className} style={s}>{paths[name]}</svg>;
}

/* ---------- Logo (real Evans lockup, locked to 733:231 ratio) ---------- */
function Logo({ size = 34, light = false }) {
  const h = size * 1.34;
  const w = h * (733 / 231);
  return (
    <img src="header-logo.png" alt="Evans Equipment & Environmental"
      className={light ? 'logo-light' : ''}
      style={{ height: h, width: w, maxWidth: 'none', flexShrink: 0, alignSelf: 'flex-start', display: 'block' }} />
  );
}

/* ---------- Garment placeholder image ---------- */
function Garment({ product, color, tag = true, logo = true }) {
  const c = color || product.colors[0];
  const fill = COLORS[c] || '#cfd6d4';
  const isWhite = ['white','cream','silver','stone','hivis','tan','khaki'].includes(c);
  return (
    <div className="garment">
      <div dangerouslySetInnerHTML={{ __html: garmentSVG(product.kind, fill) }} />
      {logo && product.kind !== 'cap' && (
        <div className="chest-logo" style={{ top: '34%', left: '56%' }}>
          <div style={{ width: 14, height: 14, borderRadius: '50%', border: `1.6px solid ${isWhite ? 'rgba(0,0,0,.4)' : 'rgba(255,255,255,.85)'}`, display:'flex', alignItems:'center', justifyContent:'center' }}>
            <div style={{ width: 5, height: 5, borderRadius: '50%', background: isWhite ? 'rgba(0,0,0,.4)' : 'rgba(255,255,255,.85)' }}/>
          </div>
        </div>
      )}
      {product.fr && <div className="badge badge-amber" style={{ position:'absolute', top:10, right:10 }}>FR</div>}
      {tag && <div className="garment-tag">Product photo</div>}
    </div>
  );
}

/* ---------- Swatch row ---------- */
function Swatches({ colors, selected, onSelect, lg = false, max }) {
  const shown = max ? colors.slice(0, max) : colors;
  const extra = max ? colors.length - max : 0;
  return (
    <div className="swatches">
      {shown.map(c => (
        <button key={c} title={c}
          className={`swatch${lg ? ' lg' : ''}${selected === c ? ' sel' : ''}`}
          style={{ background: COLORS[c] || '#ccc' }}
          onClick={(e) => { e.stopPropagation(); onSelect && onSelect(c); }} />
      ))}
      {extra > 0 && <span className="swatch more">+{extra}</span>}
    </div>
  );
}

/* ---------- Points display ---------- */
function Price({ points, size = 16 }) {
  return (
    <span className="pprice" style={{ fontSize: size }}>
      <span className="mono-num">{points} pts</span>
      <span className="usd">(${points})</span>
    </span>
  );
}

function PointsPill() {
  const { user } = useContext(AppCtx);
  const remaining = user.pointsTotal - user.pointsUsed;
  const pct = Math.max(0, Math.min(100, (remaining / user.pointsTotal) * 100));
  return (
    <div className="pts-pill" title="Your annual clothing allowance">
      <Icon name="coins" size={16} style={{ color: 'var(--teal-600)' }} />
      <div className="pts-val"><b>{remaining}</b> <span>/ {user.pointsTotal} pts</span></div>
      <div className="pts-meter"><i style={{ width: pct + '%' }} /></div>
    </div>
  );
}

/* ---------- Product card ---------- */
function ProductCard({ product }) {
  const { navigate } = useContext(AppCtx);
  const [color, setColor] = useState(product.colors[0]);
  return (
    <div className="pcard" onClick={() => navigate('product', { id: product.id, color })}>
      <Garment product={product} color={color} />
      <div className="pcard-body">
        <div className="pbrand">{product.brand} · {product.sku}</div>
        <div className="pname">{product.name}</div>
        <Swatches colors={product.colors} selected={color} onSelect={setColor} max={6} />
        <Price points={product.price} />
      </div>
    </div>
  );
}

/* ---------- Storefront header ---------- */
function StoreHeader() {
  const { navigate, route, cart, user, logout } = useContext(AppCtx);
  const [menu, setMenu] = useState(false);
  const cartCount = cart.reduce((n, i) => n + i.qty, 0);
  const cats = CATEGORIES.filter(c => user.categories.includes(c.id));
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 50, background: 'rgba(255,255,255,.88)', backdropFilter: 'blur(10px)', borderBottom: '1px solid var(--line)' }}>
      <div className="wrap row" style={{ height: 70, gap: 28 }}>
        <div style={{ cursor: 'pointer' }} onClick={() => navigate('home')}><Logo size={32} /></div>
        <nav className="row" style={{ gap: 4, marginLeft: 6 }}>
          <NavLink label="Home" active={route.name === 'home'} onClick={() => navigate('home')} />
          {cats.map(c => (
            <NavLink key={c.id} label={c.short} active={route.name === 'category' && route.params.cat === c.id} onClick={() => navigate('category', { cat: c.id })} />
          ))}
        </nav>
        <div className="grow" />
        <PointsPill />
        <button className="btn btn-icon btn-ghost" style={{ position: 'relative' }} onClick={() => navigate('cart')} title="Cart">
          <Icon name="cart" size={19} />
          {cartCount > 0 && <span style={{ position: 'absolute', top: -5, right: -5, minWidth: 18, height: 18, padding: '0 5px', borderRadius: 99, background: 'var(--teal-600)', color: '#fff', fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-display)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{cartCount}</span>}
        </button>
        <div style={{ position: 'relative' }}>
          <button className="btn btn-icon btn-ghost row" style={{ gap: 7, paddingRight: 10 }} onClick={() => setMenu(m => !m)}>
            <span style={{ width: 26, height: 26, borderRadius: '50%', background: 'var(--teal-600)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12 }}>{user.first[0]}{user.name.split(' ')[1][0]}</span>
            <Icon name="chevronDown" size={15} />
          </button>
          {menu && (
            <>
              <div style={{ position: 'fixed', inset: 0, zIndex: 60 }} onClick={() => setMenu(false)} />
              <div className="card fade-up" style={{ position: 'absolute', right: 0, top: 46, width: 232, zIndex: 70, boxShadow: 'var(--shadow-lg)', padding: 6 }}>
                <div style={{ padding: '10px 12px' }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700 }}>{user.name}</div>
                  <div className="muted" style={{ fontSize: 12.5 }}>{user.role}</div>
                </div>
                <div className="divider" style={{ margin: '4px 0' }} />
                <MenuItem icon="user" label="My Account" onClick={() => { setMenu(false); navigate('account'); }} />
                <MenuItem icon="receipt" label="Order History" onClick={() => { setMenu(false); navigate('account'); }} />
                <MenuItem icon="shield" label="Admin Dashboard" onClick={() => { setMenu(false); navigate('admin'); }} />
                <div className="divider" style={{ margin: '4px 0' }} />
                <MenuItem icon="logout" label="Sign out" onClick={() => { setMenu(false); logout(); }} />
              </div>
            </>
          )}
        </div>
      </div>
    </header>
  );
}
function NavLink({ label, active, onClick }) {
  return (
    <button onClick={onClick} style={{ background: active ? 'var(--teal-50)' : 'transparent', color: active ? 'var(--teal-700)' : 'var(--ink-2)', border: 'none', padding: '8px 13px', borderRadius: 9, fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14, transition: 'background .15s, color .15s' }}>{label}</button>
  );
}
function MenuItem({ icon, label, onClick }) {
  return (
    <button onClick={onClick} className="row" style={{ width: '100%', gap: 11, padding: '9px 12px', background: 'transparent', border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 500, color: 'var(--ink-2)', textAlign: 'left' }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-2)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
      <Icon name={icon} size={17} style={{ color: 'var(--muted)' }} /> {label}
    </button>
  );
}

/* ---------- Footer ---------- */
function StoreFooter() {
  const { navigate } = useContext(AppCtx);
  return (
    <footer style={{ background: 'var(--teal-700)', color: 'rgba(255,255,255,.86)', marginTop: 64 }}>
      <div className="wrap" style={{ padding: '40px 28px 30px', display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr', gap: 40 }}>
        <div>
          <a href="https://evansequipment.com/" target="_blank" rel="noopener noreferrer" style={{ display: 'inline-block' }}><Logo size={32} light /></a>
          <p style={{ marginTop: 14, fontSize: 13.5, maxWidth: 320, color: 'rgba(255,255,255,.66)' }}>The private employee apparel store for Evans Equipment &amp; Environmental. Authorized personnel only.</p>
          <div className="row" style={{ gap: 9, marginTop: 18 }}>
            <span style={{ width: 34, height: 34, borderRadius: 9, background: 'rgba(255,255,255,.10)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name="spark" size={18} style={{ color: 'rgba(255,255,255,.85)' }} />
            </span>
            <span style={{ lineHeight: 1.3 }}>
              <span style={{ display: 'block', fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,.5)' }}>Apparel &amp; embroidery by</span>
              <a href="https://talkntshirts.com/" target="_blank" rel="noopener noreferrer" style={{ display: 'block', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5, color: '#fff', textDecoration: 'none', cursor: 'pointer' }} onMouseEnter={e => e.currentTarget.style.textDecoration = 'underline'} onMouseLeave={e => e.currentTarget.style.textDecoration = 'none'}>Talk&rsquo;N T-Shirts</a>
            </span>
          </div>
        </div>
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12, letterSpacing: '.12em', textTransform: 'uppercase', marginBottom: 12, color: 'rgba(255,255,255,.6)' }}>Shop</div>
          {CATEGORIES.map(c => <div key={c.id} style={{ fontSize: 14, padding: '5px 0', cursor: 'pointer' }} onClick={() => navigate('category', { cat: c.id })}>{c.label}</div>)}
        </div>
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12, letterSpacing: '.12em', textTransform: 'uppercase', marginBottom: 12, color: 'rgba(255,255,255,.6)' }}>Account</div>
          <div style={{ fontSize: 14, padding: '5px 0', cursor: 'pointer' }} onClick={() => navigate('account')}>My Account</div>
          <div style={{ fontSize: 14, padding: '5px 0', cursor: 'pointer' }} onClick={() => navigate('account')}>Points &amp; Orders</div>
          <div style={{ fontSize: 14, padding: '5px 0', cursor: 'pointer' }} onClick={() => navigate('admin')}>Admin Dashboard</div>
        </div>
      </div>
      <div style={{ borderTop: '1px solid rgba(255,255,255,.14)' }}>
        <div className="wrap row" style={{ padding: '16px 28px', fontSize: 12.5, color: 'rgba(255,255,255,.6)', justifyContent: 'space-between' }}>
          <span>© 2026 <a href="https://evansequipment.com/" target="_blank" rel="noopener noreferrer" style={{ color: 'inherit', textDecoration: 'underline', textUnderlineOffset: 2 }}>Evans Equipment &amp; Environmental</a></span>
          <span>Apparel by <a href="https://talkntshirts.com/" target="_blank" rel="noopener noreferrer" style={{ color: 'rgba(255,255,255,.82)', textDecoration: 'underline', textUnderlineOffset: 2 }}>Talk&rsquo;N T-Shirts</a> · Site by <a href="https://digitaldp.digitaldpsite.com/" target="_blank" rel="noopener noreferrer" style={{ color: 'rgba(255,255,255,.82)', textDecoration: 'underline', textUnderlineOffset: 2 }}>Digital DP LLC</a></span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { AppCtx, Icon, Logo, Garment, Swatches, Price, PointsPill, ProductCard, StoreHeader, NavLink, MenuItem, StoreFooter });
