/* ============================================================
   Store screens — Part 2: Cart, Checkout, Confirmation, Account
   ============================================================ */

/* ---------------- CART ---------------- */
function CartScreen() {
  const { cart, navigate, updateQty, removeItem, user } = useContext(AppCtx);
  const subtotal = cart.reduce((n, i) => n + i.product.price * i.qty, 0);
  const remaining = user.pointsTotal - user.pointsUsed;
  const over = Math.max(0, subtotal - remaining);

  if (cart.length === 0) {
    return (
      <div className="wrap fade-up" style={{ paddingTop: 70, textAlign: 'center' }}>
        <div style={{ width: 76, height: 76, borderRadius: '50%', background: 'var(--teal-50)', color: 'var(--teal-600)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}><Icon name="cart" size={32} /></div>
        <h1 style={{ fontSize: 26 }}>Your cart is empty</h1>
        <p className="muted" style={{ marginTop: 8 }}>Browse the catalog and add some gear to get started.</p>
        <button className="btn btn-primary btn-lg" style={{ marginTop: 22 }} onClick={() => navigate('home')}>Start shopping</button>
      </div>
    );
  }
  return (
    <div className="wrap fade-up" style={{ paddingTop: 28 }}>
      <h1 style={{ fontSize: 30 }}>Your cart</h1>
      <p className="muted" style={{ marginTop: 6 }}>{cart.reduce((n, i) => n + i.qty, 0)} items</p>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 28, marginTop: 24, alignItems: 'start' }}>
        <div className="card" style={{ overflow: 'hidden' }}>
          {cart.map((item, idx) => (
            <CartRow key={item.key} item={item} last={idx === cart.length - 1} updateQty={updateQty} removeItem={removeItem} />
          ))}
        </div>
        <OrderSummary subtotal={subtotal} remaining={remaining} over={over} cta="Continue to checkout" onCta={() => navigate('checkout')} onBack={() => navigate('home')} />
      </div>
    </div>
  );
}
function CartRow({ item, last, updateQty, removeItem }) {
  const { navigate } = useContext(AppCtx);
  const p = item.product;
  return (
    <div className="row" style={{ gap: 18, padding: 18, borderBottom: last ? 'none' : '1px solid var(--line-2)', alignItems: 'flex-start' }}>
      <div style={{ width: 92, flexShrink: 0, cursor: 'pointer' }} onClick={() => navigate('product', { id: p.id, color: item.color })}>
        <Garment product={p} color={item.color} tag={false} logo={false} />
      </div>
      <div className="grow">
        <div className="pbrand" style={{ fontSize: 12, color: 'var(--faint)' }}>{p.brand} · {p.sku}</div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 15.5, marginTop: 2, cursor: 'pointer' }} onClick={() => navigate('product', { id: p.id, color: item.color })}>{p.name}</div>
        <div className="row" style={{ gap: 14, marginTop: 8 }}>
          <span className="row" style={{ gap: 6, fontSize: 13, color: 'var(--muted)' }}><span className="swatch" style={{ width: 14, height: 14, background: COLORS[item.color] }} /> <span style={{ textTransform: 'capitalize' }}>{item.color}</span></span>
          <span style={{ fontSize: 13, color: 'var(--muted)' }}>Size {item.size}</span>
        </div>
        <button className="row link" style={{ gap: 5, fontSize: 12.5, marginTop: 12, background: 'none', border: 'none', padding: 0 }} onClick={() => removeItem(item.key)}><Icon name="trash" size={14} /> Remove</button>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className="row" style={{ border: '1px solid var(--line)', borderRadius: 9, overflow: 'hidden', marginBottom: 10 }}>
          <button className="btn btn-icon btn-sm" style={{ borderRadius: 0 }} onClick={() => updateQty(item.key, -1)}><Icon name="minus" size={14} /></button>
          <span className="mono-num" style={{ width: 32, textAlign: 'center', fontWeight: 700, fontSize: 14 }}>{item.qty}</span>
          <button className="btn btn-icon btn-sm" style={{ borderRadius: 0 }} onClick={() => updateQty(item.key, 1)}><Icon name="plus" size={14} /></button>
        </div>
        <div className="mono-num" style={{ fontWeight: 800, fontSize: 16 }}>{p.price * item.qty} pts</div>
        <div className="muted" style={{ fontSize: 12 }}>${p.price * item.qty}</div>
      </div>
    </div>
  );
}

/* ---------------- ORDER SUMMARY (shared) ---------------- */
function OrderSummary({ subtotal, remaining, over, cta, onCta, onBack, ctaDisabled }) {
  const after = remaining - subtotal;
  return (
    <div className="card" style={{ padding: 22, position: 'sticky', top: 90 }}>
      <h3 style={{ fontSize: 17, marginBottom: 16 }}>Order summary</h3>
      <SummaryLine label="Items subtotal" value={`${subtotal} pts`} />
      <SummaryLine label="Delivery" value="Free" sub />
      <div className="divider" style={{ margin: '14px 0' }} />
      <SummaryLine label="Your balance" value={`${remaining} pts`} />
      <SummaryLine label="This order" value={`– ${subtotal} pts`} />
      <div className="divider" style={{ margin: '14px 0' }} />
      {over > 0 ? (
        <>
          <div className="row" style={{ justifyContent: 'space-between' }}>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700 }}>Balance after</span>
            <span className="mono-num" style={{ fontWeight: 800, color: 'var(--danger)' }}>–{Math.abs(after)} pts</span>
          </div>
          <div className="card" style={{ marginTop: 16, padding: '12px 14px', background: 'var(--amber-bg)', borderColor: 'var(--amber-line)', display: 'flex', gap: 11 }}>
            <Icon name="alert" size={18} style={{ color: 'var(--amber)', flexShrink: 0, marginTop: 1 }} />
            <span style={{ fontSize: 12.5, color: '#7a5210', lineHeight: 1.5 }}>This order exceeds your allowance by <b>{over} pts (${over})</b>. It can still go through — the overage is logged and your HR admin is notified for billing.</span>
          </div>
        </>
      ) : (
        <div className="row" style={{ justifyContent: 'space-between' }}>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700 }}>Balance after</span>
          <span className="mono-num" style={{ fontWeight: 800, color: 'var(--teal-700)' }}>{after} pts</span>
        </div>
      )}
      <button className="btn btn-primary btn-lg btn-block" style={{ marginTop: 20 }} onClick={onCta} disabled={ctaDisabled}>{cta} <Icon name="arrowRight" size={17} /></button>
      {onBack && <button className="btn btn-ghost btn-block" style={{ marginTop: 10 }} onClick={onBack}>Keep shopping</button>}
      <div className="row" style={{ gap: 8, marginTop: 16, justifyContent: 'center', color: 'var(--muted)', fontSize: 12 }}>
        <Icon name="shield" size={14} /> Internal order · no card required
      </div>
    </div>
  );
}
function SummaryLine({ label, value, sub }) {
  return (
    <div className="row" style={{ justifyContent: 'space-between', padding: '5px 0' }}>
      <span className="muted" style={{ fontSize: 14 }}>{label}</span>
      <span className="mono-num" style={{ fontWeight: 600, fontSize: 14, color: sub ? 'var(--ok)' : 'var(--ink)' }}>{value}</span>
    </div>
  );
}

/* ---------------- CHECKOUT ---------------- */
function CheckoutScreen() {
  const { cart, navigate, user, placeOrder } = useContext(AppCtx);
  const subtotal = cart.reduce((n, i) => n + i.product.price * i.qty, 0);
  const remaining = user.pointsTotal - user.pointsUsed;
  const over = Math.max(0, subtotal - remaining);
  const [method, setMethod] = useState('inperson');
  const [loc, setLoc] = useState('hq');
  const [ack, setAck] = useState(false);

  const canPlace = method === 'inperson' || (method === 'ship' && loc);
  return (
    <div className="wrap fade-up" style={{ paddingTop: 28 }}>
      <div className="row link muted" style={{ gap: 5, fontSize: 13, marginBottom: 14 }} onClick={() => navigate('cart')}><Icon name="chevronLeft" size={15} /> Back to cart</div>
      <h1 style={{ fontSize: 30 }}>Checkout</h1>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 28, marginTop: 24, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* Delivery method */}
          <div className="card card-pad">
            <div className="row" style={{ gap: 10, marginBottom: 16 }}>
              <StepDot n="1" /> <h3 style={{ fontSize: 17 }}>How should we get this to you?</h3>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <RadioCard icon="truck" selected={method === 'inperson'} onClick={() => setMethod('inperson')}
                title="In-person delivery" desc="We hand-deliver your order to your job site or office. Most orders arrive within a week." badge="Recommended" />
              <RadioCard icon="box" selected={method === 'ship'} onClick={() => setMethod('ship')}
                title="Ship to a company location" desc="Pick up at one of our three locations." />
              {method === 'ship' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10, paddingLeft: 4, marginTop: 2 }}>
                  {LOCATIONS.map(l => (
                    <button key={l.id} onClick={() => setLoc(l.id)} className="row" style={{ textAlign: 'left', gap: 12, padding: '12px 14px', borderRadius: 11, cursor: 'pointer', border: `1.5px solid ${loc === l.id ? 'var(--teal-600)' : 'var(--line)'}`, background: loc === l.id ? 'var(--teal-50)' : '#fff' }}>
                      <Icon name="pin" size={17} style={{ color: loc === l.id ? 'var(--teal-600)' : 'var(--muted)' }} />
                      <span className="grow"><b style={{ fontFamily: 'var(--font-display)', fontSize: 14 }}>{l.name}</b><br /><span className="muted" style={{ fontSize: 12.5 }}>{l.addr}</span></span>
                      {loc === l.id && <Icon name="checkCircle" size={18} style={{ color: 'var(--teal-600)' }} />}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
          {/* Recipient */}
          <div className="card card-pad">
            <div className="row" style={{ gap: 10, marginBottom: 16 }}>
              <StepDot n="2" /> <h3 style={{ fontSize: 17 }}>Recipient</h3>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <ReadField label="Employee" value={user.name} />
              <ReadField label="Employee ID" value={user.empId} />
              <ReadField label="Department / role" value={user.role} />
              <ReadField label="Contact email" value={user.email} />
            </div>
            <div className="field" style={{ marginTop: 14 }}>
              <label>Order note <span className="muted" style={{ fontWeight: 400 }}>(optional)</span></label>
              <input className="input" placeholder="e.g. Need by the 20th for the Broussard job" />
            </div>
          </div>
          {/* Overage acknowledgement */}
          {over > 0 && (
            <div className="card card-pad" style={{ background: 'var(--amber-bg)', borderColor: 'var(--amber-line)' }}>
              <div className="row" style={{ gap: 12, alignItems: 'flex-start' }}>
                <Icon name="alert" size={22} style={{ color: 'var(--amber)', flexShrink: 0 }} />
                <div>
                  <h3 style={{ fontSize: 16, color: '#7a5210' }}>This order exceeds your allowance</h3>
                  <p style={{ fontSize: 13.5, color: '#7a5210', marginTop: 6, lineHeight: 1.55 }}>You're <b>{over} points (${over})</b> over your remaining balance. Your order will still be placed — the overage is recorded and your HR administrator will reach out about the ${over} balance.</p>
                  <label className="row" style={{ gap: 9, marginTop: 14, fontSize: 13.5, color: '#7a5210', cursor: 'pointer', fontWeight: 600 }}>
                    <input type="checkbox" checked={ack} onChange={e => setAck(e.target.checked)} style={{ width: 16, height: 16, accentColor: 'var(--amber)' }} />
                    I understand I may be billed ${over} for the overage.
                  </label>
                </div>
              </div>
            </div>
          )}
        </div>
        <OrderSummary subtotal={subtotal} remaining={remaining} over={over}
          cta="Place order" ctaDisabled={!canPlace || (over > 0 && !ack)}
          onCta={() => placeOrder({ method, loc, subtotal, over })} />
      </div>
    </div>
  );
}
function StepDot({ n }) {
  return <span style={{ width: 26, height: 26, borderRadius: '50%', background: 'var(--ink)', color: '#fff', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{n}</span>;
}
function RadioCard({ icon, title, desc, badge, selected, onClick }) {
  return (
    <button onClick={onClick} className="row" style={{ textAlign: 'left', gap: 14, padding: '16px 18px', borderRadius: 13, cursor: 'pointer', border: `1.5px solid ${selected ? 'var(--teal-600)' : 'var(--line)'}`, background: selected ? 'var(--teal-50)' : '#fff', alignItems: 'flex-start' }}>
      <span style={{ width: 40, height: 40, borderRadius: 10, background: selected ? 'var(--teal-600)' : 'var(--surface-2)', color: selected ? '#fff' : 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={icon} size={20} /></span>
      <span className="grow col" style={{ gap: 3 }}>
        <span className="row" style={{ gap: 8 }}>
          <b style={{ fontFamily: 'var(--font-display)', fontSize: 15 }}>{title}</b>
          {badge && <span className="badge badge-teal">{badge}</span>}
        </span>
        <span className="muted" style={{ fontSize: 13 }}>{desc}</span>
      </span>
      <span style={{ width: 20, height: 20, borderRadius: '50%', border: `2px solid ${selected ? 'var(--teal-600)' : 'var(--line)'}`, flexShrink: 0, marginTop: 2, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{selected && <span style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--teal-600)' }} />}</span>
    </button>
  );
}
function ReadField({ label, value }) {
  return (
    <div>
      <div className="muted" style={{ fontSize: 12, fontFamily: 'var(--font-display)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.05em' }}>{label}</div>
      <div style={{ fontSize: 14.5, marginTop: 4, fontWeight: 500 }}>{value}</div>
    </div>
  );
}

/* ---------------- CONFIRMATION ---------------- */
function ConfirmationScreen({ order }) {
  const { navigate } = useContext(AppCtx);
  const loc = LOCATIONS.find(l => l.id === order.loc);
  return (
    <div className="wrap fade-up" style={{ paddingTop: 50, maxWidth: 640 }}>
      <div className="center">
        <div style={{ width: 78, height: 78, borderRadius: '50%', background: 'var(--ok-bg)', color: 'var(--ok)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 22px' }}><Icon name="checkCircle" size={40} /></div>
        <h1 style={{ fontSize: 30 }}>Order placed</h1>
        <p className="muted" style={{ marginTop: 10, fontSize: 15.5 }}>Thanks! Your order <b className="mono-num" style={{ color: 'var(--ink)' }}>{order.id}</b> is confirmed. A copy was emailed to you.</p>
      </div>
      <div className="card card-pad" style={{ marginTop: 30 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
          <ReadField label="Items" value={`${order.count} item${order.count > 1 ? 's' : ''} · ${order.subtotal} pts`} />
          <ReadField label="Delivery" value={order.method === 'inperson' ? 'In-person delivery' : `Pickup · ${loc.name}`} />
          <ReadField label="Points used" value={`${order.subtotal} pts`} />
          <ReadField label="Remaining balance" value={`${order.remainingAfter} pts`} />
        </div>
        {order.over > 0 && (
          <div className="card" style={{ marginTop: 18, padding: '12px 14px', background: 'var(--amber-bg)', borderColor: 'var(--amber-line)', display: 'flex', gap: 11 }}>
            <Icon name="alert" size={18} style={{ color: 'var(--amber)', flexShrink: 0 }} />
            <span style={{ fontSize: 12.5, color: '#7a5210' }}>Overage of <b>${order.over}</b> logged. Your HR administrator has been notified and will follow up about billing.</span>
          </div>
        )}
      </div>
      <div className="card card-pad" style={{ marginTop: 16, display: 'flex', gap: 14, alignItems: 'center', background: 'var(--surface-2)' }}>
        <Icon name="truck" size={22} style={{ color: 'var(--teal-600)' }} />
        <span style={{ fontSize: 14, color: 'var(--ink-2)' }}>{order.method === 'inperson' ? 'We\'ll coordinate hand-delivery to your job site. Watch your email for scheduling.' : `Your order will be ready for pickup at ${loc.name} — ${loc.addr}.`}</span>
      </div>
      <div className="row" style={{ gap: 12, marginTop: 24, justifyContent: 'center' }}>
        <button className="btn btn-ghost btn-lg" onClick={() => navigate('account')}>View order history</button>
        <button className="btn btn-primary btn-lg" onClick={() => navigate('home')}>Continue shopping</button>
      </div>
    </div>
  );
}

/* ---------------- MY ACCOUNT ---------------- */
function AccountScreen() {
  const { user, navigate } = useContext(AppCtx);
  const remaining = user.pointsTotal - user.pointsUsed;
  const pct = (remaining / user.pointsTotal) * 100;
  const R = 64, C = 2 * Math.PI * R;
  return (
    <div className="wrap fade-up" style={{ paddingTop: 28 }}>
      <h1 style={{ fontSize: 30 }}>My account</h1>
      <p className="muted" style={{ marginTop: 6 }}>{user.name} · {user.email}</p>
      <div style={{ display: 'grid', gridTemplateColumns: '340px 1fr', gap: 24, marginTop: 24, alignItems: 'start' }}>
        {/* Points ring card */}
        <div className="card card-pad" style={{ textAlign: 'center' }}>
          <div className="eyebrow" style={{ color: 'var(--muted)' }}>Clothing allowance</div>
          <div style={{ position: 'relative', width: 170, height: 170, margin: '16px auto 8px' }}>
            <svg width="170" height="170" style={{ transform: 'rotate(-90deg)' }}>
              <circle cx="85" cy="85" r={R} fill="none" stroke="var(--line)" strokeWidth="14" />
              <circle cx="85" cy="85" r={R} fill="none" stroke="var(--teal-600)" strokeWidth="14" strokeLinecap="round" strokeDasharray={C} strokeDashoffset={C * (1 - pct / 100)} style={{ transition: 'stroke-dashoffset 1s' }} />
            </svg>
            <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
              <div className="mono-num" style={{ fontSize: 36, fontWeight: 800, lineHeight: 1 }}>{remaining}</div>
              <div className="muted" style={{ fontSize: 12.5 }}>of {user.pointsTotal} pts left</div>
            </div>
          </div>
          <div className="divider" style={{ margin: '16px 0' }} />
          <div className="row" style={{ justifyContent: 'space-between', fontSize: 13.5 }}><span className="muted">Spent this year</span><b className="mono-num">{user.pointsUsed} pts</b></div>
          <div className="row" style={{ justifyContent: 'space-between', fontSize: 13.5, marginTop: 8 }}><span className="muted">Resets on</span><b>{user.resetDate}</b></div>
          <button className="btn btn-soft btn-block" style={{ marginTop: 18 }} onClick={() => navigate('home')}>Spend my points</button>
        </div>
        {/* Right column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <div className="card">
            <div className="row card-pad" style={{ justifyContent: 'space-between', paddingBottom: 14 }}>
              <h3 style={{ fontSize: 17 }}>Order history</h3>
              <span className="muted" style={{ fontSize: 13 }}>{ORDER_HISTORY.length} orders</span>
            </div>
            <table className="tbl">
              <thead><tr><th>Order</th><th>Date</th><th>Items</th><th>Points</th><th>Status</th></tr></thead>
              <tbody>
                {ORDER_HISTORY.map(o => (
                  <tr key={o.id}>
                    <td className="mono-num" style={{ fontWeight: 600 }}>{o.id}</td>
                    <td className="muted">{o.date}</td>
                    <td>{o.items}</td>
                    <td className="mono-num" style={{ fontWeight: 600 }}>{o.points} pts</td>
                    <td><span className="badge badge-ok">{o.status}</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="card card-pad">
            <h3 style={{ fontSize: 17, marginBottom: 14 }}>Profile</h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <ReadField label="Full name" value={user.name} />
              <ReadField label="Employee ID" value={user.empId} />
              <ReadField label="Role" value={user.role} />
              <ReadField label="Email" value={user.email} />
            </div>
            <p className="muted" style={{ fontSize: 12.5, marginTop: 16 }}>Need to update your details or points balance? Contact your HR administrator.</p>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CartScreen, CartRow, OrderSummary, SummaryLine, CheckoutScreen, StepDot, RadioCard, ReadField, ConfirmationScreen, AccountScreen });
