/* ============================================================
   ACCOUNT / ORDER STATUS
   ============================================================ */
const STATUS_STEPS = ['Order Received', 'Confirmed', 'Processing', 'En Route', 'Delivered'];

function AccountPage() {
  const { orders, nav, wish, user, signOut } = useStore();
  const [tab, setTab] = useState('orders');
  const wishProducts = BB.products.filter(p => wish.includes(p.id));

  useEffect(() => { if (!user) nav('signin'); }, [user]);
  if (!user) return null;

  const initials = (user.firstName[0] + user.lastName[0]).toUpperCase();
  const fullName = `${user.firstName} ${user.lastName}`;

  return (
    <div className="container wide" style={{ padding: 'clamp(36px,5vw,64px) var(--gutter) clamp(64px,9vw,110px)' }}>
      <p className="eyebrow">My Account</p>
      <h1 style={{ fontSize: 'clamp(36px,5vw,60px)', margin: '12px 0 6px' }}>Welcome back, <em style={{ fontStyle: 'italic' }}>{user.firstName}.</em></h1>
      <p className="muted" style={{ marginBottom: 36 }}>Track your orders, manage saved pieces and update your details.</p>

      <div className="account-layout">
        <aside>
          <div style={{ background: 'var(--ivory)', borderRadius: 'var(--r-lg)', padding: 22, boxShadow: 'var(--shadow-sm)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, paddingBottom: 18, borderBottom: '1px solid var(--line)', marginBottom: 12 }}>
              <span style={{ width: 50, height: 50, borderRadius: 100, background: 'linear-gradient(135deg,var(--gold-deep),var(--blush))', color: '#fff', display: 'grid', placeItems: 'center', fontFamily: 'var(--serif)', fontSize: 20 }}>{initials}</span>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 500, lineHeight: 1.3 }}>{fullName}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.3 }}>{user.email}</div>
              </div>
            </div>
            {[['orders', 'My Orders', I.truck], ['wishlist', 'Wishlist', I.heart], ['details', 'Details', I.user]].map(([id, l, Ic]) => (
              <button key={id} onClick={() => setTab(id)} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', padding: '12px 14px', borderRadius: 'var(--r-md)', fontSize: 14.5, fontWeight: 500, background: tab === id ? 'var(--cream-deep)' : 'transparent', color: tab === id ? 'var(--ink)' : 'var(--ink-soft)', transition: 'all .2s' }}>
                {Ic({ width: 19, height: 19 })} {l}
              </button>
            ))}
            <button onClick={() => { signOut(); nav('home'); }} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', padding: '12px 14px', borderRadius: 'var(--r-md)', fontSize: 14.5, color: 'var(--blush)', marginTop: 8 }}>
              <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
              Sign out
            </button>
          </div>
        </aside>

        <div>
          {tab === 'orders' && (
            orders.length === 0 ? (
              <Empty icon={I.truck} title="No orders yet" sub="Once you place an order, you can track it from here — every step from received to delivered." cta="Start shopping" onCta={() => nav('shop')} />
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
                {orders.map(o => <OrderCard key={o.num} order={o} />)}
              </div>
            )
          )}
          {tab === 'wishlist' && (
            wishProducts.length === 0 ? (
              <Empty icon={I.heart} title="Your wishlist is empty" sub="Tap the heart on any product to save it for later." cta="Browse products" onCta={() => nav('shop')} />
            ) : (
              <div className="prod-grid">{wishProducts.map((p, i) => <ProductCard key={p.id} p={p} delay={(i % 4) + 1} />)}</div>
            )
          )}
          {tab === 'details' && (
            <div style={{ background: 'var(--ivory)', borderRadius: 'var(--r-lg)', padding: 28, boxShadow: 'var(--shadow-sm)', maxWidth: 560 }}>
              <h3 style={{ fontSize: 24, marginBottom: 20 }}>Account details</h3>
              <div className="form-row" style={{ marginBottom: 16 }}>
                <div className="field"><label>First name</label><input className="input" defaultValue={user.firstName} /></div>
                <div className="field"><label>Last name</label><input className="input" defaultValue={user.lastName} /></div>
              </div>
              <div className="field" style={{ marginBottom: 16 }}><label>Email</label><input className="input" defaultValue={user.email} /></div>
              <div className="field" style={{ marginBottom: 22 }}><label>Phone</label><input className="input" defaultValue={user.phone || ''} /></div>
              <button className="btn btn-primary">Save changes</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function OrderCard({ order }) {
  const status = order.status || 1;
  const date = new Date(order.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
  return (
    <div style={{ background: 'var(--ivory)', borderRadius: 'var(--r-lg)', padding: 'clamp(20px,3vw,28px)', boxShadow: 'var(--shadow-sm)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 12, marginBottom: 22 }}>
        <div>
          <div style={{ fontFamily: 'var(--serif)', fontSize: 24 }}>Order #{order.num}</div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-soft)' }}>Placed {date} · {BB.fmt(order.subtotal + (order.shipping || 0), order.currency)}</div>
        </div>
        <span className="chip active" style={{ cursor: 'default' }}>{STATUS_STEPS[status]}</span>
      </div>

      {/* status tracker */}
      <div className="status-track">
        {STATUS_STEPS.map((s, i) => (
          <div key={s} className="status-node">
            <div className="status-line" style={{ background: i <= status ? 'var(--sage)' : 'var(--line)', visibility: i === 0 ? 'hidden' : 'visible' }} />
            <span style={{ width: 30, height: 30, borderRadius: 100, display: 'grid', placeItems: 'center', flexShrink: 0, zIndex: 1, background: i < status ? 'var(--sage)' : i === status ? 'var(--gold)' : 'var(--cream-deep)', color: i <= status ? '#fff' : 'var(--ink-faint)', boxShadow: i === status ? '0 0 0 5px var(--gold-soft)' : 'none', transition: 'all .3s' }}>
              {i < status ? <I.check width={15} height={15} /> : <span style={{ width: 7, height: 7, borderRadius: 100, background: 'currentColor' }} />}
            </span>
            <span style={{ fontSize: 11.5, marginTop: 8, color: i <= status ? 'var(--ink)' : 'var(--ink-faint)', fontWeight: i === status ? 600 : 400, textAlign: 'center', lineHeight: 1.2 }}>{s}</span>
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', gap: 10, marginTop: 22, paddingTop: 18, borderTop: '1px solid var(--line)', flexWrap: 'wrap' }}>
        {order.lines.map((l, i) => (
          <span key={i} style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{l.qty} × {l.name}{i < order.lines.length - 1 ? '  ·' : ''}</span>
        ))}
      </div>
    </div>
  );
}

function Empty({ icon, title, sub, cta, onCta }) {
  return (
    <div style={{ background: 'var(--ivory)', borderRadius: 'var(--r-lg)', padding: 'clamp(40px,7vw,72px) 28px', textAlign: 'center', boxShadow: 'var(--shadow-sm)' }}>
      {icon({ width: 46, height: 46, style: { opacity: .3, margin: '0 auto 16px' } })}
      <h3 style={{ fontSize: 28 }}>{title}</h3>
      <p className="muted" style={{ marginTop: 10, maxWidth: 380, marginInline: 'auto', fontSize: 15 }}>{sub}</p>
      <button className="btn btn-gold" style={{ marginTop: 24 }} onClick={onCta}>{cta}</button>
    </div>
  );
}

Object.assign(window, { AccountPage, STATUS_STEPS });
