let {Switch,Route,useHistory,useParams,useRouteMatch,useLocation } = ReactRouterDOM;
const {Container,Row,Col,Table,Form,Image,OverlayTrigger,Tooltip,Button} = ReactBootstrap;
const _functions = FunctionsApp()

function Home({state,updateState}) {
	const {arrCategoriesProducts} = state;
	let { id } = useParams();
	const history = useHistory();

	return (
	<div>
		<NavbarTop state={state} updateState={updateState.bind(this)} />
		<div style={{marginTop:'70px'}}>
			<Anouncement state={state} updateState={updateState.bind(this)} />
			<Carousel state={state} updateState={updateState.bind(this)} />

			<Row>
				<Col onClick={() => { history.push('/productos/5f6cabb395fde'); }} style={{ position: 'relative', textAlign: 'center', marginBottom: 10, }}>
					<p className={`ws__products_title`}>RES</p>
					<img className={'ws__products_view'} src={'https://hg.wsoft.com.mx/imgs/product1@2x.png'} />
				</Col>
				<Col onClick={() => { history.push('/productos/5f6cabdd4bc14'); }} style={{ position: 'relative', textAlign: 'center', marginBottom: 10, }}>
					<p className={`ws__products_title`}>CERDO</p>
					<img className={'ws__products_view'} src={'https://hg.wsoft.com.mx/imgs/product2@2x.png'} />
				</Col>
			</Row>
			<Row>
				<Col onClick={() => { history.push('/productos/5f6cabe442592'); }} style={{ position: 'relative', textAlign: 'center', marginBottom: 10, }}>
					<p className={`ws__products_title`}>POLLO</p>
					<img className={'ws__products_view'} src={'https://hg.wsoft.com.mx/imgs/product3@2x.png'} />
				</Col>
				<Col onClick={() => { history.push('/productos/5f6cac034c14f'); }} style={{ position: 'relative', textAlign: 'center', marginBottom: 10, }}>
					<p className={`ws__products_title`}>ABARROTES</p>
					<img className={'ws__products_view'} src={'https://hg.wsoft.com.mx/imgs/product4@2x.png'} />
				</Col>
			</Row>
		</div> 
	</div>
	);
}

function ProductosList({state,updateState}) {
	const { arrCategoriesProducts, } = state;
	let { id_categoria } = useParams();
	const history = useHistory();

	let arrItem, indexItem = -1;
	arrCategoriesProducts.map((t, e) => {

		if(t.id_categoria === id_categoria) {
			indexItem = e;
			arrItem = t;
		}
	})

	return (
		<div>
			<NavbarTop state={state} updateState={updateState.bind(this)} />
			<div style={{marginTop:'70px'}}>
				<Anouncement state={state} updateState={updateState.bind(this)} />

				{
					( arrItem.productos.length > 0 )
					? <Category state={state} updateState={updateState.bind(this)} title={arrItem.nombre} productos={arrItem.productos} indexCategoria={indexItem} />
					: <p onClick={() => { history.push('/') }}>No se encontraron productos. Haz clic para regresar</p>
				}
				<Footer state={state} updateState={updateState.bind(this)} />
			</div> 
		</div>
	);
}

function Categorias({state,updateState}){
	let { path, url } = useRouteMatch();
	return(
	<div>
	    <Switch>
	    	<Route path={`${path}/:topicId`}>
	    		<ViewCategoria state={state} updateState={updateState} />
	    	</Route>
	    </Switch>
	</div>
	)
}

function ViewCategoria({state,updateState}) {
  	let { topicId } = useParams();
  	const {arrCategoriesProducts} = state;
  	return (
    <div>
    	<NavbarTop state={state} updateState={updateState} />
    	<div style={{marginTop:'70px'}}>
	    	<Anouncement state={state} updateState={updateState} />
	    	{/*<Carousel state={state} updateState={updateState} />*/}
	      	<CategoriesList state={state} updateState={updateState.bind(this)} organizador={true} />
			{
				(arrCategoriesProducts.length>0) ?
				arrCategoriesProducts.map((category,index) => (
					(category.id_categoria==topicId) ?
					<Category state={state} updateState={updateState.bind(this)} title={category.nombre} productos={category.productos} indexCategoria={index} />
					:
					null
				))
				:
				null
			}
		</div>
		<Footer state={state} updateState={updateState} />
    </div>
  	);
}

function Carrito({state,updateState}){
	let { arrCategoriesProducts, carritoProductos, porcDesc, } = state

	if(carritoProductos.length === 0) {
		window.location = '/'
	}

	let total = 0, descuento = porcDesc;
	carritoProductos.map((t0,e0) => {
		total += t0.cantidad * t0.precio_venta
	});

	return(
		<div>
			<NavbarTop state={state} updateState={updateState} />
			<div style={{marginTop:'70px'}}>
				<Anouncement state={state} updateState={updateState} />
				<Container className="mt-4" style={{minHeight:'450px'}}>
					<Row>
						<Col xs={12}>
							<h1 className="ws_text_2 mb-3">Carrito</h1>
							<Table responsive>
								<thead>
									<tr>
										<th></th>
										<th>PRODUCTO</th>
										<th>PRECIO</th>
										<th>CANTIDAD</th>
										<th></th>
										<th>TOTAL</th>
									</tr>
								</thead>

								<tbody className="ws_tbody_text">
									{
										carritoProductos.map((t,e) => (
											<tr>
												<td></td>
												<td><p className="mb-0 pt-3 pb-3">{t.nombre}</p></td>
												<td><p className="mb-0 pt-3 pb-3">${number_format(t.precio_venta)}</p></td>
												<td>
													<div className="mb-0 pt-3 pb-3 d-flex justify-content-between align-self-center ws_box_select_q">
														<span
															onClick={ () => {
																if(carritoProductos[e].cantidad > 1) {
																	carritoProductos[e].cantidad = (carritoProductos[e].cantidad - 1)
																	updateState({carritoProductos})
																}
															}}
														>-</span>
														<span>{t.cantidad}</span>
														<span
															onClick={ () => {
																carritoProductos[e].cantidad = (carritoProductos[e].cantidad + 1)
																updateState({carritoProductos})
															}}
														>+</span>
													</div>
												</td>
												<td><p
													onClick={ () => {
														let newArr = []
														arrCategoriesProducts[t.indexCategoria].productos[t.index].active = false
														carritoProductos.map((t0,e0) => {
															if(e0 != e)
																newArr.push(t0)
														})

														carritoProductos = newArr
														updateState({carritoProductos})
													}}
												className="mb-0 pt-3 pb-3 btn w_c_1">ELIMINAR</p></td>
												<td><p className="mb-0 pt-3 pb-3">${number_format(t.cantidad * t.precio_venta)}</p></td>
											</tr>
										))
									}

								</tbody>
							</Table>
							<div style={{float:'right'}}>
								<h4>SUBTOTAL: ${
									number_format(total)
								}</h4>
								<h4>DESCUENTO: ${number_format(total * descuento)}</h4>
								<h4>TOTAL: ${number_format( total - (total * descuento) )} </h4>
								<p className="mb-3 ws_text_3">Los gatos de envio se calculan durante el pago</p>
								<p className="mb-3 ws_text_3">Aplicar un código de descuento</p>

								{
									state.porcDesc > 0 ? (
										<Row>
										<Col>
											<p>CÓDIGO: {state.code}</p>
										</Col>
										<Col>
											<button className="btn ws_button w-100 mb-3 pt-2 pb-2" onClick={() => { updateState({ porcDesc: 0, }) }}>Remover</button>
										</Col>
									</Row>
									) : (
									<Row>
										<Col>
											<input value={state.code} type={'text'} onChange={(e) => { updateState({ code: e.target.value, }); }} placeholder={'Ingresa un código aquí.'} />
										</Col>
										<Col>
											<button className="btn ws_button w-100 mb-3 pt-2 pb-2" onClick={() => { onValidateCode(state, updateState) }}>Validar</button>
										</Col>
									</Row>
									)
								}
								<Link className="btn ws_button w-100 mb-3 pt-2 pb-2" to="/pago">Pagar</Link>
								<Link className="btn ws_button2 w-100 w_b_2 pt-2 pb-2 mb-4" to="/">Seguir Comprando</Link>
							</div>
						</Col>
					</Row>
				</Container>
			</div>
			<Footer state={state} updateState={updateState} />
		</div>
	)
}

function onValidateCode(state,updateState) {
	let { code } = state

	if(!code || code === '') {
		alert('No haz ingresado un código.')
		return false
	} else {

		_functions.fetch('validarCodePromocion', {
			code,
		}, (res) => {
				console.log(res)
			if(res.stat) {
				if(!res.response.status) {
					alert('El código introducido no fue encontrado o ya expiró.')
					return false
				} else {
					updateState({ porcDesc: res.response.descuento / 100, })
				}
			}
		})

	}

}

function Pago({state,updateState}){
	let {stepPagos,addCard,arrDatos, carritoProductos, loginNumber, proccessPayment, porcDesc, } = state;
	let total = 0, descuento = porcDesc;

	if(carritoProductos.length === 0) {
		window.location = '/'
	}

	carritoProductos.map((t0,e0) => {
		total += t0.cantidad * t0.precio_venta
	});

	return(
		<div>
			<NavbarTop state={state} updateState={updateState} />
			<div style={{marginTop:'70px'}}>
				<Container fluid>
					<Row>
						<Col xs={12} sm={6} className="" style={{paddingLeft:'0px',paddingRight:'0px'}}>

							<div className="ws_header_payment" style={{paddingLeft:'40px',paddingBottom:'20px'}}>
								<Image src={`${urlPath}/imgs/logo-header.svg`} style={{width:'120px'}} />
								<p>{`Paso ${stepPagos} de 4`}</p>
								<h3 className="ws_text_4">
									{
										stepPagos==='validateCode' ?
										'Validando mi usuario'
										: stepPagos===1 ?
										'Información de Contacto'
										: stepPagos === 2 ?
										'Datos de entrega'
										: stepPagos === 3 ?
										'Selecciona el método de pago'
										:
										null
									}
								</h3>
							</div>

							<div className="mt-5" style={{paddingBottom:'65px'}}>
								{
								stepPagos===1 ?
								<div style={{paddingLeft:'30px'}}>
									<p className="w-40 mb-0 d-inline-block">¿Ya estás registrado?</p>
									<p className="w-60 mb-0 d-inline-block w_c_1 c_pointer">Inicia sesión con tu teléfono</p>
								</div>
								:
								null
								}
								{
								stepPagos==='validateCode' ?
								<div style={{paddingLeft:'30px'}}>
									<p className="w-40 mb-0 d-inline-block">Confirma el código enviado</p>
								</div>
								:
								null
								}
								<Container>
								<Row>
									<Col xs={ 12 } sm={12} lg={(stepPagos===3||stepPagos===4) ? 12 : 6}>
										{
											stepPagos === 'validateCode' ? 
											<Form>
												<Form.Group controlId="frmRegistro" className="pt-4 pb-4" style={{position:'relative'}}>
													<Form.Label>
													<OverlayTrigger
								            placement="right"
								            delay={{ show: 250, hide: 400 }}
								            overlay={ <Tooltip>Se te ha enviado un código a tu whatsapp</Tooltip> }
								          >
													<span class="ws_img_info"><Image src={`${urlPath}/imgs/info-icon.svg`} alt="info" /></span>
													</OverlayTrigger>
													&nbsp;Código</Form.Label>
													<Form.Control value={state.loginCode} className="ws-control" type="text" placeholder="Escribe el código de 4 dígitos" required
													onChange={
															(e) => {
																updateState({loginCode: e.target.value})
															}
														}
													/>
													<span className="ws_show_iconfc" style={{position:'absolute',right:'-35px',top:'39px'}}></span>
												</Form.Group>

												<Form.Group controlId="frmButtonGuardar" className="mb-3">
													<Button variant="primary ws_button2 w_b_2 w-100 wb-0 pt-2 pb-2"
													disabled={(state.submitForm) ? true : false }
													onClick={
														(e) => {
															getValidateCode(state, updateState)
														}
													}
													>Confirmar código</Button>
												</Form.Group>
											</Form>
											: stepPagos===1?
											<Form>
												<Form.Group controlId="frmRegistro" className="pt-4 pb-4" style={{position:'relative'}}>
													<Form.Label>
													<OverlayTrigger
								            placement="right"
								            delay={{ show: 250, hide: 400 }}
								            overlay={ <Tooltip>Agrega tu whatsapp</Tooltip> }
								          >
													<span class="ws_img_info"><Image src={`${urlPath}/imgs/info-icon.svg`} alt="info" /></span>
													</OverlayTrigger>
													&nbsp;Teléfono</Form.Label>
													<Form.Control className="ws-control" id="telefono" type="phone" placeholder="Introduce tu teléfono" required
													onChange={
														(e)=>{
															updateState({ loginNumber: e.target.value, })
														}
													} 
													/>
													<span className="ws_show_iconfc" style={{position:'absolute',right:'-35px',top:'39px'}}></span>
												</Form.Group>

												<Form.Group controlId="frmButtonGuardar" className="mb-3">
													<Button variant="primary ws_button2 w_b_2 w-100 wb-0 pt-2 pb-2"
													disabled={(state.submitForm) ? true : false }
													onClick={
														(e) => {
															getValidateLogin(state, updateState)
														}
													}
													>Iniciar sesión</Button>
												</Form.Group>

												<Form.Group controlId="frmButtonGuardar" className="mb-3">
													<Button variant="primary ws_button2 w_b_2 w-100 wb-0 pt-2 pb-2"
													disabled={(state.submitForm) ? true : false }
													onClick={
														(e) => {
															updateState({
																stepPagos:2
															})
														}
													}
													>Soy nuevo</Button>
												</Form.Group>
											</Form>
											: stepPagos === 2 ?
											<Form>
												<Form.Group controlId="frmRegistro2" className="" style={{position:'relative'}}>
													<Form.Label>
													<OverlayTrigger
											            placement="right"
											            delay={{ show: 250, hide: 400 }}
											            overlay={ <Tooltip>Agrega tu nombre</Tooltip> }
											          >
													<span class="ws_img_info"><Image src={`${urlPath}/imgs/info-icon.svg`} alt="info" /></span>
													</OverlayTrigger>
													&nbsp;Nombre</Form.Label>
													<Form.Control className="ws-control" id="nombre" type="text" placeholder="Introduce tu nombre" required
													onChange={
														(e)=>{
															console.log(e.target.oldValue)
														}
													} 
													/>
													<span className="ws_show_iconfc" style={{position:'absolute',right:'-35px',top:'39px'}}></span>
												</Form.Group>

												<Form.Group controlId="frmRegistro2" className="pt-2" style={{position:'relative'}}>
													<Form.Label>
													<OverlayTrigger
											            placement="right"
											            delay={{ show: 250, hide: 400 }}
											            overlay={ <Tooltip>Agrega tus apellidos</Tooltip> }
											          >
													<span class="ws_img_info"><Image src={`${urlPath}/imgs/info-icon.svg`} alt="info" /></span>
													</OverlayTrigger>
													&nbsp;Apellidos</Form.Label>
													<Form.Control className="ws-control" id="apellidos" type="text" placeholder="Introduce tu apellidos" required
													onChange={
														(e)=>{
															console.log(e.target.oldValue)
														}
													} 
													/>
													<span className="ws_show_iconfc" style={{position:'absolute',right:'-35px',top:'39px'}}></span>
												</Form.Group>

												<Form.Group controlId="frmRegistro2" className="pt-2" style={{position:'relative'}}>
													<Form.Label>
													<OverlayTrigger
											            placement="right"
											            delay={{ show: 250, hide: 400 }}
											            overlay={ <Tooltip>Agrega tu dirección</Tooltip> }
											          >
													<span class="ws_img_info"><Image src={`${urlPath}/imgs/info-icon.svg`} alt="info" /></span>
													</OverlayTrigger>
													&nbsp;Dirección</Form.Label>
													<Form.Control className="ws-control" id="direccion" type="text" placeholder="Introduce tu dirección" required
													onChange={
														(e)=>{
															console.log(e.target.oldValue)
														}
													} 
													/>
													<span className="ws_show_iconfc" style={{position:'absolute',right:'-35px',top:'39px'}}></span>
												</Form.Group>

												<Form.Group controlId="frmRegistro2" className="pt-2" style={{position:'relative'}}>
													<Form.Label>
													<OverlayTrigger
											            placement="right"
											            delay={{ show: 250, hide: 400 }}
											            overlay={ <Tooltip>Agrega tu ciudad</Tooltip> }
											          >
													<span class="ws_img_info"><Image src={`${urlPath}/imgs/info-icon.svg`} alt="info" /></span>
													</OverlayTrigger>
													&nbsp;Ciudad</Form.Label>
													<Form.Control className="ws-control" id="ciudad" type="text" placeholder="Introduce tu ciudad" required
													onChange={
														(e)=>{
															console.log(e.target.oldValue)
														}
													} 
													/>
													<span className="ws_show_iconfc" style={{position:'absolute',right:'-35px',top:'39px'}}></span>
												</Form.Group>

												<Form.Group controlId="frmRegistro2" className="pt-2" style={{position:'relative'}}>
													<Form.Label>
													<OverlayTrigger
											            placement="right"
											            delay={{ show: 250, hide: 400 }}
											            overlay={ <Tooltip>Agrega tu estado</Tooltip> }
											          >
													<span class="ws_img_info"><Image src={`${urlPath}/imgs/info-icon.svg`} alt="info" /></span>
													</OverlayTrigger>
													&nbsp;Estado</Form.Label>
													<Form.Control className="ws-control" id="estado" type="text" placeholder="Introduce tu estado" required
													onChange={
														(e)=>{
															console.log(e.target.oldValue)
														}
													} 
													/>
													<span className="ws_show_iconfc" style={{position:'absolute',right:'-35px',top:'39px'}}></span>
												</Form.Group>

												<Form.Group controlId="frmRegistro2" className="pt-2" style={{position:'relative'}}>
													<Form.Label>
													<OverlayTrigger
											            placement="right"
											            delay={{ show: 250, hide: 400 }}
											            overlay={ <Tooltip>Agrega tu código postal</Tooltip> }
											          >
													<span class="ws_img_info"><Image src={`${urlPath}/imgs/info-icon.svg`} alt="info" /></span>
													</OverlayTrigger>
													&nbsp;CP</Form.Label>
													<Form.Control className="ws-control" id="cp" type="text" placeholder="Introduce tu código postal" required
													onChange={
														(e)=>{
															console.log(e.target.oldValue)
														}
													} 
													/>
													<span className="ws_show_iconfc" style={{position:'absolute',right:'-35px',top:'39px'}}></span>
												</Form.Group>

												<Form.Group controlId="frmRegistro2" className="pt-2" style={{position:'relative'}}>
													<Form.Label>
													<OverlayTrigger
											            placement="right"
											            delay={{ show: 250, hide: 400 }}
											            overlay={ <Tooltip>Agrega tu teléfono</Tooltip> }
											          >
													<span class="ws_img_info"><Image src={`${urlPath}/imgs/info-icon.svg`} alt="info" /></span>
													</OverlayTrigger>
													&nbsp;Teléfono</Form.Label>
													<Form.Control className="ws-control" id="telefono" type="text" placeholder="Introduce tu teléfono" required
													onChange={
														(e)=>{
															console.log(e.target.oldValue)
														}
													} 
													/>
													<span className="ws_show_iconfc" style={{position:'absolute',right:'-35px',top:'39px'}}></span>
												</Form.Group>

												<Form.Group controlId="frmButtonGuardar" className="mb-3 pt-3">
													<Button variant="primary ws_button2 w_b_2 w-100 wb-0 pt-2 pb-2"
													disabled={(state.submitForm) ? true : false }
													onClick={
														(e) => {
															updateState({
																stepPagos:3
															})
														}
													}
													>{(state.submitForm) ? 'Guardando datos...' : 'IR AL PAGO' }</Button>
												</Form.Group>
											</Form>
											: stepPagos === 3 ?
											
												addCard === 0 ?
												<div className="text-center" style={{padding:'40px 0px 10px 0px'}}>
													<h1 className="ws__text__t1">No tienes</h1>
													<h2 className="ws__text__t1">tarjetas registradas</h2>
													<img src={`${urlPath}/imgs/icon-card-plus.png`} className="ws__icon__card"/>
													<p className="ws__text__p1">Pero puedes agregar una</p>
													<button className="btn btn-primary btn__registro__sadett mb-4 pl-5 pr-5 ws__border__r10"
													onClick={
														(e) => {
															updateState({
																addCard:2
															})
														}
													}
													>
														Agregar tarjeta
													</button>
													<p className="ws__text__s1">o utiliza otros métodos de pago</p>
												</div>
												: addCard === 1 ?
												<div className="text-center" style={{padding:'40px 0px 10px 0px'}}>
													<form>
														<div class="form-check">
														  <input class="form-check-input" type="radio" name="card" id="card1" value="option1" checked />
														  <label class="form-check-label" for="card1" style={{displa:'flex',justifyContent:'center',alignItems:'center'}}>
														    <img src={'./img/icon-visa-b.png'} className="ws__icon__visa__b" /><span className="ws__text__visa">terminación 4567</span>
														  </label>
														</div>
														<div className="form-group pl-4 pr-4">
															<button className="btn btn-primary btn-block btn__registro__sadett mb-4 pl-5 pr-5 ws__border__r10 ws__button__s1 mt-5"
															onClick={
																(e) => {
																	updateState({addCard:2})
																}
															}
															>Agregar otra tarjeta</button>
														</div>
													</form>
												</div>
												: addCard === 2 ?
												<div className="text-left">
													<form id={'ws_payment_conekta'} className="text-left mt-2" style={{paddingBottom:'100px'}}>
														<div className="form-group mb-2">
															<label>Nombre del tajetahabiente</label>
															<input type="text"
																className="form-control"
																name="tarjetahabiente"
																value={arrDatos.tarjetahabiente}
																onChange={
																	(e) =>{
																		handleChange(e)
																	}
																}
																id="input_tarjetahabiente"
																autoComplete="off"
																placeholder="Nombre del tarjetahabiente"
																required
																autoFocus
																size="20"
																data-conekta="card[name]" />
														</div>
														<div className="form-group mb-2">
															<label>Correo</label>
															<input 
																className="form-control"
																type="text"
						                    name="correo"
						                    value={arrDatos.correo}
						                    onChange={
						                    	(e) => {
						                    		handleChange(e)
						                    	}
						                    }
						                    id="input_correo"
						                    autoComplete="off"
						                    placeholder="Escribe tu correo electrónico"
															/>
														</div>
														<div className="form-group mb-2">
															<label>Teléfono</label>
															<input 
																className="form-control"
																type="text"
						                    name="telefono"
						                    value={arrDatos.telefono}
						                    onChange={
						                    	(e) => {
						                    		handleChange(e)
						                    	}
						                    }
						                    id="input_telefono"
						                    autoComplete="off"
						                    placeholder="Escribe tu teléfono"
															/>
														</div>
														<div className="form-group mb-2">
															<label>Número de tarjeta</label>
															<input 
																className="form-control"
																type="text"
							                  name="numero"
							                  value={arrDatos.numero}
							                  onChange={
							                  	(e) => {
							                  		handleChange(e)
							                  	}
							                  }
							                  id="input_numero"
							                  autoComplete="off"
							                  placeholder="Número de tarjeta"
							                  required
							                  maxLength="20"
							                  data-conekta="card[number]"
							                />
														</div>
														<Row>
							                <Col md={4}>
							                  <div className="form-group mb-2">
							                    <label>Mes (MM)</label>
							                    <input
							                    className="form-control"
							                      type="text"
							                      name="month"
							                      value={arrDatos.month}
							                      onChange={
							                      	(e) => {
							                      		handleChange(e)
							                      	}
							                      }
							                      id="input_month"
							                      autoComplete="off"
							                      placeholder="Mes"
							                      required
							                      maxLength="2"
							                      data-conekta="card[exp_month]"
							                    />
							                  </div>
							                </Col>
							                <Col md={4}>
							                  <div className="form-group mb-2">
							                    <label>Año (YY)</label>
							                    <input
							                    className="form-control"
							                      type="text"
							                      name="year"
							                      value={arrDatos.year}
							                      onChange={
							                      	(e) => {
							                      		handleChange(e)
							                      	}
							                      }
							                      id="input_year"
							                      autoComplete="off"
							                      placeholder="Año"
							                      required
							                      maxLength="2"
							                      data-conekta="card[exp_year]"
							                    />
							                  </div>
							                </Col>
							                <Col md={4}>
							                  <div className="form-group mb-2">
							                    <label>CVC</label>
							                    <input
							                    className="form-control"
							                      type="password"
							                      name="cvc"
							                      value={arrDatos.cvc}
							                      onChange={
							                      	(e) => {
							                      		handleChange(e)
							                      	}
							                      }
							                      id="input_cvc"
							                      autoComplete="off"
							                      placeholder="CVC"
							                      required
							                      maxLength="4"
							                      data-conekta="card[cvc]"
							                    />
							                  </div>
							                </Col>
							              </Row>

														<div className="form-group pl-4 pr-4 pt-3">
															<button className="btn btn-primary btn-block ws_button2 w_b_2 w-100 wb-0 pt-2 pb-2"
															onClick={
																(e) => {
																	e.preventDefault();
																	procesarPago(state, updateState);
																}
															}
															>Procesar mi orden</button>
														</div>
													</form>
												</div>
												:
												null
											
											: stepPagos === 4 ?
											<div>
												<div style={{display:'flex'}}>
													<div className="container main-container" style={{height:'100%'}}>
														<div className="row">
															<div className="col-sm-12 col-md-12 col-lg-12 pb-12" style={{ margin: '0 auto', marginTop: 0, }}>
																{
																	(!proccessPayment) ?
																	<div className="text-center" style={{padding:'40px 0px 10px 0px'}}>
																		<h1 className="ws__text__t1">Tu pago se</h1>
																		<h2 className="ws__text__t1">está procesando...</h2>
																		<img src={'https://diana.wsoft.com.mx/pos/nutrisadettapp/img/icon-sadett-pay.png'} className="ws__icon__card"/>
																	</div>
																	: 
																	<div className="text-center" style={{padding:'40px 0px 10px 0px'}}>
																		<h1 className="ws__text__t1">¡Tu orden ha</h1>
																		<h2 className="ws__text__t1">sido creada con éxito!</h2>
																		<img src={'https://diana.wsoft.com.mx/pos/nutrisadettapp/img/icon-clock.png'} className="ws__icon__card"/>
																		<p className="ws__text__p1">Hemos enviado un comprobante de tu pago a tu Whatsapp</p>
																		<br />
																		{
																			state.id_order ? (
																				<a href="#" className="ws__text__s1"
																					onClick={() => {
																						window.location = `https://apis.nutriologasadett.com/?t=recipt&order=${state.id_order}`;
																					}}
																				>Ver recibo</a>
																			) : null
																		}
																	</div>
																}

															</div>
														</div>
													</div>

												</div>
											</div>
											:
											null
										}
									</Col>

								</Row>
								</Container>
							</div>
							
							
						</Col>
						<Col xs={6} className="d-none d-sm-block" style={{paddingLeft:'0px',paddingRight:'0px'}}>
							<div className="ws_sidebar_cp pb-4">
								{
									carritoProductos.map((t,e) => (
										<div className="d-flex justify-content-between align-items-center mb-2">
											<div>
												<Image src={`${t.image}`} className="ws_sidebar_cp_image" />
											</div>
											<div>
												<p className="mb-0 w_c_1">{t.nombre}</p>
											</div>								
											<div>
												<p className="mb-0 w_c_1">${number_format(t.cantidad * t.precio_venta)}</p>
											</div>							
										</div>
									))
								}
								<div className="mt-4 ws_border_top_1 ws_border_bottom_2 pt-3 pb-3">
									<div className="d-inline-block w-50"><p className="mb-0" style={{textAlign:'right'}}>SUBTOTAL:</p></div>
									<div className="d-inline-block w-50"><p className="mb-0" style={{textAlign:'right'}}>${number_format(total)}</p></div>

									<div className="d-inline-block w-50 mt-2"><p className="mb-0" style={{textAlign:'right'}}>ENVÍO:</p></div>
									<div className="d-inline-block w-50"><p className="mb-0" style={{textAlign:'right'}}>${number_format(100)}</p></div>
								</div>

								<div className="mt-4 ws_border_bottom_1 pb-3">
									<div className="d-inline-block w-50"><p className="mb-0" style={{textAlign:'right'}}>TOTAL:</p></div>
									<div className="d-inline-block w-50"><p className="mb-0" style={{textAlign:'right'}}>${number_format( (total - (total * descuento) + 100) )}</p></div>
								</div>
							</div>
						</Col>
						{/*Display only in mobile*/}
						<Col xs={12} className="d-block d-sm-none ws_carrito_m" style={{borderTop:'1px solid rgb(210 210 210)',paddingTop:'5px',paddingBottom:'5px',boxShadow:'0px 2px 5px rgb(0 0 0 / 30%)'}}>
							<div className="d-flex justify-content-center align-items-start flex-column">
								<p className="mb-0">Total</p>
								<p className="mb-0">${number_format( total - (total * descuento) )}</p>
							</div>
						</Col>	
					</Row>
				</Container>
			</div>
		</div>
	)

	function procesarPago(state, updateState) {

		//Primero pasa por el procesar pago
		updateState({ stepPagos: 4, proccessPayment: false, })
		const $form = document.getElementById('ws_payment_conekta')
		Conekta.Token.create($form,
		({id, object, used}) => {
			if(object === 'token') {
				_functions.fetch('setRegisterOrder', {
					token_conekta: id,
					arrDatos: state.arrDatos,
					code: 'DESCUENTOCITA',
					arrProductos: carritoProductos,
				}, (res) => {
					if(res.stat) {
						setTimeout(() => {
							updateState({ proccessPayment: true, id_order: res.response.id_order, })
						}, 1000)
					}
				})
			}

		},
		(err) => {
			if(err.object === 'error') {
				alert(`Error: ${err.message_to_purchaser}`)
				updateState({
					stepPagos: 3,
					proccessPayment: false,
				})
				return false
			}
		});
	}

	function getValidateLogin(state, updateState) {
		const { loginNumber } = state

		_functions.fetch('existPhonePatient', { phone: loginNumber, }, (res) => {
			const { response } = res
			if(res.stat) {
				if( !response.status ) {
					alert( 'Lo sentimos, este número de teléfono no se encuentra en los registros.' )
					return false
				}

				updateState({ loginStep: 0, })
				setTimeout(() => {
					updateState({ stepPagos: 'validateCode', loginToken: response.token, })
				}, 1500)
			}
		})
	}

	function getValidateCode(state, updateState) {
		const { loginToken, loginCode, loginIntent, } = state

		_functions.fetch('validateCodeLogin', { token: loginToken, code: loginCode, }, (res) => {
			const { response } = res
			if(res.stat) {
				if( !response.status ) {
					if(loginIntent >= 3) {
						alert( `Lo sentimos, no pudiste autentificar tu cuenta.\nSerás redireccionado al inicio` )
						window.location = `https://tienda.nutriologasadett.com`;
					} else {
						alert( `Lo sentimos, el código introducido no es válido.\nIntento: ${loginIntent} de 3.` )
					}
					updateState({ loginIntent: (loginIntent + 1) })
					return false
				} else {
					//Si es exitoso le precargamos su nombre.
					
					if(response.tarjeta.length > 0)
						arrDatos = { ...arrDatos, ...response.tarjeta[0] };
					if(response.patient.length > 0)
						arrDatos = { ...arrDatos, ...response.patient[0] };
					updateState({ arrDatos, stepPagos: 3, addCard: 2, })
				}
			}
		})

	}
	

	function handleChange(e){
		let { name, value } = e.target;
	    if (
	      name === "numero" ||
	      name === "telefono" ||
	      name === "cvc" ||
	      name === "month" ||
	      name === "year"
	    ) {
	      value = value.replace(/\D/, "");
	    }
	    arrDatos = {...arrDatos, [name]: value}
	    updateState({ arrDatos })
	}
}

//Barra de navegación principal
function NavbarTop({state,updateState}){
	const {Image,Nav,NavDropdown} = ReactBootstrap;
	const { showMenu, carritoProductos, } = state;
	let { path, url } = useRouteMatch(); 
	return(
		<div>
			<div className="ws_navbar_top d-none d-lg-flex">
				<div className="ws_navbar_top_logo">
					<Image src={`https://hg.wsoft.com.mx/imgs/logo-hg-color@2x.png`} className="ws_navbar_logo_c" />
				</div>
				<div className="ws_navbar_header_list d-flex justify-content-center">
				</div>
				<div className="ws_navbar_cart d-flex">
					<Nav defaultActiveKey="/home" as="ul" className="align-items-center">
					  {/*<Nav.Item as="li">
					    <Nav.Link href="#">Login</Nav.Link>
					  </Nav.Item>*/}
					</Nav>
					<Link to={`${carritoProductos.length > 0 ? '/carrito' : '/'}`} className="nav-link">
						<Image src={`${urlPath}/imgs/shoping-cart.svg`} className="ws_footer_social_icon" 
						onClick={
							(e) => {

							}
						}
						/>
					</Link>
					<p className="mb-0 align-self-center ws_cart_number">{carritoProductos.length}</p>
				</div>
			</div>
			<div className="ws_navbar_top d-bloc d-lg-none">
			{
				(showMenu) ? 
				<i class="fas fa-times fa-2x" onClick={ (e) => { updateState({ showMenu:false }) }} ></i>
				:
				<i class="fas fa-bars fa-2x"  onClick={ (e) => { updateState({ showMenu:true }) }} ></i>
			}
				<Image src={`https://hg.wsoft.com.mx/imgs/logo-hg-color@2x.png`} className="ws_navbar_logo_c" />
				
				<div className="d-flex">
					<Link to={`${carritoProductos.length > 0 ? '/carrito' : '/'}`} className="nav-link">
						<Image src={`${urlPath}/imgs/shoping-cart.svg`} className="ws_footer_social_icon ws-m-0" />
					</Link>
					<p className="mb-0 align-self-center ws_cart_number">{carritoProductos.length}</p>
				</div>
			</div>
			<div className={(showMenu) ? 'ws_backdrop_menu active' : 'ws_backdrop_menu' }>
				<div className={(showMenu) ? 'ws_mobile_menu active' : 'ws_mobile_menu'}>
					<p>Lista de menú</p>
				</div>
			</div>
		</div>	
	)
}
// Anuncio de descuentos
function Anouncement({state,updateState}){
	return(
		<div className="ws_anouncement">
			<p className="mb-0">{state.anouncement}</p>
		</div>
	)
}
//Carousel de imagenes
function Carousel({state,updateState}){
	var Carousel = ReactBootstrap.Carousel;
	return(
		<Carousel>
			<Carousel.Item>
				<img src={`https://hg.wsoft.com.mx/imgs/main-banner@2x.png`} alt="slide1" />
			</Carousel.Item>
			<Carousel.Item>
				<img src={`https://hg.wsoft.com.mx/imgs/main-banner@2x.png`} alt="slide2" />
			</Carousel.Item>
			<Carousel.Item>
				<img src={`https://hg.wsoft.com.mx/imgs/main-banner@2x.png`} alt="slide3" />
			</Carousel.Item>
		</Carousel>
	)
}
//Sección Categorias
function CategoriesList({state,updateState,organizador=false}){
	var Container = ReactBootstrap.Container;
	var Row = ReactBootstrap.Row;
	var Col = ReactBootstrap.Col;
	var Form = ReactBootstrap.Form;
	return(
		<Container className="pt-5 pb-5">
			<Row>
				<Col xs={12}>
					{
						(organizador) ?
						<div className="d-flex justify-content-end align-items-center">
							<h4 className="mb-0 ws_text_1">Organizar por:</h4>
							<Form>
								<Form.Select aria-label="Default select example" className="ws_select">
									<option value="1">Más vendidos</option>
									<option value="2">Alfabéticamente, A-Z</option>
									<option value="2">Alfabéticamente, Z-A</option>
									<option value="2">Precio mayor a menor</option>
									<option value="2">Precio menor a mayor</option>
								</Form.Select>
							</Form>
						</div>
						:
						<div>
							<h2 className="ws_title pb-4">Categorías</h2>
							<Row>
								{
								state.arrCategoriesList.map((category,index) => (
									<Col xs={12} md={6} lg={3} className={'pb-3'}>
										<div className="ws_categorie_box">
											<img src={category.src} alt={category.alt} />
										</div>
									</Col>
								))
								}
							</Row>
						</div>
					}
					<hr className="mt-4 mb-4 ws_separator"/>
				</Col>
			</Row>
		</Container>
	)
}
//Sección Categoria
function Category({state,updateState,title,productos, indexCategoria}) {
	var Container = ReactBootstrap.Container;
	var Row = ReactBootstrap.Row;
	var Col = ReactBootstrap.Col;
	return(
		<Container className="pb-5 mt-5">
			<Row>
				<Col xs={12}>
					<h2 className="ws_title pb-4 text-center">{title}</h2>
					<Row>
						{
							productos.map((producto,index) => (
								<Row xs={12} md={12} lg={12} className={'pb-3'} style={{ margin: '0 auto', }}>
									<Col xs={4} md={4} lg={4}>
										<img style={{ width: '100%', }} src={producto.image} alt={producto.id_producto} />
									</Col>
									<Col xs={8} md={8} lg={8}>
										<p className="ws_product_name">{producto.nombre}</p>
										<p className="ws_product_price">$ {producto.precio_venta}</p>
										<button
											onClick={() => { onAddProductToCarrito(state, updateState, indexCategoria, index); }}
										className={`btn ${producto.active ? 'btn-secondary' : 'ws_button'}`}>{ producto.active ? 'Quitar del carrito' : 'Agregar al carrito' }</button>
									</Col>
								</Row>
							))
						}
					</Row>
					<hr className="mt-4 mb-4 ws_separator"/>
				</Col>
			</Row>
		</Container>
	)
}

function onAddProductToCarrito(state, updateState, indexCategoria, index) {
	let { arrCategoriesProducts, carritoProductos, } = state;

	if(!arrCategoriesProducts[indexCategoria].productos[index].active) {
		//Se agrega
		arrCategoriesProducts[indexCategoria].productos[index].active = true
		arrCategoriesProducts[indexCategoria].productos[index].cantidad = 1;
		carritoProductos.push({
			...arrCategoriesProducts[indexCategoria].productos[index],
			indexCategoria,
			index,
		})
		updateState({
			carritoProductos,
			arrCategoriesProducts,
		})

	} else {
		let newArr = []
		arrCategoriesProducts[indexCategoria].productos[index].active = false
		carritoProductos.map((t,e) => {
			if(t.id_producto !== arrCategoriesProducts[indexCategoria].productos[index].id_producto)
				newArr.push(t)
		})

		carritoProductos = newArr;
		updateState({
			carritoProductos,
			arrCategoriesProducts,
		})
	}



}

function Footer({state,updateState}){
	const {Container,Row,Col,Image} = ReactBootstrap;
	return(
		<div style={{clear:'both',position:'relative',height:'211px',marginTop:'125px'}}>
			<div className="ws_footer">
				<Container>
					<Row>
						<Col xs={12}>
							<div className="ws_footer_content">
								<Image src={`${urlPath}/imgs/logow.png`} alt="logo-white" className="ws_footer_logo" />
								<div className="ws_footer_sections">
								</div>
								<div className="ws_footer_terms">
								</div>
								<div className="ws_footer_social_content">
									<Image src={`${urlPath}/imgs/footer-fb.png`} alt="logo-footer-fb" className="ws_footer_social_icon"/>
									<Image src={`${urlPath}/imgs/footer-ig.png`} alt="logo-footer-ig" className="ws_footer_social_icon"/>
								</div>
							</div>
						</Col>
					</Row>
				</Container>
			</div>
			<div className="ws_footer_bottom">
				<Container>
					<Row>
						<Col xs={12} className="text-center">
							<p className="mb-1">©2021, Carnicerías Hermanos Gonzalez, All Rights Reserved</p>
							<p className="mb-0">Powered by W Soft</p>
						</Col>
					</Row>
				</Container>
			</div>
		</div>
	)
}

function number_format(number, decimals, decPoint, thousandsSep) {
	number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
	var n = !isFinite(+number) ? 0 : +number
	var prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
	var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
	var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
	var s = ''
	var toFixedFix = function (n, prec) {
		var k = Math.pow(10, prec)
		return '' + (Math.round(n * k) / k)
		.toFixed(prec)
	}
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
	if (s[0].length > 3) {
		s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
	}
	if ((s[1] || '').length < prec) {
		s[1] = s[1] || ''
		s[1] += new Array(prec - s[1].length + 1).join('0')
	}
	return s.join(dec)
}