/* ============================================================
   Store screens — Part 1: Login, Home, Category, Product
   ============================================================ */

/* ---------------- LOGIN ---------------- */
function LoginScreen() {
  const { login } = useContext(AppCtx);
  const [email, setEmail] = useState('m.hebert@evansequip.com');
  const [pw, setPw] = useState('••••••••');
  return (
    <div style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: '1.05fr .95fr' }}>
      {/* Left brand panel */}
      <div style={{ background: 'linear-gradient(160deg, var(--teal-700), var(--teal-800) 70%)', color: '#fff', padding: '52px 56px', display: 'flex', flexDirection: 'column', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', right: -120, top: -90, width: 420, height: 420, borderRadius: '50%', border: '1px solid rgba(255,255,255,.10)' }} />
        <div style={{ position: 'absolute', right: -40, bottom: -140, width: 360, height: 360, borderRadius: '50%', border: '1px solid rgba(255,255,255,.08)' }} />
        <Logo size={38} light />
        <div className="grow" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', maxWidth: 440 }}>
          <div className="badge" style={{ background: 'rgba(255,255,255,.14)', color: '#fff', alignSelf: 'flex-start', marginBottom: 22 }}>Employees only</div>
          <h1 style={{ color: '#fff', fontSize: 42, lineHeight: 1.05, fontWeight: 800, letterSpacing: '-.02em' }}>Your company apparel store.</h1>
          <p style={{ marginTop: 18, fontSize: 16.5, color: 'rgba(255,255,255,.78)', lineHeight: 1.55 }}>Sign in to browse Evans-branded gear and spend your annual <b style={{ color: '#fff' }}>$300 clothing allowance</b> — no card required.</p>
          <div className="row" style={{ gap: 26, marginTop: 34 }}>
            {[['coins','300 pts / year'],['shield','Private &amp; secure'],['truck','Delivered to you']].map(([ic, t]) => (
              <div key={t} className="row" style={{ gap: 9 }}>
                <Icon name={ic} size={18} style={{ color: 'rgba(255,255,255,.85)' }} />
                <span style={{ fontSize: 13.5, color: 'rgba(255,255,255,.85)' }} dangerouslySetInnerHTML={{ __html: t }} />
              </div>
            ))}
          </div>
        </div>
        <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,.5)' }}>© 2026 Evans Equipment &amp; Environmental</div>
      </div>
      {/* Right form */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40, background: 'var(--surface)' }}>
        <div style={{ width: '100%', maxWidth: 380 }} className="fade-up">
          <h2 style={{ fontSize: 27 }}>Sign in</h2>
          <p className="muted" style={{ marginTop: 8, marginBottom: 28, fontSize: 14.5 }}>Use the account issued by your HR administrator.</p>
          <form onSubmit={(e) => { e.preventDefault(); login(); }} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div className="field">
              <label>Work email</label>
              <input className="input" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@evansequip.com" />
            </div>
            <div className="field">
              <div className="row" style={{ justifyContent: 'space-between' }}>
                <label>Password</label>
                <span className="link" style={{ fontSize: 12.5 }}>Forgot password?</span>
              </div>
              <input className="input" type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="••••••••" />
            </div>
            <label className="row" style={{ gap: 9, fontSize: 13.5, color: 'var(--ink-2)', cursor: 'pointer' }}>
              <input type="checkbox" defaultChecked style={{ width: 16, height: 16, accentColor: 'var(--teal-600)' }} /> Keep me signed in on this device
            </label>
            <button className="btn btn-primary btn-lg btn-block" type="submit" style={{ marginTop: 4 }}>Sign in <Icon name="arrowRight" size={17} /></button>
          </form>
          <div className="divider" style={{ margin: '26px 0 18px' }} />
          <p className="muted center" style={{ fontSize: 12.5 }}>Need access? Contact your HR administrator to have an account created.</p>
        </div>
      </div>
    </div>
  );
}

/* ---------------- HOME ---------------- */
function HomeScreen() {
  const { navigate, user } = useContext(AppCtx);
  const remaining = user.pointsTotal - user.pointsUsed;
  const cats = CATEGORIES.filter(c => user.categories.includes(c.id));
  const featured = PRODUCTS.filter(p => user.categories.includes(p.cat)).slice(0, 4);
  return (
    <div className="fade-up">
      {/* Welcome / allowance band */}
      <div style={{ background: 'linear-gradient(165deg, var(--teal-700), var(--teal-800))', color: '#fff' }}>
        <div className="wrap" style={{ padding: '40px 28px 120px' }}>
          <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 20 }}>
            <div>
              <div className="eyebrow" style={{ color: 'rgba(255,255,255,.7)' }}>Welcome back</div>
              <h1 style={{ color: '#fff', fontSize: 34, marginTop: 8 }}>Hey {user.first} 👋</h1>
              <p style={{ color: 'rgba(255,255,255,.78)', marginTop: 8, fontSize: 15.5 }}>You have <b style={{ color: '#fff' }}>{remaining} points</b> left to spend this year. Pick out your gear below.</p>
            </div>
          </div>
        </div>
      </div>
      <div className="wrap" style={{ marginTop: -86, position: 'relative', zIndex: 2 }}>
        {/* Allowance card */}
        <div className="card" style={{ boxShadow: 'var(--shadow)', padding: 22, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr auto', gap: 0, alignItems: 'center' }}>
          <AllowanceStat label="Annual allowance" value={`${user.pointsTotal} pts`} sub="$300 value" />
          <AllowanceStat label="Spent so far" value={`${user.pointsUsed} pts`} sub={`$${user.pointsUsed}`} divider />
          <AllowanceStat label="Remaining" value={`${remaining} pts`} sub={`$${remaining}`} highlight divider />
          <div style={{ paddingLeft: 22 }}>
            <button className="btn btn-primary" onClick={() => navigate('account')}>View my account</button>
          </div>
        </div>

        {/* Category tiles */}
        <div style={{ marginTop: 40 }}>
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 18 }}>
            <h2 style={{ fontSize: 22 }}>Shop by category</h2>
            <span className="muted" style={{ fontSize: 13 }}>Showing categories for your role · {user.role}</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cats.length}, 1fr)`, gap: 20 }}>
            {cats.map((c, i) => <CategoryTile key={c.id} cat={c} i={i} />)}
          </div>
        </div>

        {/* Featured */}
        <div style={{ marginTop: 48 }}>
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 18 }}>
            <h2 style={{ fontSize: 22 }}>Popular this season</h2>
            <span className="link" onClick={() => navigate('category', { cat: cats[0].id })}>Browse all <Icon name="chevron" size={14} style={{ verticalAlign: '-2px' }} /></span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }}>
            {featured.map(p => <ProductCard key={p.id} product={p} />)}
          </div>
        </div>
      </div>
    </div>
  );
}
function AllowanceStat({ label, value, sub, highlight, divider }) {
  return (
    <div className="row" style={{ gap: 0 }}>
      {divider && <div style={{ width: 1, alignSelf: 'stretch', background: 'var(--line)', marginRight: 22 }} />}
      <div>
        <div className="eyebrow" style={{ color: 'var(--muted)' }}>{label}</div>
        <div className="mono-num" style={{ fontSize: 26, fontWeight: 800, marginTop: 5, color: highlight ? 'var(--teal-600)' : 'var(--ink)' }}>{value}</div>
        <div className="muted" style={{ fontSize: 12.5 }}>{sub}</div>
      </div>
    </div>
  );
}
function CategoryTile({ cat, i }) {
  const { navigate } = useContext(AppCtx);
  const sample = PRODUCTS.filter(p => p.cat === cat.id);
  const tints = ['var(--teal-600)', 'var(--forest)', 'var(--teal-800)'];
  return (
    <div onClick={() => navigate('category', { cat: cat.id })}
      style={{ borderRadius: 'var(--radius-lg)', overflow: 'hidden', cursor: 'pointer', border: '1px solid var(--line)', background: 'var(--surface)', transition: 'box-shadow .2s, transform .2s' }}
      onMouseEnter={e => { e.currentTarget.style.boxShadow = 'var(--shadow-lg)'; e.currentTarget.style.transform = 'translateY(-4px)'; }}
      onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
      <div style={{ position: 'relative', background: tints[i % 3], padding: '26px 24px 0', height: 200, overflow: 'hidden' }}>
        <div style={{ position: 'relative', zIndex: 2 }}>
          <div className="badge" style={{ background: 'rgba(255,255,255,.16)', color: '#fff' }}>{sample.length} styles</div>
          <h3 style={{ color: '#fff', fontSize: 23, marginTop: 12, maxWidth: 200 }}>{cat.label}</h3>
        </div>
        <div style={{ position: 'absolute', right: 14, bottom: -30, width: 150, opacity: .96 }} dangerouslySetInnerHTML={{ __html: garmentSVG(cat.kind, 'rgba(255,255,255,.92)') }} />
        <div style={{ position: 'absolute', left: -50, bottom: -70, width: 200, height: 200, borderRadius: '50%', border: '1px solid rgba(255,255,255,.12)' }} />
      </div>
      <div className="row" style={{ justifyContent: 'space-between', padding: '15px 20px' }}>
        <span className="muted" style={{ fontSize: 13.5 }}>{cat.blurb}</span>
        <span style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--teal-50)', color: 'var(--teal-700)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chevron" size={16} /></span>
      </div>
    </div>
  );
}

/* ---------------- CATEGORY LISTING ---------------- */
function CategoryScreen({ cat }) {
  const { navigate } = useContext(AppCtx);
  const category = CATEGORIES.find(c => c.id === cat);
  const all = PRODUCTS.filter(p => p.cat === cat);
  const [sort, setSort] = useState('featured');
  const [filter, setFilter] = useState('all');
  let list = [...all];
  if (filter === 'fr') list = list.filter(p => p.fr);
  if (filter === 'jackets') list = list.filter(p => p.kind === 'jacket');
  if (sort === 'low') list.sort((a, b) => a.price - b.price);
  if (sort === 'high') list.sort((a, b) => b.price - a.price);
  return (
    <div className="wrap fade-up" style={{ paddingTop: 28 }}>
      <div className="row muted" style={{ gap: 6, fontSize: 13, marginBottom: 14 }}>
        <span className="link" onClick={() => navigate('home')}>Home</span>
        <Icon name="chevron" size={13} /> <span>{category.label}</span>
      </div>
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <h1 style={{ fontSize: 30 }}>{category.label}</h1>
          <p className="muted" style={{ marginTop: 6 }}>{all.length} styles · embroidered or printed with the Evans logo</p>
        </div>
        <div className="row" style={{ gap: 10 }}>
          {category.id === 'tech' && (
            <select className="select" style={{ width: 'auto' }} value={filter} onChange={e => setFilter(e.target.value)}>
              <option value="all">All gear</option>
              <option value="fr">FR-rated only</option>
              <option value="jackets">Outerwear</option>
            </select>
          )}
          <select className="select" style={{ width: 'auto' }} value={sort} onChange={e => setSort(e.target.value)}>
            <option value="featured">Sort: Featured</option>
            <option value="low">Price: Low to High</option>
            <option value="high">Price: High to Low</option>
          </select>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20, marginTop: 26 }}>
        {list.map(p => <ProductCard key={p.id} product={p} />)}
      </div>
    </div>
  );
}

/* ---------------- PRODUCT DETAIL ---------------- */
function ProductScreen({ id, color: initColor }) {
  const { navigate, addToCart, user } = useContext(AppCtx);
  const product = PRODUCTS.find(p => p.id === id);
  const [color, setColor] = useState(initColor || product.colors[0]);
  const [size, setSize] = useState('L');
  const [qty, setQty] = useState(1);
  const [added, setAdded] = useState(false);
  const category = CATEGORIES.find(c => c.id === product.cat);
  const remaining = user.pointsTotal - user.pointsUsed;

  const doAdd = () => {
    addToCart(product, color, size, qty);
    setAdded(true);
    setTimeout(() => setAdded(false), 1800);
  };
  return (
    <div className="wrap fade-up" style={{ paddingTop: 28 }}>
      <div className="row muted" style={{ gap: 6, fontSize: 13, marginBottom: 18 }}>
        <span className="link" onClick={() => navigate('home')}>Home</span>
        <Icon name="chevron" size={13} />
        <span className="link" onClick={() => navigate('category', { cat: product.cat })}>{category.label}</span>
        <Icon name="chevron" size={13} /> <span>{product.name}</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, alignItems: 'start' }}>
        {/* Gallery */}
        <div>
          <div className="card" style={{ padding: 28, background: 'var(--surface)' }}>
            <Garment product={product} color={color} tag={false} />
          </div>
          <div className="row" style={{ gap: 10, marginTop: 12 }}>
            {product.colors.slice(0, 5).map(c => (
              <button key={c} onClick={() => setColor(c)} className="card" style={{ padding: 8, borderColor: color === c ? 'var(--teal-600)' : 'var(--line)', borderWidth: color === c ? 2 : 1, width: 76, cursor: 'pointer', background: '#fff' }}>
                <div dangerouslySetInnerHTML={{ __html: garmentSVG(product.kind, COLORS[c]) }} style={{ width: '100%' }} />
              </button>
            ))}
          </div>
        </div>
        {/* Info */}
        <div>
          <div className="row" style={{ gap: 8, marginBottom: 10 }}>
            <span className="badge badge-gray">{product.brand}</span>
            {product.fr && <span className="badge badge-amber">FR · NFPA 2112</span>}
          </div>
          <h1 style={{ fontSize: 30, lineHeight: 1.12 }}>{product.name}</h1>
          <div className="muted" style={{ marginTop: 8, fontSize: 13.5 }}>Style {product.sku}</div>
          <div className="row" style={{ gap: 10, alignItems: 'baseline', marginTop: 18 }}>
            <span className="mono-num" style={{ fontSize: 30, fontWeight: 800 }}>{product.price} pts</span>
            <span className="muted" style={{ fontSize: 15, fontWeight: 600 }}>(${product.price} value)</span>
          </div>
          <p style={{ marginTop: 18, color: 'var(--ink-2)', fontSize: 15, lineHeight: 1.6, maxWidth: 460 }}>{product.desc}</p>

          {/* Color */}
          <div style={{ marginTop: 26 }}>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 10 }}>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14 }}>Color</span>
              <span className="muted" style={{ fontSize: 13, textTransform: 'capitalize' }}>{color}</span>
            </div>
            <Swatches colors={product.colors} selected={color} onSelect={setColor} lg />
          </div>
          {/* Size */}
          <div style={{ marginTop: 24 }}>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 10 }}>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14 }}>Size</span>
              <span className="link" style={{ fontSize: 13 }}>Size guide</span>
            </div>
            <div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
              {SIZES.map(s => (
                <button key={s} onClick={() => setSize(s)} style={{ minWidth: 48, padding: '10px 0', borderRadius: 10, fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14, cursor: 'pointer', border: `1.5px solid ${size === s ? 'var(--teal-600)' : 'var(--line)'}`, background: size === s ? 'var(--teal-50)' : '#fff', color: size === s ? 'var(--teal-700)' : 'var(--ink-2)' }}>{s}</button>
              ))}
            </div>
          </div>
          {/* Qty + add */}
          <div className="row" style={{ gap: 14, marginTop: 28 }}>
            <div className="row" style={{ border: '1px solid var(--line)', borderRadius: 11, overflow: 'hidden' }}>
              <button className="btn btn-icon" style={{ borderRadius: 0 }} onClick={() => setQty(q => Math.max(1, q - 1))}><Icon name="minus" size={16} /></button>
              <span className="mono-num" style={{ width: 40, textAlign: 'center', fontWeight: 700 }}>{qty}</span>
              <button className="btn btn-icon" style={{ borderRadius: 0 }} onClick={() => setQty(q => q + 1)}><Icon name="plus" size={16} /></button>
            </div>
            <button className={`btn btn-lg grow ${added ? 'btn-soft' : 'btn-primary'}`} onClick={doAdd} style={{ transition: 'all .2s' }}>
              {added ? <><Icon name="check" size={18} /> Added to cart</> : <><Icon name="cart" size={18} /> Add to cart · {product.price * qty} pts</>}
            </button>
          </div>
          <div className="card" style={{ marginTop: 20, padding: '14px 16px', background: 'var(--surface-2)', display: 'flex', gap: 12, alignItems: 'center' }}>
            <Icon name="coins" size={18} style={{ color: 'var(--teal-600)' }} />
            <span style={{ fontSize: 13.5, color: 'var(--ink-2)' }}>This order uses <b>{product.price * qty} of your {remaining} remaining points.</b> No payment needed when you're within your allowance.</span>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen, HomeScreen, AllowanceStat, CategoryTile, CategoryScreen, ProductScreen });
